Programs & Examples On #Signal strength

How to calculate distance from Wifi router using Signal Strength?

To calculate the distance you need signal strength and frequency of the signal. Here is the java code:

public double calculateDistance(double signalLevelInDb, double freqInMHz) {
    double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(signalLevelInDb)) / 20.0;
    return Math.pow(10.0, exp);
}

The formula used is:

distance = 10 ^ ((27.55 - (20 * log10(frequency)) + signalLevel)/20)

Example: frequency = 2412MHz, signalLevel = -57dbm, result = 7.000397427391188m

This formula is transformed form of Free Space Path Loss(FSPL) formula. Here the distance is measured in meters and the frequency - in megahertz. For other measures you have to use different constant (27.55). Read for the constants here.

For more information read here.

How can I jump to class/method definition in Atom text editor?

I believe the problem with "go to" packages is that they would work diferently for each language.

If you use Javascript js-hyperclick and hyperclick (since code-links is deprecated) may do what you need.


Use symbols-view package which let your search and jump to functions declaration but just of current opened file. Unfortunately, I don't know of any other language's equivalent.

There is also another package which could be useful for go-to in Python: python-tools

As of May 2016, recent version of Atom now support "Go-To" natively. At the GitHub repo for this module you get a list of the following keys:

  • symbols-view:toggle-file-symbols to Show all symbols in current file
  • symbols-view:toggle-project-symbols to Show all symbols in the project
  • symbols-view:go-to-declaration to Jump to the symbol under the cursor
  • symbols-view:return-from-declaration to Return from the jump

screenshot

I now only have one thing missing with Atom for this: mouse click bindings. There's an open issue on Github if anyone want to follow that feature.

MySQL LIKE IN()?

Just a little tip:

I prefer to use the variant RLIKE (exactly the same command as REGEXP) as it sounds more like natural language, and is shorter; well, just 1 char.

The "R" prefix is for Reg. Exp., of course.

Angular 2 @ViewChild annotation returns undefined

This works for me, see the example below.

_x000D_
_x000D_
import {Component, ViewChild, ElementRef} from 'angular2/core';_x000D_
_x000D_
@Component({_x000D_
    selector: 'app',_x000D_
    template:  `_x000D_
        <a (click)="toggle($event)">Toggle</a>_x000D_
        <div *ngIf="visible">_x000D_
          <input #control name="value" [(ngModel)]="value" type="text" />_x000D_
        </div>_x000D_
    `,_x000D_
})_x000D_
_x000D_
export class AppComponent {_x000D_
_x000D_
    private elementRef: ElementRef;_x000D_
    @ViewChild('control') set controlElRef(elementRef: ElementRef) {_x000D_
      this.elementRef = elementRef;_x000D_
    }_x000D_
_x000D_
    visible:boolean;_x000D_
_x000D_
    toggle($event: Event) {_x000D_
      this.visible = !this.visible;_x000D_
      if(this.visible) {_x000D_
        setTimeout(() => { this.elementRef.nativeElement.focus(); });_x000D_
      }_x000D_
    }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

For making the application & its multiple instance you can directly add this line then you can able to install the multiple application with same package name every time just modify the application id:

Example : application id : XXXX.123 (Old or existing one which is installed in phone)

Now make application id as : XXX.1234 and install the app.

Format:

<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>
<permission
    android:name="${applicationId}.permission.C2D_MESSAGE"
    android:protectionLevel="signature"/>

How do you add a timer to a C# console application

I suggest you following Microsoft guidelines ( https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer.interval?view=netcore-3.1).

I first tried using System.Threading; with

var myTimer = new Timer((e) =>
{
   // Code
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

but it continuously stopped after ~20 minutes.

With that, I tried the solutions setting

GC.KeepAlive(myTimer)

or

for (; ; ) { }
}

but they didn't work in my case.

Following Microsoft documentation, it worked perfectly:

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
// The example displays output like the following: 
//       Press the Enter key to exit the program at any time... 
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM 

How do I catch a numpy warning like it's an exception (not just for testing)?

To add a little to @Bakuriu's answer:

If you already know where the warning is likely to occur then it's often cleaner to use the numpy.errstate context manager, rather than numpy.seterr which treats all subsequent warnings of the same type the same regardless of where they occur within your code:

import numpy as np

a = np.r_[1.]
with np.errstate(divide='raise'):
    try:
        a / 0   # this gets caught and handled as an exception
    except FloatingPointError:
        print('oh no!')
a / 0           # this prints a RuntimeWarning as usual

Edit:

In my original example I had a = np.r_[0], but apparently there was a change in numpy's behaviour such that division-by-zero is handled differently in cases where the numerator is all-zeros. For example, in numpy 1.16.4:

all_zeros = np.array([0., 0.])
not_all_zeros = np.array([1., 0.])

with np.errstate(divide='raise'):
    not_all_zeros / 0.  # Raises FloatingPointError

with np.errstate(divide='raise'):
    all_zeros / 0.  # No exception raised

with np.errstate(invalid='raise'):
    all_zeros / 0.  # Raises FloatingPointError

The corresponding warning messages are also different: 1. / 0. is logged as RuntimeWarning: divide by zero encountered in true_divide, whereas 0. / 0. is logged as RuntimeWarning: invalid value encountered in true_divide. I'm not sure why exactly this change was made, but I suspect it has to do with the fact that the result of 0. / 0. is not representable as a number (numpy returns a NaN in this case) whereas 1. / 0. and -1. / 0. return +Inf and -Inf respectively, per the IEE 754 standard.

If you want to catch both types of error you can always pass np.errstate(divide='raise', invalid='raise'), or all='raise' if you want to raise an exception on any kind of floating point error.

How to get Maven project version to the bash command line

Just for the record, it's possible to configure Maven's Simple SLF4J logging directly in the command line to output only what we need by configuring:

  • org.slf4j.simpleLogger.defaultLogLevel=WARN and
  • org.slf4j.simpleLogger.log.org.apache.maven.plugins.help=INFO

as documented at http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html

MAVEN_OPTS="\
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.plugins.help=INFO" \
mvn help:evaluate -o -Dexpression=project.version

As a result, one can run simply tail -1 and get:

$ MAVEN_OPTS="\
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.plugins.help=INFO" \
mvn help:evaluate -o -Dexpression=project.version | tail -1

1.0.0-SNAPSHOT

Note that this is a one-liner. MAVEN_OPTS are being rewritten only for this particular mvn execution.

is there any alternative for ng-disabled in angular2?

For angular 4+ versions you can try

<input [readonly]="true" type="date" name="date" />

What is resource-ref in web.xml used for?

You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.

<resource-ref> introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.

So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB name. The container finds that web.xml has a <resource-ref> element for jdbc/primaryDB, so it will look into the container-specific configuration, that contains something similar to the following:

<resource-ref>
  <res-ref-name>jdbc/primaryDB</res-ref-name>
  <jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>

Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer.

The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Solution without charts

Function SelectionToPicture(nome)

'save location ( change if you want )
FName = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & nome & ".jpg"

'copy selection and get size
Selection.CopyPicture xlScreen, xlBitmap
w = Selection.Width
h = Selection.Height



With ThisWorkbook.ActiveSheet

    .Activate

    Dim chtObj As ChartObject
    Set chtObj = .ChartObjects.Add(100, 30, 400, 250)
    chtObj.Name = "TemporaryPictureChart"

    'resize obj to picture size
    chtObj.Width = w
    chtObj.Height = h

    ActiveSheet.ChartObjects("TemporaryPictureChart").Activate
    ActiveChart.Paste

    ActiveChart.Export FileName:=FName, FilterName:="jpg"

    chtObj.Delete

End With
End Function

How do I perform a JAVA callback between classes?

Use the observer pattern. It works like this:

interface MyListener{
    void somethingHappened();
}

public class MyForm implements MyListener{
    MyClass myClass;
    public MyForm(){
        this.myClass = new MyClass();
        myClass.addListener(this);
    }
    public void somethingHappened(){
       System.out.println("Called me!");
    }
}
public class MyClass{
    private List<MyListener> listeners = new ArrayList<MyListener>();

    public void addListener(MyListener listener) {
        listeners.add(listener);
    }
    void notifySomethingHappened(){
        for(MyListener listener : listeners){
            listener.somethingHappened();
        }
    }
}

You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.

This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.

In my example:

MyClass is the producer here as its notifying a list of listeners.

MyListener is the interface.

MyForm is interested in when somethingHappened, so it is implementing MyListener and registering itself with MyClass. Now MyClass can inform MyForm about events without directly referencing MyForm. This is the strength of the observer pattern, it reduces dependency and increases reusability.

How do you add multi-line text to a UIButton?

These days, if you really need this sort of thing to be accessible in interface builder on a case-by-case basis, you can do it with a simple extension like this:

extension UIButton {
    @IBInspectable var numberOfLines: Int {
        get { return titleLabel?.numberOfLines ?? 1 }
        set { titleLabel?.numberOfLines = newValue }
    }
}

Then you can simply set numberOfLines as an attribute on any UIButton or UIButton subclass as if it were a label. The same goes for a whole host of other usually-inaccessible values, such as the corner radius of a view's layer, or the attributes of the shadow that it casts.

Number of days in particular month of particular year?

Number of days in particular year - Java 8+ solution

Year.now().length()

How do you create different variable names while in a loop?

It's simply pointless to create variable variable names. Why?

  • They are unnecessary: You can store everything in lists, dictionarys and so on
  • They are hard to create: You have to use exec or globals()
  • You can't use them: How do you write code that uses these variables? You have to use exec/globals() again

Using a list is much easier:

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them

How to change the Eclipse default workspace?

If you want to change recent workspace manually in a configurationfile org.eclipse.ui.ide.prefs exists in

eclipse > configuration > .settings > org.eclipse.ui.ide.prefs

open this file in an editor find RECENT_WORKSPACES in line #2 and in this line you can see recent workspaces and can change or even remove them.

(Built-in) way in JavaScript to check if a string is a valid number

This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:

const isNumRegEx = /^-?(\d*\.)?\d+$/;

function isNumeric(n, allowScientificNotation = false) {
    return allowScientificNotation ? 
                !Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
                isNumRegEx.test(n);
}

How to redirect 'print' output to a file using python?

The easiest solution isn't through python; its through the shell. From the first line of your file (#!/usr/bin/python) I'm guessing you're on a UNIX system. Just use print statements like you normally would, and don't open the file at all in your script. When you go to run the file, instead of

./script.py

to run the file, use

./script.py > <filename>

where you replace <filename> with the name of the file you want the output to go in to. The > token tells (most) shells to set stdout to the file described by the following token.

One important thing that needs to be mentioned here is that "script.py" needs to be made executable for ./script.py to run.

So before running ./script.py,execute this command

chmod a+x script.py (make the script executable for all users)

Difference between $(this) and event.target?

Within an event handler function or object method, one way to access the properties of "the containing element" is to use the special this keyword. The this keyword represents the owner of the function or method currently being processed. So:

  • For a global function, this represents the window.

  • For an object method, this represents the object instance.

  • And in an event handler, this represents the element that received the event.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown() {
            alert(this);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown();alert(this);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object Window
object HTMLParagraphElement

An Event object is associated with all events. It has properties that provide information "about the event", such as the location of a mouse click in the web page.

For example:

<!DOCTYPE html>
<html>
    <head>
        <script>
        function mouseDown(event) {
            var theEvent = event ? event : window.event;
            var locString = "X = " + theEvent.screenX + " Y = " + theEvent.screenY;
            alert(event);
                    alert(locString);
        }
        </script>
    </head>
    <body>
        <p onmouseup="mouseDown(event);">Hi</p>
    </body>
</html>

The content of alert windows after rendering this html respectively are:

object MouseEvent
X = 982 Y = 329

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Uncheck "normalize CSS" - http://jsfiddle.net/qGCUk/3/ The CSS reset used in that defaults all list margins and paddings to 0

UPDATE http://jsfiddle.net/qGCUk/4/ - you have to include your sub-lists in your main <li>

_x000D_
_x000D_
ol {_x000D_
  counter-reset: item_x000D_
}_x000D_
li {_x000D_
  display: block_x000D_
}_x000D_
li:before {_x000D_
  content: counters(item, ".") " ";_x000D_
  counter-increment: item_x000D_
}
_x000D_
<ol>_x000D_
  <li>one</li>_x000D_
  <li>two_x000D_
    <ol>_x000D_
      <li>two.one</li>_x000D_
      <li>two.two</li>_x000D_
      <li>two.three</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
  <li>three_x000D_
    <ol>_x000D_
      <li>three.one</li>_x000D_
      <li>three.two_x000D_
        <ol>_x000D_
          <li>three.two.one</li>_x000D_
          <li>three.two.two</li>_x000D_
        </ol>_x000D_
      </li>_x000D_
    </ol>_x000D_
  </li>_x000D_
  <li>four</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Find and Replace text in the entire table using a MySQL query

I believe "swapnesh" answer to be the best ! Unfortunately I couldn't execute it in phpMyAdmin (4.5.0.2) who although illogical (and tried several things) it kept saying that a new statement was found and that no delimiter was found…

Thus I came with the following solution that might be usefull if you exeprience the same issue and have no other access to the database than PMA…

UPDATE `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid` 
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
SET `toUpdate`.`guid`=`updated`.`guid`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

To test the expected result you may want to use :

SELECT `toUpdate`.`guid` AS `old guid`,`updated`.`guid` AS `new guid`
FROM `wp_posts` AS `toUpdate`,
(SELECT `ID`,REPLACE(`guid`,'http://old.tld','http://new.tld') AS `guid`
 FROM `wp_posts` WHERE `guid` LIKE 'http://old.tld%') AS `updated`
WHERE `toUpdate`.`ID`=`updated`.`ID`;

MySQL combine two columns into one column

If you are Working On Oracle Then:

SELECT column1 || column2 AS column3
FROM table;

OR

If You Are Working On MySql Then:

SELECT Concat(column1 ,column2) AS column3
FROM table;

Create a day-of-week column in a Pandas dataframe using Python

Using dt.weekday_name is deprecated since pandas 0.23.0, instead, use dt.day_name():

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])

df['my_dates'].dt.day_name()

0    Thursday
1      Friday
2    Saturday
Name: my_dates, dtype: object

Can we add div inside table above every <tr>?

No, you cannot insert a div directly inside of a table. It is not correct html, and will result in unexpected output.

I would be happy to be more insightful, but you haven't said what you are attempting, so I can't really offer an alternative.

Remove the last three characters from a string

myString = myString.Remove(myString.Length - 3, 3);

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

Program to find largest and second largest number in array

You need to preserve the index of array members better as they are unique Here is a working code with few changes:

#include<stdio.h>
int main()
{
    int a[10],n;
    int largest1,largest2,i;

    printf("enter number of elements you want in array");
    scanf("%d",&n);
    printf("enter elements");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    largest1=0;
    for(i=0;i<n;i++)
    {
        if(a[i]>a[largest1])
        {
            largest1=i;
        }
    }
    if(largest1!=0) // this condition to select another index than the largest
        largest2=0;
    else
        largest2=n-1;
    for(i=0;i<n && i != largest1 ;i++)
    {
        if(a[i]>a[largest2])
            largest2=i;
    }
    printf("First and second largest number is %d and %d ",a[largest1],a[largest2]);
}

Note that when the array is of size 1 values will be the same.

++i or i++ in for loops ??

No compiler worth its weight in salt will run differently between

for(int i=0; i<10; i++)

and

for(int i=0;i<10;++i)

++i and i++ have the same cost. The only thing that differs is that the return value of ++i is i+1 whereas the return value of i++ is i.

So for those prefering ++i, there's probably no valid justification, just personal preference.

EDIT: This is wrong for classes, as said in about every other post. i++ will generate a copy if i is a class.

How do you run `apt-get` in a dockerfile behind a proxy?

before any apt-get command in your Dockerfile you should put this line

COPY apt.conf /etc/apt/apt.conf

Dont'f forget to create apt.conf in the same folder that you have the Dockerfile, the content of the apt.conf file should be like this:

Acquire::socks::proxy "socks://YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://YOUR-PROXY-IP:PORT/";

if you use username and password to connect to your proxy then the apt.conf should be like as below:

Acquire::socks::proxy "socks://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::http::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";
Acquire::https::proxy "http://USERNAME:PASSWORD@YOUR-PROXY-IP:PORT/";

for example :

Acquire::https::proxy "http://foo:[email protected]:8080/";

Where the foo is the username and bar is the password.

Get the key corresponding to the minimum value within a dictionary

# python 
d={320:1, 321:0, 322:3}
reduce(lambda x,y: x if d[x]<=d[y] else y, d.iterkeys())
  321

What is the difference between atan and atan2 in C++?

std::atan2 allows calculating the arctangent of all four quadrants. std::atan only allows calculating from quadrants 1 and 4.

Unresolved external symbol in object files

I believe most of the points regarding the causes and remedies have been covered by all contributors in this thread. I just want to point out for my 'unresolved external' problem, it was caused by a datatype defined as macro that gets substituted differently than expected, which results in that incorrect type being supplied to the function in question, and since the function with type is never defined, it couldn't have been resolved. In particular, under C/C++ -> Language, there is an attribute called 'Treat WChar_t As Built in Type, which should have been defined as 'No (/Zc:wchar_t-)' but did not in my case.

Apache HttpClient Android (Gradle)

None of the others worked for me. I had to add the following dependency, as explained here

compile group: 'cz.msebera.android' , name: 'httpclient', version: '4.4.1.1'

because I was targeting API 23.

Trying to Validate URL Using JavaScript

var RegExp = (/^HTTP|HTTP|http(s)?:\/\/(www\.)?[A-Za-z0-9]+([\-\.]{1}[A-Za-z0-9]+)*\.[A-Za-z]{2,40}(:[0-9]{1,40})?(\/.*)?$/);

Combining "LIKE" and "IN" for SQL Server

One other option would be to use something like this

SELECT  * 
FROM    table t INNER JOIN
        (
            SELECT  'Text%' Col
            UNION SELECT 'Link%'
            UNION SELECT 'Hello%'
            UNION SELECT '%World%'
        ) List ON t.COLUMN LIKE List.Col

How to convert an int value to string in Go?

fmt.Sprintf("%v",value);

If you know the specific type of value use the corresponding formatter for example %d for int

More info - fmt

How to insert special characters into a database?

You are propably pasting them directly into a query. Istead you should "escape" them, using appriopriate function - mysql_real_escape_string, mysqli_real_escape_string or PDO::quote depending on extension you are using.

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

Is it possible to get all arguments of a function as single object inside that function?

Use arguments. You can access it like an array. Use arguments.length for the number of arguments.

GCD to perform task in main thread

No you don't need to check if you're in the main thread. Here is how you can do this in Swift:

runThisInMainThread { () -> Void in
    runThisInMainThread { () -> Void in
        // No problem
    }
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

Create a git patch from the uncommitted changes in the current working directory

We could also specify the files, to include just the files with relative changes, particularly when they span multiple directories e.x.

git diff ~/path1/file1.ext ~/path2/file2.ext...fileN.ext > ~/whatever_path/whatever_name.patch

I found this to be not specified in the answers or comments, which are all relevant and correct, so chose to add it. Explicit is better than implicit!

Htaccess: add/remove trailing slash from URL

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
## hide .html extension
# To externally redirect /dir/foo.html to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+).html
RewriteRule ^ %1 [R=301,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)/\s
RewriteRule ^ %1 [R=301,L]

## To internally redirect /dir/foo to /dir/foo.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^([^\.]+)$ $1.html [L]


<Files ~"^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</Files>

This removes html code or php if you supplement it. Allows you to add trailing slash and it come up as well as the url without the trailing slash all bypassing the 404 code. Plus a little added security.

How can I roll back my last delete command in MySQL?

I also had deleted some values from my development database, but I had the same copy in QA database, so I did a generate script and selected option "type of data to script" to "data only" and selected my table.

Then I got the insert statements with same data, and then I run the script on my development database.

Maximum request length exceeded.

I was dealing with same error and after spending time solved it by adding below lines in web.config file

<system.web>
   <httpRuntime targetFramework="4.7.1" maxRequestLength="1048576"/>
</system.web>

and

 <system.webServer>
   <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
</system.webServer>

How to run a program in Atom Editor?

You can run specific lines of script by highlighting them and clicking shift + ctrl + b

You can also use command line by going to the root folder and writing: $ node nameOfFile.js

Adding new files to a subversion repository

Normally svn add * works. But if you get message like svn: warning: W150002: due to mix off versioned and non-versioned files in working copy. Use this command:

svn add <path to directory> --force

or

svn add * --force

How to get the current loop index when using Iterator?

You can use ListIterator to do the counting:

final List<String> list = Arrays.asList("zero", "one", "two", "three");

for (final ListIterator<String> it = list.listIterator(); it.hasNext();) {
    final String s = it.next();
    System.out.println(it.previousIndex() + ": " + s);
}

Can an int be null in Java?

I'm no expert, but I do believe that the null equivalent for an int is 0.

For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.

In some situations, this may be of use.

How to get correct timestamp in C#

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

to this:

String timeStamp = GetTimestamp(DateTime.Now);

iOS: UIButton resize according to text length

Swift:

The important thing here is when will you call the .sizeToFit() , it should be after setting the text to display so it can read the size needed, if you later update text, then call it again.

var button = UIButton()
button.setTitle("Length of this text determines size", forState: UIControlState.Normal)
button.sizeToFit()
self.view.addSubview(button)

Managing large binary files with Git

git clone --filter from Git 2.19 + shallow clones

This new option might eventually become the final solution to the binary file problem, if the Git and GitHub devs and make it user friendly enough (which they arguably still haven't achieved for submodules for example).

It allows to actually only fetch files and directories that you want for the server, and was introduced together with a remote protocol extension.

With this, we could first do a shallow clone, and then automate which blobs to fetch with the build system for each type of build.

There is even already a --filter=blob:limit<size> which allows limiting the maximum blob size to fetch.

I have provided a minimal detailed example of how the feature looks like at: How do I clone a subdirectory only of a Git repository?

HttpUtility does not exist in the current context

You're probably targeting the Client Profile, in which System.Web.dll is not available.

You can target the full framework in project's Properties.

CSS disable text selection

Use a wild card selector * for this purpose.

#div * { /* Narrowing, to specific elements, like  input, textarea is PREFFERED */
 -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

Now, every element inside a div with id div will have no selection.

Demo

Working with time DURATION, not time of day

I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)

Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.

In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.

Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).

iPhone 6 and 6 Plus Media Queries

iPhone 6

  • Landscape

    @media only screen 
        and (min-device-width : 375px) // or 213.4375em or 3in or 9cm
        and (max-device-width : 667px) // or 41.6875em
        and (width : 667px) // or 41.6875em
        and (height : 375px) // or 23.4375em
        and (orientation : landscape) 
        and (color : 8)
        and (device-aspect-ratio : 375/667)
        and (aspect-ratio : 667/375)
        and (device-pixel-ratio : 2)
        and (-webkit-min-device-pixel-ratio : 2)
    { }
    
  • Portrait

    @media only screen 
        and (min-device-width : 375px) // or 213.4375em
        and (max-device-width : 667px) // or 41.6875em
        and (width : 375px) // or 23.4375em
        and (height : 559px) // or 34.9375em
        and (orientation : portrait) 
        and (color : 8)
        and (device-aspect-ratio : 375/667)
        and (aspect-ratio : 375/559)
        and (device-pixel-ratio : 2)
        and (-webkit-min-device-pixel-ratio : 2)
    { }
    

    if you prefer you can use (device-width : 375px) and (device-height: 559px) in place of the min- and max- settings.

    It is not necessary to use all of these settings, and these are not all the possible settings. These are just the majority of possible options so you can pick and choose whichever ones meet your needs.

  • User Agent

    tested with my iPhone 6 (model MG6G2LL/A) with iOS 9.0 (13A4305g)

    # Safari
    Mozilla/5.0 (iPhone; CPU iPhone OS 9_0 like Mac OS X) AppleWebKit/601.1.39 (KHTML, like Gecko) Version/9.0 Mobile/13A4305g Safari 601.1
    # Google Chrome
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.53.11 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10 (000102)
    # Mercury
    Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53
    
  • Launch images

    • 750 x 1334 (@2x) for portrait
    • 1334 x 750 (@2x) for landscape
  • App icon

    • 120 x 120

iPhone 6+

  • Landscape

    @media only screen 
        and (min-device-width : 414px) 
        and (max-device-width : 736px) 
        and (orientation : landscape) 
        and (-webkit-min-device-pixel-ratio : 3) 
    { }
    
  • Portrait

    @media only screen 
        and (min-device-width : 414px) 
        and (max-device-width : 736px)
        and (device-width : 414px)
        and (device-height : 736px)
        and (orientation : portrait) 
        and (-webkit-min-device-pixel-ratio : 3) 
        and (-webkit-device-pixel-ratio : 3)
    { }
    
  • Launch images

    • 1242 x 2208 (@3x) for portrait
    • 2208 x 1242 (@3x) for landscape
  • App icon

    • 180 x 180

iPhone 6 and 6+

@media only screen 
    and (max-device-width: 640px), 
    only screen and (max-device-width: 667px), 
    only screen and (max-width: 480px)
{ }

Predicted

According to the Apple website the iPhone 6 Plus will have 401 pixels-per-inch and be 1920 x 1080. The smaller version of the iPhone 6 will be 1334 x 750 with 326 PPI.

So, assuming that information is correct, we can write a media query for the iPhone 6:

@media screen 
    and (min-device-width : 1080px) 
    and (max-device-width : 1920px) 
    and (min-resolution: 401dpi) 
    and (device-aspect-ratio:16/9) 
{ }

@media screen 
    and (min-device-width : 750px) 
    and (max-device-width : 1334px) 
    and (min-resolution: 326dpi) 
{ }

Note that will be deprecated in http://dev.w3.org/csswg/mediaqueries-4/ and replaced with

Min-width and max-width may be something like 1704 x 960.


Apple Watch (speculative)

Specs on the Watch are still a bit speculative since (as far as I'm aware) there has been no official spec sheet yet. But Apple did mention in this press release that the Watch will be available in two sizes.. 38mm and 42mm.

Further assuming.. that those sizes refer to the screen size rather than the overall size of the Watch face these media queries should work.. And I'm sure you could give or take a few millimeters to cover either scenario without sacrificing any unwanted targeting because..

@media (!small) and (damn-small), (omfg) { }

or

@media 
    (max-device-width:42mm) 
    and (min-device-width:38mm) 
{ }

It's worth noting that Media Queries Level 4 from W3C currently only available as a first public draft, once available for use will bring with it a lot of new features designed with smaller wearable devices like this in mind.

Default interface methods are only supported starting with Android N

You should use Java 8 to solve this, based on the Android documentation you can do this by

clicking File > Project Structure

and change Source Compatibility and Target Compatibility.

enter image description here

and you can also configure it directly in the app-level build.gradle file:

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

How to turn off caching on Firefox?

First of All, this can be easily done, for e.g. by PHP to force the browser to renew files based on cache date (expiration time). If you just need it for experimental needs, then try to use ctrl+shift+del to clear all cache at once inside Firefox browser. The third solution is to use many add-ons that exits for Firefox to clear cache based on time lines.

GitHub Error Message - Permission denied (publickey)

you can try this way...

enter image description here

enter image description here

choose another links

How to insert a value that contains an apostrophe (single quote)?

Use a backtick (on the ~ key) instead;

`O'Brien`

Load properties file in JAR?

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

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

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

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

Using Keras & Tensorflow with AMD GPU

Technically you can if you use something like OpenCL, but Nvidia's CUDA is much better and OpenCL requires other steps that may or may not work. I would recommend if you have an AMD gpu, use something like Google Colab where they provide a free Nvidia GPU you can use when coding.

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

Defining a `required` field in Bootstrap

Try using required="true" in bootstrap 3

Can't connect to docker from docker-compose

I know it's silly, but in my case I just tried with sudo and it worked like a charm.

in your case, just try: $ sudo docker-compose up

list all files in the folder and also sub folders

Using you current code, make this tweak:

public void listf(String directoryName, List<File> files) {
    File directory = new File(directoryName);

    // Get all files from a directory.
    File[] fList = directory.listFiles();
    if(fList != null)
        for (File file : fList) {      
            if (file.isFile()) {
                files.add(file);
            } else if (file.isDirectory()) {
                listf(file.getAbsolutePath(), files);
            }
        }
    }
}

Using ls to list directories and their total sizes

du -h --max-depth=1 . | sort -n -r

How to get rid of blank pages in PDF exported from SSRS

The problem for me was that SSRS purposely treats your white space as if you intend it be honored:

enter image description here

As well as white space, make sure there is no right margin.

Laravel stylesheets and javascript don't load for non-base routes

In Laravel 5.8

<script src="{{asset('js/customPath1/customPath2/customjavascript.js')}}"></script>

just made the trick for me.

Is it possible to simulate key press events programmatically?

That's what I tried with js/typescript in chrome. Thanks to this answer for inspiration.

var x = document.querySelector('input');

var keyboardEvent = new KeyboardEvent("keypress", { bubbles: true });
// you can try charCode or keyCode but they are deprecated
Object.defineProperty(keyboardEvent, "key", {
  get() {
    return "Enter";
  },
});
x.dispatchEvent(keyboardEvent);

_x000D_
_x000D_
{
  // example
  document.querySelector('input').addEventListener("keypress", e => console.log("keypress", e.key))
  // unfortunatelly doesn't trigger submit
  document.querySelector('form').addEventListener("submit", e => {
    e.preventDefault();
    console.log("submit")
  })
}

var x = document.querySelector('input');

var keyboardEvent = new KeyboardEvent("keypress", { bubbles: true });
// you can try charCode or keyCode but they are deprecated
Object.defineProperty(keyboardEvent, "key", {
  get() {
    return "Enter";
  },
});
x.dispatchEvent(keyboardEvent);
_x000D_
<form>
  <input>
</form>
_x000D_
_x000D_
_x000D_

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

How do I disable a Button in Flutter?

You can also use the AbsorbPointer, and you can use it in the following way:

AbsorbPointer(
      absorbing: true, // by default is true
      child: RaisedButton(
        onPressed: (){
          print('pending to implement onPressed function');
        },
        child: Text("Button Click!!!"),
      ),
    ),

If you want to know more about this widget, you can check the following link Flutter Docs

Choosing the default value of an Enum type without having to change values

If you define the Default enum as the enum with the smallest value you can use this:

public enum MyEnum { His = -1, Hers = -2, Mine = -4, Theirs = -3 }

var firstEnum = ((MyEnum[])Enum.GetValues(typeof(MyEnum)))[0];

firstEnum == Mine.

This doesn't assume that the enum has a zero value.

How to push both key and value into an Array in Jquery

You might mean this:

var unEnumeratedArray = [];
var wtfObject = {
                 key    : 'val', 
                 0      : (undefined = 'Look, I\'m defined'),
                 'new'  : 'keyword', 
                 '{!}'  : 'use bracket syntax',
                 '        ': '8 spaces'
                };

for(var key in wtfObject){
    unEnumeratedArray[key] = wtfObject[key];
}
console.log('HAS KEYS PER VALUE NOW:', unEnumeratedArray, unEnumeratedArray[0], 
             unEnumeratedArray.key, unEnumeratedArray['new'], 
             unEnumeratedArray['{!}'], unEnumeratedArray['        ']);

You can set an enumerable for an Object like: ({})[0] = 'txt'; and you can set a key for an Array like: ([])['myKey'] = 'myVal';

Hope this helps :)

How to change the font size on a matplotlib plot

You can use plt.rcParams["font.size"] for setting font_size in matplotlib and also you can use plt.rcParams["font.family"] for setting font_family in matplotlib. Try this example:

import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')

label = [1,2,3,4,5,6,7,8]
x = [0.001906,0.000571308,0.0020305,0.0037422,0.0047095,0.000846667,0.000819,0.000907]
y = [0.2943301,0.047778308,0.048003167,0.1770876,0.532489833,0.024611333,0.157498667,0.0272095]


plt.ylabel('eigen centrality')
plt.xlabel('betweenness centrality')
plt.text(0.001906, 0.2943301, '1 ', ha='right', va='center')
plt.text(0.000571308, 0.047778308, '2 ', ha='right', va='center')
plt.text(0.0020305, 0.048003167, '3 ', ha='right', va='center')
plt.text(0.0037422, 0.1770876, '4 ', ha='right', va='center')
plt.text(0.0047095, 0.532489833, '5 ', ha='right', va='center')
plt.text(0.000846667, 0.024611333, '6 ', ha='right', va='center')
plt.text(0.000819, 0.157498667, '7 ', ha='right', va='center')
plt.text(0.000907, 0.0272095, '8 ', ha='right', va='center')
plt.rcParams["font.family"] = "Times New Roman"
plt.rcParams["font.size"] = "50"
plt.plot(x, y, 'o', color='blue')

Please, see the output:

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

You are not allowed to have a CNAME record for the domain, as the CNAME is an aliasing feature that covers all data types (regardless of whether the client looks for MX, NS or SOA records). CNAMEs also always refer to a new name, not an ip-address, so there are actually two errors in the single line

@                        IN CNAME   88.198.38.XXX

Changing that CNAME to an A record should make it work, provided the ip-address you use is the correct one for your Heroku app.

The only correct way in DNS to make a simple domain.com name work in the browser, is to point the domain to an IP-adress with an A record.

how to align all my li on one line?

Here is what you want. In this case you do not want the list items to be treated as blocks that can wrap.

li{display:inline}
ul{overflow:hidden}

Shorter syntax for casting from a List<X> to a List<Y>?

This is not quite the answer to this question, but it may be useful for some: as @SWeko said, thanks to covariance and contravariance, List<X> can not be cast in List<Y>, but List<X> can be cast into IEnumerable<Y>, and even with implicit cast.

Example:

List<Y> ListOfY = new List<Y>();
List<X> ListOfX = (List<X>)ListOfY; // Compile error

but

List<Y> ListOfY = new List<Y>();
IEnumerable<X> EnumerableOfX = ListOfY;  // No issue

The big advantage is that it does not create a new list in memory.

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

I think the right way to find the internal Java used by the Android Studio is to

  1. Open Android Studio
  2. Go to File->Other Settings->Default Project Structure/JDK Location:
  3. and copy what ever string is specified there

This will not require memorising the folder or searching for java and also these steps wil take of any future changes to the java location by the Android Studio team changes I suppose

adb uninstall failed

Try disable "Instant run" from Preference! It's working for me.

enter image description here

Match everything except for specified strings

Matching Anything but Given Strings

If you want to match the entire string where you want to match everything but certain strings you can do it like this:

^(?!(red|green|blue)$).*$

This says, start the match from the beginning of the string where it cannot start and end with red, green, or blue and match anything else to the end of the string.

You can try it here: https://regex101.com/r/rMbYHz/2

Note that this only works with regex engines that support a negative lookahead.

How to list all available Kafka brokers in a cluster?

Here are a couple of quick functions I use when bash scripting Kafka Data Load into Demo Environments. In this example I use HDP with no security, but it is easily modified to other environments and intended to be quick and functional rather than particularly robust.

The first retrieves the address of the first ZooKeeper node from the config:

ZKS1=$(cat /usr/hdp/current/zookeeper-client/conf/zoo.cfg | grep server.1)
[[ ${ZKS1} =~ server.1=(.*?):[0-9]*:[0-9]* ]]
export ZKADDR=${BASH_REMATCH[1]}:2181
echo "using ZooKeeper Server $ZKADDR"

The second retrieves the Broker IDs from ZooKeeper:

echo "Fetching list of Kafka Brokers"
export BROKERIDS=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< 'ls /brokers/ids' | tail -1)
export BROKERIDS=${BROKERIDS//[!0-9 ]/}
echo "Found Kafka Broker IDS: $BROKERIDS"

The third parses ZooKeeper again to retrieve the list of Kafka Brokers Host:port ready for use in the command-line client:

unset BROKERS
for i in $BROKERIDS
do
DETAIL=$(/usr/hdp/current/kafka-broker/bin/zookeeper-shell.sh ${ZKADDR} <<< "get /brokers/ids/$i")
[[ $DETAIL =~ PLAINTEXT:\/\/(.*?)\"\] ]]
if [ -z ${BROKERS+x} ]; then BROKERS=${BASH_REMATCH[1]}; else 
BROKERS="${BROKERS},${BASH_REMATCH[1]}"; fi
done
echo "Found Brokerlist: $BROKERS"

CSS background-image - What is the correct usage?

just check the directory structure where exactly image is suppose you have a css folder and images folder outside css folder then you will have to use"../images/image.jpg" and it will work as it did for me just make sure the directory stucture.

Java 8 Lambda filter by Lists

Look this:

List<Client> result = clients
    .stream()
    .filter(c -> 
        (users.stream().map(User::getName).collect(Collectors.toList())).contains(c.getName()))
        .collect(Collectors.toList());

Input from the keyboard in command line application

I managed to figure it out without dropping down in to C:

My solution is as follows:

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding:NSUTF8StringEncoding)!
}

More recent versions of Xcode need an explicit typecast (works in Xcode 6.4):

func input() -> String {
    var keyboard = NSFileHandle.fileHandleWithStandardInput()
    var inputData = keyboard.availableData
    return NSString(data: inputData, encoding:NSUTF8StringEncoding)! as String
}

Return multiple values from a SQL Server function

Example of using a stored procedure with multiple out parameters

As User Mr. Brownstone suggested you can use a stored procedure; to make it easy for all i created a minimalist example. First create a stored procedure:

Create PROCEDURE MultipleOutParameter
    @Input int,
    @Out1 int OUTPUT, 
    @Out2 int OUTPUT 
AS
BEGIN
    Select @Out1 = @Input + 1
    Select @Out2 = @Input + 2   
    Select 'this returns your normal Select-Statement' as Foo
          , 'amazing is it not?' as Bar

    -- Return can be used to get even more (afaik only int) values 
    Return(@Out1+@Out2+@Input)
END 

Calling the stored procedure

To execute the stored procedure a few local variables are needed to receive the value:

DECLARE @GetReturnResult int, @GetOut1 int, @GetOut2 int 
EXEC @GetReturnResult = MultipleOutParameter  
    @Input = 1,
    @Out1 = @GetOut1 OUTPUT,
    @Out2 = @GetOut2 OUTPUT

To see the values content you can do the following

Select @GetReturnResult as ReturnResult, @GetOut1 as Out_1, @GetOut2 as Out_2 

This will be the result:

Result of Stored Procedure Call with multiple out parameters

Good tool for testing socket connections?

In situations like this, why not write your own? A simple server app to test connections can be done in a matter of minutes if you know what you're doing, and you can make it respond exactly how you need to, and for specific scenarios.

Git diff --name-only and copy that list

The following should work fine:

git diff -z --name-only commit1 commit2 | xargs -0 -IREPLACE rsync -aR REPLACE /home/changes/protected/

To explain further:

  • The -z to with git diff --name-only means to output the list of files separated with NUL bytes instead of newlines, just in case your filenames have unusual characters in them.

  • The -0 to xargs says to interpret standard input as a NUL-separated list of parameters.

  • The -IREPLACE is needed since by default xargs would append the parameters to the end of the rsync command. Instead, that says to put them where the later REPLACE is. (That's a nice tip from this Server Fault answer.)

  • The -a parameter to rsync means to preserve permissions, ownership, etc. if possible. The -R means to use the full relative path when creating the files in the destination.

Update: if you have an old version of xargs, you'll need to use the -i option instead of -I. (The former is deprecated in later versions of findutils.)

Random number from a range in a Bash Script

$RANDOM is a number between 0 and 32767. You want a port between 2000 and 65000. These are 63001 possible ports. If we stick to values of $RANDOM + 2000 between 2000 and 33500, we cover a range of 31501 ports. If we flip a coin and then conditionally add 31501 to the result, we can get more ports, from 33501 to 65001. Then if we just drop 65001, we get the exact coverage needed, with a uniform probability distribution for all ports, it seems.

random-port() {
    while [[ not != found ]]; do
        # 2000..33500
        port=$((RANDOM + 2000))
        while [[ $port -gt 33500 ]]; do
            port=$((RANDOM + 2000))
        done

        # 2000..65001
        [[ $((RANDOM % 2)) = 0 ]] && port=$((port + 31501)) 

        # 2000..65000
        [[ $port = 65001 ]] && continue
        echo $port
        break
    done
}

Testing

i=0
while true; do
    i=$((i + 1))
    printf "\rIteration $i..."
    printf "%05d\n" $(random-port) >> ports.txt
done

# Then later we check the distribution
sort ports.txt | uniq -c | sort -r

Convert JSON string to dict using Python

json.loads()

import json

d = json.loads(j)
print d['glossary']['title']

How to restore the menu bar in Visual Studio Code

Some changes to this coming in v1.54, see https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_54.md#updated-application-menu-settings

Updated Application Menu Settings

The window.menuBarVisibility setting for the application menu visibility has been updated to better reflect the options. Two primary changes have been made.

First, the default option for the setting has been renamed to classic.

Second, the Show Menu Bar entry in the the application menu bar now toggles between the classic and compact options. To hide it completely, you can update the setting, or use the context menu of the Activity Bar when in compact mode.

SSH Key: “Permissions 0644 for 'id_rsa.pub' are too open.” on mac

chmod 600 id_rsa

Run above command from path where key is stored in vm ex: cd /home/opc/.ssh

Deserializing a JSON into a JavaScript object

You could also use eval() but JSON.parse() is safer and easier way, so why would you?

good and works

var yourJsonObject = JSON.parse(json_as_text);

I don't see any reason why would you prefer to use eval. It only puts your application at risk.

That said - this is also possible.

bad - but also works

var yourJsonObject = eval(json_as_text);

Why is eval a bad idea?

Consider the following example.

Some third party or user provided JSON string data.

var json = `
[{
    "adjacencies": [
        {
          "nodeTo": function(){
            return "delete server files - you have been hacked!";
          }(),
          "nodeFrom": "graphnode1",
          "data": {
            "$color": "#557EAA"
          }
        }
    ],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode1",
    "name": "graphnode1"
},{
    "adjacencies": [],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode2",
    "name": "graphnode2"
}]
`;

Your server-side script processes that data.

Using JSON.parse:

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}

will throw:

Uncaught SyntaxError: Unexpected token u in JSON at position X. 

Function will not get executed.

You are safe.

Using eval():

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}

will execute the function and return the text.

If I replace that harmless function with one that removes files from your website folder you have been hacked. No errors/warnings will get thrown in this example.

You are NOT safe.

I was able to manipulate a JSON text string so it acts as a function which will execute on the server.

eval(JSON)[0].adjacencies[0].nodeTo expects to process a JSON string but, in reality, we just executed a function on our server.

This could also be prevented if we server-side check all user-provided data before passing it to an eval() function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

MySQL root password change

Using the mysqladmin command-line utility to alter the MySQL password:

mysqladmin --user=root --password=oldpassword password "newpassword"

Source

PHP: Get the key from an array in a foreach loop

you need nested foreach loops

foreach($samplearr as $key => $item){
   echo $key;
    foreach($item as $detail){
       echo $detail['value1'] . " " . $detail['value2']
     }
 }

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

When iterating over cell arrays of strings, the loop variable (let's call it f) becomes a single-element cell array. Having to write f{1} everywhere gets tedious, and modifying the loop variable provides a clean workaround.

% This example transposes each field of a struct.
s.a = 1:3;
s.b = zeros(2,3);
s % a: [1 2 3]; b: [2x3 double]
for f = fieldnames(s)'
    s.(f{1}) = s.(f{1})';
end
s % a: [3x1 double]; b: [3x2 double]

% Redefining f simplifies the indexing.
for f = fieldnames(s)'
    f = f{1};
    s.(f) = s.(f)';
end
s % back to a: [1 2 3]; b: [2x3 double]

PHP: Best way to check if input is a valid number?

For PHP version 4 or later versions:

<?PHP
$input = 4;
if(is_numeric($input)){  // return **TRUE** if it is numeric
    echo "The input is numeric";
}else{
    echo "The input is not numeric";
}
?>

Remove all constraints affecting a UIView

Details

  • Xcode 10.2.1 (10E1001), Swift 5

Solution

import UIKit

extension UIView {

    func removeConstraints() { removeConstraints(constraints) }
    func deactivateAllConstraints() { NSLayoutConstraint.deactivate(getAllConstraints()) }
    func getAllSubviews() -> [UIView] { return UIView.getAllSubviews(view: self) }

    func getAllConstraints() -> [NSLayoutConstraint] {
        var subviewsConstraints = getAllSubviews().flatMap { $0.constraints }
        if let superview = self.superview {
            subviewsConstraints += superview.constraints.compactMap { (constraint) -> NSLayoutConstraint? in
                if let view = constraint.firstItem as? UIView, view == self { return constraint }
                return nil
            }
        }
        return subviewsConstraints + constraints
    }

    class func getAllSubviews(view: UIView) -> [UIView] {
        return view.subviews.flatMap { [$0] + getAllSubviews(view: $0) }
    }
}

Usage

print("constraints: \(view.getAllConstraints().count), subviews: \(view.getAllSubviews().count)")
view.deactivateAllConstraints()

Call a function on click event in Angular 2

This worked for me: :)

<button (click)="updatePendingApprovals(''+pendingApproval.personId, ''+pendingApproval.personId)">Approve</button>
updatePendingApprovals(planId: string, participantId: string) : void {
  alert('PlanId:' + planId + '    ParticipantId:' + participantId);
}

How to set specific window (frame) size in java swing?

Most layout managers work best with a component's preferredSize, and most GUI's are best off allowing the components they contain to set their own preferredSizes based on their content or properties. To use these layout managers to their best advantage, do call pack() on your top level containers such as your JFrames before making them visible as this will tell these managers to do their actions -- to layout their components.

Often when I've needed to play a more direct role in setting the size of one of my components, I'll override getPreferredSize and have it return a Dimension that is larger than the super.preferredSize (or if not then it returns the super's value).

For example, here's a small drag-a-rectangle app that I created for another question on this site:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MoveRect extends JPanel {
   private static final int RECT_W = 90;
   private static final int RECT_H = 70;
   private static final int PREF_W = 600;
   private static final int PREF_H = 300;
   private static final Color DRAW_RECT_COLOR = Color.black;
   private static final Color DRAG_RECT_COLOR = new Color(180, 200, 255);
   private Rectangle rect = new Rectangle(25, 25, RECT_W, RECT_H);
   private boolean dragging = false;
   private int deltaX = 0;
   private int deltaY = 0;

   public MoveRect() {
      MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
      addMouseListener(myMouseAdapter);
      addMouseMotionListener(myMouseAdapter);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (rect != null) {
         Color c = dragging ? DRAG_RECT_COLOR : DRAW_RECT_COLOR;
         g.setColor(c);
         Graphics2D g2 = (Graphics2D) g;
         g2.draw(rect);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private class MyMouseAdapter extends MouseAdapter {

      @Override
      public void mousePressed(MouseEvent e) {
         Point mousePoint = e.getPoint();
         if (rect.contains(mousePoint)) {
            dragging = true;
            deltaX = rect.x - mousePoint.x;
            deltaY = rect.y - mousePoint.y;
         }
      }

      @Override
      public void mouseReleased(MouseEvent e) {
         dragging = false;
         repaint();
      }

      @Override
      public void mouseDragged(MouseEvent e) {
         Point p2 = e.getPoint();
         if (dragging) {
            int x = p2.x + deltaX;
            int y = p2.y + deltaY;
            rect = new Rectangle(x, y, RECT_W, RECT_H);
            MoveRect.this.repaint();
         }
      }
   }

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Note that my main class is a JPanel, and that I override JPanel's getPreferredSize:

public class MoveRect extends JPanel {
   //.... deleted constants

   private static final int PREF_W = 600;
   private static final int PREF_H = 300;

   //.... deleted fields and constants

   //... deleted methods and constructors

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

Also note that when I display my GUI, I place it into a JFrame, call pack(); on the JFrame, set its position, and then call setVisible(true); on my JFrame:

   private static void createAndShowGui() {
      MoveRect mainPanel = new MoveRect();

      JFrame frame = new JFrame("MoveRect");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Find the server name for an Oracle database

I use this query in order to retrieve the server name of my Oracle database.

SELECT program FROM v$session WHERE program LIKE '%(PMON)%';

How can I view an old version of a file with Git?

You can also specify a commit hash (often also called commit ID) with the git show command.


In a nutshell

git show <commitHash>:/path/to/file


Step by step

  1. Show the log of all the changes for a given file with git log /path/to/file
  2. In the list of changes shown, it shows the commit hash such as commit 06c98... (06c98... being the commit hash)
  3. Copy the commit hash
  4. Run the command git show <commitHash>:/path/to/file using the commit hashof step 3 & the path/to/file of step 1.

Note: adding the ./ when specifying a relative path seems important, i.e. git show b2f8be577166577c59b55e11cfff1404baf63a84:./flight-simulation/src/main/components/nav-horiz.html.

Find duplicate records in MongoDB

You can find the list of duplicate names using the following aggregate pipeline:

  • Group all the records having similar name.
  • Match those groups having records greater than 1.
  • Then group again to project all the duplicate names as an array.

The Code:

db.collection.aggregate([
{$group:{"_id":"$name","name":{$first:"$name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"name":1,"_id":0}},
{$group:{"_id":null,"duplicateNames":{$push:"$name"}}},
{$project:{"_id":0,"duplicateNames":1}}
])

o/p:

{ "duplicateNames" : [ "ksqn291", "ksqn29123213Test" ] }

Auto-Submit Form using JavaScript

Try using document.getElementById("myForm") instead of document.myForm.

<script>
var auto_refresh = setInterval(function() { submitform(); }, 10000);

function submitform()
{
  alert('test');
  document.getElementById("myForm").submit();
}
</script>

How to randomly select rows in SQL?

SELECT * FROM TABLENAME ORDER BY random() LIMIT 5; 

Unable to install Android Studio in Ubuntu

None of these options worked for me on Ubuntu 12.10 (yeah, I need to upgrade). However, I found an easy solution. Download the source from here: https://github.com/miracle2k/android-platform_sdk/blob/master/emulator/mksdcard/mksdcard.c. Then simply compile with "gcc mksdcard.c -o mksdcard". Backup mksdcard in the SDK tools subfolder and replace with the newly compiled one. Android Studio will now be happy with your SDK.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

MYSQL import data from csv using LOAD DATA INFILE

You can load data from a csv or text file. If you have a text file with records from a table, you can load those records within the table. For example if you have a text file, where each row is a record with the values for each column, you can load the records this way.

table.sql

id //field 1

name //field2

table.txt

1,peter

2,daniel

...

--example on windows

LOAD DATA LOCAL INFILE 'C:\\directory_example\\table.txt'
INTO TABLE Table
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'; 

Using File.listFiles with FileNameExtensionFilter

Here's something I quickly just made and it should perform far better than File.getName().endsWith(".xxxx");

import java.io.File;
import java.io.FileFilter;

public class ExtensionsFilter implements FileFilter 
{
    private char[][] extensions;

    private ExtensionsFilter(String[] extensions)
    {
        int length = extensions.length;
        this.extensions = new char[length][];
        for (String s : extensions)
        {
            this.extensions[--length] = s.toCharArray();
        }
    }

    @Override
    public boolean accept(File file)
    {
        char[] path = file.getPath().toCharArray();
        for (char[] extension : extensions)
        {
            if (extension.length > path.length)
            {
                continue;
            }
            int pStart = path.length - 1;
            int eStart = extension.length - 1;
            boolean success = true;
            for (int i = 0; i <= eStart; i++)
            {
                if ((path[pStart - i] | 0x20) != (extension[eStart - i] | 0x20))
                {
                    success = false;
                    break;
                }
            }
            if (success)
                return true;
        }
        return false;
    }
}

Here's an example for various images formats.

private static final ExtensionsFilter IMAGE_FILTER = 
      new ExtensionsFilter(new String[] {".png", ".jpg", ".bmp"});

Get value (String) of ArrayList<ArrayList<String>>(); in Java

A cleaner way of iterating the lists is:

// initialise the collection
collection = new ArrayList<ArrayList<String>>();
// iterate
for (ArrayList<String> innerList : collection) {
    for (String string : innerList) {
        // do stuff with string
    }
}

How to implement history.back() in angular.js

For me, my problem was I needed to navigate back and then transition to another state. So using $window.history.back() didn't work because for some reason the transition happened before history.back() occured so I had to wrap my transition in a timeout function like so.

$window.history.back();
setTimeout(function() {
  $state.transitionTo("tab.jobs"); }, 100);

This fixed my issue.

Hive External Table Skip First Row

Just append below property in your query and the first header or line int the record will not load or it will be skipped.

Try this

tblproperties ("skip.header.line.count"="1");

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Run the command below;

sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib
pip install psycopg2

jQuery callback for multiple ajax calls

async   : false,

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

I had similar issue. I was not able to use value="something" to display and edit. I had to use the below command inside my <input>along withe ng model being declared.

[(ngModel)]=userDataToPass.pinCode

Where I have the list of data in the object userDataToPass and the item that I need to display and edit is pinCode.

For the same , I referred to this YouTube video

Maven2: Missing artifact but jars are in place

When I copied from maven repository, there was 4th row called <type>. When I removed this <type>, it solved my error.

Calling Web API from MVC controller

well, you can do it a lot of ways... one of them is to create a HttpRequest. I would advise you against calling your own webapi from your own MVC (the idea is redundant...) but, here's a end to end tutorial.

Remove last characters from a string in C#. An elegant way?

Use lastIndexOf. Like:

string var = var.lastIndexOf(',');

How to reload a page using Angularjs?

Be sure to include the $route service into your scope and do this:

$route.reload();

See this:

How to reload or re-render the entire page using AngularJS

Updating the list view when the adapter data changes

invalidate(); calls the list view to invalidate itself (ie. background color)
invalidateViews(); calls all of its children to be invalidated. allowing you to update the children views

I assume its some type of efficiency thing preventing all of the items to constantly have to be redraw if not necessary.

Carriage return in C?

Program prints ab, goes back one character and prints si overwriting the b resulting asi. Carriage return returns the caret to the first column of the current line. That means the ha will be printed over as and the result is hai

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.xlabel("Colors")
plt.ylabel("Values")
plt.title("Colors vs Values") # You can comment this line out if you don't need title
plt.show(fig)

Output figure:

enter image description here

Commenting in a Bash script inside a multiline command

The trailing backslash must be the last character on the line for it to be interpreted as a continuation command. No comments or even whitespace are allowed after it.

You should be able to put comment lines in between your commands

# output MYSQLDUMP file
cat ${MYSQLDUMP} | \
# simplify the line
sed '/created_at/d' | \
# create some newlines
tr ",;" "\n" | \
# use some sed magic
sed -e 's/[asbi]:[0-9]*[:]*//g' -e '/^[{}]/d' -e 's/""//g' -e '/^"{/d' | \
# more magic
sed -n -e '/^"/p' -e '/^print_value$/,/^option_id$/p' | \
# even more magic
sed -e '/^option_id/d' -e '/^print_value/d' -e 's/^"\(.*\)"$/\1/' | \
tr "\n" "," | \
# I hate phone numbers in my output
sed -e 's/,\([0-9]*-[0-9]*-[0-9]*\)/\n\1/g' -e 's/,$//' | \ 
# one more sed call and then send it to the CSV file
sed -e 's/^/"/g' -e 's/$/"/g' -e 's/,/","/g' >> ${CSV}

How to copy folders to docker image from Dockerfile?

COPY . <destination>

Which would be in your case:

COPY . /

How to get All input of POST in Laravel

You can use it

$params = request()->all();

without

import Illuminate\Http\Request OR

use Illuminate\Support\Facades\Request OR other.

How to compile for Windows on Linux with gcc/g++?

Suggested method gave me error on Ubuntu 16.04: E: Unable to locate package mingw32

===========================================================================

To install this package on Ubuntu please use following:

sudo apt-get install mingw-w64

After install you can use it:

x86_64-w64-mingw32-g++

Please note!

For 64-bit use: x86_64-w64-mingw32-g++

For 32-bit use: i686-w64-mingw32-g++

Python: How to create a unique file name?

I came across this question, and I will add my solution for those who may be looking for something similar. My approach was just to make a random file name from ascii characters. It will be unique with a good probability.

from random import sample
from string import digits, ascii_uppercase, ascii_lowercase
from tempfile import gettempdir
from os import path

def rand_fname(suffix, length=8):
    chars = ascii_lowercase + ascii_uppercase + digits

    fname = path.join(gettempdir(), 'tmp-'
                + ''.join(sample(chars, length)) + suffix)

    return fname if not path.exists(fname) \
                else rand_fname(suffix, length)

What is a tracking branch?

The Pro Git book mentions:

Tracking branches are local branches that have a direct relationship to a remote branch

Not exactly. The SO question "Having a hard time understanding git-fetch" includes:

There's no such concept of local tracking branches, only remote tracking branches.
So origin/master is a remote tracking branch for master in the origin repo.

But actually, once you establish an upstream branch relationship between:

  • a local branch like master
  • and a remote tracking branch like origin/master

Then you can consider master as a local tracking branch: It tracks the remote tracking branch origin/master which, in turn, tracks the master branch of the upstream repo origin.

alt text

Labels for radio buttons in rails form

Using true/false as the value will have the field pre-filled if the model passed to the form has this attribute already filled:

= f.radio_button(:public?, true)
= f.label(:public?, "yes", value: true)
= f.radio_button(:public?, false)
= f.label(:public?, "no", value: false)

error: cast from 'void*' to 'int' loses precision

I meet this problem too.

ids[i] = (int) arg; // error occur here => I change this to below.

ids[i] = (uintptr_t) arg;

Then I can continue compiling. Maybe you can try this too.

Get a resource using getResource()

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

VB.NET - Click Submit Button on Webbrowser page

Just follow two steps for clicking a any button using code.

  1. focus the button or element which you want to click

    WebBrowser1.Document.GetElementById("place id here").Focus()

  2. simulate mouse click using this following code

    SendKeys.Send("{ENTER}")

How to replace all spaces in a string

Simple code for replace all spaces

var str = 'How are you';
var replaced = str.split(' ').join('');

Out put: Howareyou

Caused by: java.security.UnrecoverableKeyException: Cannot recover key

I had the same error when we imported a key into a keystore that was build using a 64bit OpenSSL Version. When we followed the same procedure to import the key into a keystore that was build using a 32 bit OpenSSL version everything went fine.

How can I calculate divide and modulo for integers in C#?

Division is performed using the / operator:

result = a / b;

Modulo division is done using the % operator:

result = a % b;

How to read file with async/await properly?

To keep it succint and retain all functionality of fs:

const fs = require('fs');
const fsPromises = fs.promises;

async function loadMonoCounter() {
    const data = await fsPromises.readFile('monolitic.txt', 'binary');
    return new Buffer(data);
}

Importing fs and fs.promises separately will give access to the entire fs API while also keeping it more readable... So that something like the next example is easily accomplished.

// the 'next example'
fsPromises.access('monolitic.txt', fs.constants.R_OK | fs.constants.W_OK)
    .then(() => console.log('can access'))
    .catch(() => console.error('cannot access'));

How to update UI from another thread running in another class

I am going to throw you a curve ball here. If I have said it once I have said it a hundred times. Marshaling operations like Invoke or BeginInvoke are not always the best methods for updating the UI with worker thread progress.

In this case it usually works better to have the worker thread publish its progress information to a shared data structure that the UI thread then polls at regular intervals. This has several advantages.

  • It breaks the tight coupling between the UI and worker thread that Invoke imposes.
  • The UI thread gets to dictate when the UI controls get updated...the way it should be anyway when you really think about it.
  • There is no risk of overrunning the UI message queue as would be the case if BeginInvoke were used from the worker thread.
  • The worker thread does not have to wait for a response from the UI thread as would be the case with Invoke.
  • You get more throughput on both the UI and worker threads.
  • Invoke and BeginInvoke are expensive operations.

So in your calcClass create a data structure that will hold the progress information.

public class calcClass
{
  private double percentComplete = 0;

  public double PercentComplete
  {
    get 
    { 
      // Do a thread-safe read here.
      return Interlocked.CompareExchange(ref percentComplete, 0, 0);
    }
  }

  public testMethod(object input)
  {
    int count = 1000;
    for (int i = 0; i < count; i++)
    {
      Thread.Sleep(10);
      double newvalue = ((double)i + 1) / (double)count;
      Interlocked.Exchange(ref percentComplete, newvalue);
    }
  }
}

Then in your MainWindow class use a DispatcherTimer to periodically poll the progress information. Configure the DispatcherTimer to raise the Tick event on whatever interval is most appropriate for your situation.

public partial class MainWindow : Window
{
  public void YourDispatcherTimer_Tick(object sender, EventArgs args)
  {
    YourProgressBar.Value = calculation.PercentComplete;
  }
}

A generic error occurred in GDI+, JPEG Image to MemoryStream

Had a very similar problem and also tried cloning the image which doesn't work. I found that the best solution was to create a new Bitmap object from the image that was loaded from the memory stream. That way the stream can be disposed of e.g.

using (var m = new MemoryStream())
{
    var img = new Bitmap(Image.FromStream(m));
    return img;
}

Hope this helps.

Regular expression for exact match of a string

if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:

/^123456$/

in perl the test for matching the password would be something like

print "MATCH_OK" if ($input_pass=~/^123456$/);

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

Can't check signature: public key not found

I got the same message but my files are decrypted as expected. Please check in your destination path if you could see the output file file.

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

C# Java HashMap equivalent

I just wanted to give my two cents.
This is according to @Powerlord 's answer.

Puts "null" instead of null strings.

private static Dictionary<string, string> map = new Dictionary<string, string>();

public static void put(string key, string value)
{
    if (value == null) value = "null";
    map[key] = value;
}

public static string get(string key, string defaultValue)
{
    try
    {
        return map[key];
    }
    catch (KeyNotFoundException e)
    {
        return defaultValue;
    }
}

public static string get(string key)
{
    return get(key, "null");
}

How to select specific columns in laravel eloquent

By using all() method we can select particular columns from table like as shown below.

ModelName::all('column1', 'column2', 'column3');

Note: Laravel 5.4

How do you get the file size in C#?

MSDN FileInfo.Length says that it is "the size of the current file in bytes."

My typical Google search for something like this is: msdn FileInfo

MySQL: Insert record if not exists in table

I had a problem, and the method Mike advised worked partly, I had an error Dublicate Column name = '0', and changed the syntax of your query as this`

     $tQ = "INSERT  INTO names (name_id, surname_id, sum, sum2, sum3,sum4,sum5) 
                SELECT '$name', '$surname', '$sum', '$sum2', '$sum3','$sum4','$sum5' 
FROM DUAL
                WHERE NOT EXISTS (
                SELECT sum FROM names WHERE name_id = '$name' 
AND surname_id = '$surname') LIMIT 1;";

The problem was with column names. sum3 was equal to sum4 and mysql throwed dublicate column names, and I wrote the code in this syntax and it worked perfectly,

How to loop and render elements in React.js without an array of objects to map?

You can still use map if you can afford to create a makeshift array:

{
    new Array(this.props.level).fill(0).map((_, index) => (
        <span className='indent' key={index}></span>
    ))
}

This works because new Array(n).fill(x) creates an array of size n filled with x, which can then aid map.

array-fill

Python wildcard search in string

Same idea as Yuushi in using regular expressions, but this uses the findall method within the re library instead of a list comprehension:

import re
regex = re.compile('th.s')
l = ['this', 'is', 'just', 'a', 'test']
matches = re.findall(regex, string)

How to check whether a int is not null or empty?

public class Demo {
    private static int i;
    private static Integer j;
    private static int k = -1;

    public static void main(String[] args) {
        System.out.println(i+" "+j+" "+k);
    }
}

OutPut: 0 null -1

Post-increment and Pre-increment concept?

int i = 1;
int j = 1;

int k = i++; // post increment
int l = ++j; // pre increment

std::cout << k; // prints 1
std::cout << l; // prints 2

Post increment implies the value i is incremented after it has been assigned to k. However, pre increment implies the value j is incremented before it is assigned to l.

The same applies for decrement.

Unable to open debugger port in IntelliJ

Your Service/ Application might already be running. In Search enter Services and you will get list of services. Stop yours and then try again.

How do I use vim registers?

A cool trick is to use "1p to paste the last delete/change (, and then use . to repeatedly to paste the subsequent deletes. In other words, "1p... is basically equivalent to "1p"2p"3p"4p.

You can use this to reverse-order a handful of lines: dddddddddd"1p....

PostgreSQL next value of the sequences?

To answer your question literally, here's how to get the next value of a sequence without incrementing it:

SELECT
 CASE WHEN is_called THEN
   last_value + 1
 ELSE
   last_value
 END
FROM sequence_name

Obviously, it is not a good idea to use this code in practice. There is no guarantee that the next row will really have this ID. However, for debugging purposes it might be interesting to know the value of a sequence without incrementing it, and this is how you can do it.

Display array values in PHP

you can easily use join()

$fruits = array("apple", "banana", "orange");
print join(" ".$fruits);

Bootstrap 4 navbar color

To change navbar background color:

.navbar-custom {

    background-color: yourcolor !important;
}

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

Cannot find firefox binary in PATH. Make sure firefox is installed

I didn't see the C# anwer to this question here. The trick is to set the BrowserExecutableLocation property on a FirefoxOptions instance, and pass that into the driver constructor:

        var opt = new FirefoxOptions
        {
            BrowserExecutableLocation = @"c:\program files\mozilla firefox\firefox.exe"
        };
        var driver = new FirefoxDriver(opt);

Prevent jQuery UI dialog from setting focus to first textbox

jQuery UI 1.10.0 Changelog lists ticket 4731 as being fixed.

Looks like focusSelector was not implemented, but a cascading search for various elements was used instead. From the ticket:

Extend autofocus, starting with [autofocus], then :tabbable content, then buttonpane, then close button, then dialog

So, mark an element with the autofocus attribute and that is the element that should get the focus:

<input autofocus>

In the documentation, the focus logic is explained (just under the table of contents, under the title 'Focus'):

Upon opening a dialog, focus is automatically moved to the first item that matches the following:

  1. The first element within the dialog with the autofocus attribute
  2. The first :tabbable element within the dialog's content
  3. The first :tabbable element within the dialog's buttonpane
  4. The dialog's close button
  5. The dialog itself

Using .text() to retrieve only text not nested in child tags

I liked this reusable implementation based on the clone() method found here to get only the text inside the parent element.

Code provided for easy reference:

$("#foo")
    .clone()    //clone the element
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
    .text();

Count characters in textarea

HTML sample, used wherever I need a counter, notice the relevance of IDs of textarea and second span : id="post" <-> id="rem_post" and the title of the span that holds the desired characters amount of each particular textarea

<textarea class="countit" name="post" id="post"></textarea>
<p>
  <span>characters remaining: <span id="rem_post" title="1000"></span></span>
</p>

JavaScript function, usually placed before </body> in my template file, requires jQuery

$(".countit").keyup(function () {
  var cmax = $("#rem_" + $(this).attr("id")).attr("title");

  if ($(this).val().length >= cmax) {
    $(this).val($(this).val().substr(0, cmax));
  }

  $("#rem_" + $(this).attr("id")).text(cmax - $(this).val().length);

});

Understanding MongoDB BSON Document size limit

I have not yet seen a problem with the limit that did not involve large files stored within the document itself. There are already a variety of databases which are very efficient at storing/retrieving large files; they are called operating systems. The database exists as a layer over the operating system. If you are using a NoSQL solution for performance reasons, why would you want to add additional processing overhead to the access of your data by putting the DB layer between your application and your data?

JSON is a text format. So, if you are accessing your data through JSON, this is especially true if you have binary files because they have to be encoded in uuencode, hexadecimal, or Base 64. The conversion path might look like

binary file <> JSON (encoded) <> BSON (encoded)

It would be more efficient to put the path (URL) to the data file in your document and keep the data itself in binary.

If you really want to keep these files of unknown length in your DB, then you would probably be better off putting these in GridFS and not risking killing your concurrency when the large files are accessed.

How to backup Sql Database Programmatically in C#

you can connect to the database using SqlConnection and SqlCommand and execute the following command text for example:

BACKUP DATABASE [MyDatabase] TO  DISK = 'C:\....\MyDatabase.bak'

See here for examples.

Spring - applicationContext.xml cannot be opened because it does not exist

your-module/src/applicationContext.xml

val context = ClassPathXmlApplicationContext("applicationContext.xml")

Check the directory path, the default path is /src/ and not /.

GL

Linq select to new object

All of the grouped objects, or all of the types? It sounds like you may just want:

var query = types.GroupBy(t => t.Type)
                 .Select(g => new { Type = g.Key, Count = g.Count() });

foreach (var result in query)
{
    Console.WriteLine("{0}, {1}", result.Type, result.Count);
}

EDIT: If you want it in a dictionary, you can just use:

var query = types.GroupBy(t => t.Type)
                 .ToDictionary(g => g.Key, g => g.Count());

There's no need to select into pairs and then build the dictionary.

How to make an HTML back link?

history.go(-1) doesn't work if you click around in the 2nd domain or if the referrer is empty.

So we have to store the historyCount on arriving to this domain and go back the number of navigations in this side minus 1.


// if referrer is different from this site
if (!document.referrer.includes(window.location.host)) {
  // store current history length
  localStorage.setItem('historyLength', `${history.length}`);
}

// Return to stored referrer on logo click
document.querySelector('header .logo').addEventListener('click', 
  () =>
   history.go(Number(localStorage.getItem('historyLength')) - history.length -1)
);

builder for HashMap

This is similar to the accepted answer, but a little cleaner, in my view:

ImmutableMap.of("key1", val1, "key2", val2, "key3", val3);

There are several variations of the above method, and they are great for making static, unchanging, immutable maps.

Counting array elements in Python

If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:

import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2

This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.

import numpy as np
len(a) == np.shape(a)[0]

To get the number of elements in a multi-dimensional array of arbitrary shape:

import numpy as np
size = 1
for dim in np.shape(a): size *= dim

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Custom Date/Time formatting in SQL Server

If it's something more specific like DateKey (yyyymmdd) that you need for dimensional models, I suggest something without any casts/converts:

DECLARE @DateKeyToday int = (SELECT 10000 * DATEPART(yy,GETDATE()) + 100 * DATEPART(mm,GETDATE()) + DATEPART(dd,GETDATE()));
PRINT @DateKeyToday

Get the first N elements of an array?

array_slice() is best thing to try, following are the examples:

<?php
$input = array("a", "b", "c", "d", "e");

$output = array_slice($input, 2);      // returns "c", "d", and "e"
$output = array_slice($input, -2, 1);  // returns "d"
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

Permission denied on accessing host directory in Docker

See this Project Atomic blog post about Volumes and SELinux for the full story.

Specifically:

This got easier recently since Docker finally merged a patch which will be showing up in docker-1.7 (We have been carrying the patch in docker-1.6 on RHEL, CentOS, and Fedora).

This patch adds support for "z" and "Z" as options on the volume mounts (-v).

For example:

docker run -v /var/db:/var/db:z rhel7 /bin/sh

Will automatically do the chcon -Rt svirt_sandbox_file_t /var/db described in the man page.

Even better, you can use Z.

docker run -v /var/db:/var/db:Z rhel7 /bin/sh

This will label the content inside the container with the exact MCS label that the container will run with, basically it runs chcon -Rt svirt_sandbox_file_t -l s0:c1,c2 /var/db where s0:c1,c2 differs for each container.

Install a Nuget package in Visual Studio Code

The answers above are good, but insufficient if you have more than 1 project (.csproj) in the same folder.

First, you easily add the "PackageReference" tag to the .csproj file (either manually, by using the nuget package manager or by using the dotnet add package command).

But then, you need to run the "restore" command manually so you can tell it which project you are trying to restore (if I just clicked the restore button that popped up, nothing happened). You can do that by running:

dotnet restore Project-File-Name.csproj

And that installs the package

jQuery - Increase the value of a counter when a button is clicked

Go to the below site and tryout. http://www.counter12.com/

From the above link I have selected the one design that I liked to have in my site accepted terms and it has given me a div that I have pasted in my html page.

It did awesomely worked.

I am not answering to your problem on JQuery, but giving you an alternate solution for your problem.

Get the new record primary key ID from MySQL insert query?

BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.

I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.

The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.

IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

This works perfectly fine for me:

AdapterChart adapterChart = new AdapterChart(getContext(),messageList);
recyclerView.setAdapter(adapterChart);
recyclerView.scrollToPosition(recyclerView.getAdapter().getItemCount()-1);

How to sort by Date with DataTables jquery plugin?

You should make use of the HTML5 Data Attributes. https://www.datatables.net/examples/advanced_init/html5-data-attributes.html

Just add the data-order element to your td element.
No plugins required.

<table class="table" id="exampleTable">
    <thead>
        <tr>
            <th>Firstname</th>
            <th>Sign Up Date</th>
        </tr>
    </thead>

    <tbody>

        <tr>
            <td>Peter</td>
            <td data-order="2015-11-13 12:00">13. November 2015</td>
        </tr>
        <tr>
            <td>Daniel</td>
            <td data-order="2015-08-06 13:44">06. August 2015</td>
        </tr>
        <tr>
            <td>Michael</td>
            <td data-order="2015-10-14 16:12">14. October 2015</td>
        </tr>
    </tbody>
</table>


<script>
    $(document).ready(function() {
        $('#exampleTable').DataTable();
    });
</script>

Error message "Strict standards: Only variables should be passed by reference"

The cause of the error is the use of the internal PHP programming data structures function, array_shift() [php.net/end].

The function takes an array as a parameter. Although an ampersand is indicated in the prototype of array_shift() in the manual", there isn't any cautionary documentation following in the extended definition of that function, nor is there any apparent explanation that the parameter is in fact passed by reference.

Perhaps this is /understood/. I did not understand, however, so it was difficult for me to detect the cause of the error.

Reproduce code:

function get_arr()
{
    return array(1, 2);
}
$array = get_arr();
$el = array_shift($array);

What is the best/simplest way to read in an XML file in Java application?

I've only used jdom. It's pretty easy.

Go here for documentation and to download it: http://www.jdom.org/

If you have a very very large document then it's better not to read it all into memory, but use a SAX parser which calls your methods as it hits certain tags and attributes. You have to then create a state machine to deal with the incoming calls.

Getting the "real" Facebook profile picture URL from graph API

I realize this is late, but there is another way to obtain the URL of the profile image.

To your original url, you can add the parameter redirect=false to obtain the actual URL of the image you'd normally be redirected to.

So, the new request would look like http://graph.facebook.com/517267866/picture?type=large&redirect=false. This will return a JSON object containing the URL of the picture and a boolean is_silhouette (true if the picture is the default Facebook picture).

The picture will be of the size you specified, as well. You can test this additionally by adding dimensions: http://graph.facebook.com/517267866/picture?type=large&redirect=false&width=400&height=400

Git Push error: refusing to update checked out branch

cd into the repo/directory that you're pushing into on the remote machine and enter

$ git config core.bare true

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

What is the fastest way to send 100,000 HTTP requests in Python?

Consider using Windmill , although Windmill probably cant do that many threads.

You could do it with a hand rolled Python script on 5 machines, each one connecting outbound using ports 40000-60000, opening 100,000 port connections.

Also, it might help to do a sample test with a nicely threaded QA app such as OpenSTA in order to get an idea of how much each server can handle.

Also, try looking into just using simple Perl with the LWP::ConnCache class. You'll probably get more performance (more connections) that way.

Angular - ng: command not found

Try uninstalling the angular cli installed

npm uninstall -g angular-cli npm uninstall -g @angular/cli

The clean the node cache npm cache clean

Then npm install -g @angular/cli@latest

set Path the path C:\Users\admin\AppData\Roaming\npm\node_modules@angular\cli

Computing cross-correlation function?

For 1D array, numpy.correlate is faster than scipy.signal.correlate, under different sizes, I see a consistent 5x peformance gain using numpy.correlate. When two arrays are of similar size (the bright line connecting the diagonal), the performance difference is even more outstanding (50x +).

# a simple benchmark
res = []
for x in range(1, 1000):
    list_x = []
    for y in range(1, 1000): 

        # generate different sizes of series to compare
        l1 = np.random.choice(range(1, 100), size=x)
        l2 = np.random.choice(range(1, 100), size=y)

        time_start = datetime.now()
        np.correlate(a=l1, v=l2)
        t_np = datetime.now() - time_start

        time_start = datetime.now()
        scipy.signal.correlate(in1=l1, in2=l2)
        t_scipy = datetime.now() - time_start

        list_x.append(t_scipy / t_np)
    res.append(list_x)
plt.imshow(np.matrix(res))

enter image description here

As default, scipy.signal.correlate calculates a few extra numbers by padding and that might explained the performance difference.

>> l1 = [1,2,3,2,1,2,3]
>> l2 = [1,2,3]
>> print(numpy.correlate(a=l1, v=l2))
>> print(scipy.signal.correlate(in1=l1, in2=l2))

[14 14 10 10 14]
[ 3  8 14 14 10 10 14  8  3]  # the first 3 is [0,0,1]dot[1,2,3]

How to set thousands separator in Java?

If you are using thousand separator for Integer data type use 1.

  1. For integer data Type

String.format("%,d\n", 58625) and output will be 58,625

  1. For Floating Point data Type String.format("%,.2f",58625.21) and output will be 58,625.21

How to get the caller class in Java

Since I currently have the same problem here is what I do:

  1. I prefer com.sun.Reflection instead of stackTrace since a stack trace is only producing the name not the class (including the classloader) itself.

  2. The method is deprecated but still around in Java 8 SDK.

// Method descriptor #124 (I)Ljava/lang/Class; (deprecated) // Signature: (I)Ljava/lang/Class<*>; @java.lang.Deprecated public static native java.lang.Class getCallerClass(int arg0);

  1. The method without int argument is not deprecated

// Method descriptor #122 ()Ljava/lang/Class; // Signature: ()Ljava/lang/Class<*>; @sun.reflect.CallerSensitive public static native java.lang.Class getCallerClass();

Since I have to be platform independent bla bla including Security Restrictions, I just create a flexible method:

  1. Check if com.sun.Reflection is available (security exceptions disable this mechanism)

  2. If 1 is yes then get the method with int or no int argument.

  3. If 2 is yes call it.

If 3. was never reached, I use the stack trace to return the name. I use a special result object that contains either the class or the string and this object tells exactly what it is and why.

[Summary] I use stacktrace for backup and to bypass eclipse compiler warnings I use reflections. Works very good. Keeps the code clean, works like a charm and also states the problems involved correctly.

I use this for quite a long time and today I searched a related question so

Refresh/reload the content in Div using jquery/ajax

I know the topic is old, but you can declare the Ajax as a variable, then use a function to call the variable on the desired content. Keep in mind you are calling what you have in the Ajax if you want a different elements from the Ajax you need to specify it.

Example:

Var infogen = $.ajax({'your query')};

$("#refresh").click(function(){
  infogen;
  console.log("to verify");
});    

Hope helps

if not try:

$("#refresh").click(function(){
      loca.tion.reload();
      console.log("to verify");
    });    

How to align the text middle of BUTTON

I think you can use Padding like: Hope this one can help you.

.loginButton {
    background:url(images/loginBtn-center.jpg) repeat-x;
    width:175px;
    height:65px;
    margin:20px auto;
    border-radius:10px;
    -webkit-border-radius:10px;
    box-shadow:0 1px 2px #5e5d5b;
    <!--Using padding to align text in box or image-->
    padding: 3px 2px;
}

How to add app icon within phonegap projects?

In cordova 3.3.1-0.1.2 the expected behavior is not working right.

in

http://cordova.apache.org/docs/en/3.3.0/config_ref_images.md.html#Icons%20and%20Splash%20Screens

it clearly states you're suppose to put them into your main www folder in a folder called res and icons that follow a particular naming convention instead of the original customizable config.xml specified way (in which you point to a file of your choosing, which was/is much better). it should take then from there for each platform and put them into the platforms/?android?/res/drawable-?dpi/icon.png but it does no such correct behavior at this time... bug.

so I guess we have to manually put them there for each platform. it would of course need to remove that from duplicating it into the www folder again. for me I had to totally replace the contents in the main www folder anyway because it simply didn't work with even hello world without hacking a redirect index.html to find some weird random folder there. Putting the res folder beside www makes the most sense but what ever it seems to be for me caused by this series of cascading and confusing design choices/flaws.

Is there a way I can retrieve sa password in sql server 2005

Granted you have administrative Windows privileges on the server, another option would be to start SQL Server in Single User Mode, using the Startup parameter "-m". Doing this, you can login using SQLCMD, create a new user and give it sysadmin privileges. Finally, you have to disable Single User Mode, login to SSMS using your new user, and go to Segurity/Logins and change "sa" user password.

You can check this post: http://v-consult.be/2011/05/26/recover-sa-password-microsoft-sql-server-2008-r2/

How to check if JSON return is empty with jquery

Below code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.

   // works for any Object Including JSON(key value pair) or Array.
  //  var arr = [];
  //  var jsonObj = {};
    if (jQuery.isEmptyObject(anyObjectIncludingJSON))
    {
       console.log("Empty Object");
    }

How to configure logging to syslog in Python?

I add a little extra comment just in case it helps anyone because I found this exchange useful but needed this little extra bit of info to get it all working.

To log to a specific facility using SysLogHandler you need to specify the facility value. Say for example that you have defined:

local3.* /var/log/mylog

in syslog, then you'll want to use:

handler = logging.handlers.SysLogHandler(address = ('localhost',514), facility=19)

and you also need to have syslog listening on UDP to use localhost instead of /dev/log.

ActionBarCompat: java.lang.IllegalStateException: You need to use a Theme.AppCompat

To simply add ActionBar Compat your activity or application should use @style/Theme.AppCompat theme in AndroidManifest.xml like this:

   <activity
        ...
        android:theme="@style/Theme.AppCompat" />

This will add actionbar in activty(or all activities if you added this theme to application)


But usually you need to customize you actionbar. To do this you need to create two styles with Theme.AppCompat parent, for example, "@style/Theme.AppCompat.Light". First one will be for api 11>= (versions of android with build in android actionbar), second one for api 7-10 (no build in actionbar).

Let's look at first style. It will be located in res/values-v11/styles.xml . It will look like this:

<style name="Theme.Styled" parent="@style/Theme.AppCompat.Light">
    <!-- Setting values in the android namespace affects API levels 11+ -->
    <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

<style name="Widget.Styled.ActionBar" parent="@style/Widget.AppCompat.Light.ActionBar">
    <!-- Setting values in the android namespace affects API levels 11+ -->
    <item name="android:background">@drawable/ab_custom_solid_styled</item>
    <item name="android:backgroundStacked"
      >@drawable/ab_custom_stacked_solid_styled</item>
    <item name="android:backgroundSplit"
      >@drawable/ab_custom_bottom_solid_styled</item>
</style>

And you need to have same style for api 7-10. It will be located in res/values/styles.xml, BUT because that api levels don't yet know about original android actionbar style items, we should use one, provided by support library. ActionBar Compat items are defined just like original android, but without "android:" part in the front:

<style name="Theme.Styled" parent="@style/Theme.AppCompat.Light">
    <!-- Setting values in the default namespace affects API levels 7-11 -->
    <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

<style name="Widget.Styled.ActionBar" parent="@style/Widget.AppCompat.Light.ActionBar">
    <!-- Setting values in the default namespace affects API levels 7-11 -->
    <item name="background">@drawable/ab_custom_solid_styled</item>
    <item name="backgroundStacked">@drawable/ab_custom_stacked_solid_styled</item>
    <item name="backgroundSplit">@drawable/ab_custom_bottom_solid_styled</item>
</style>

Please mark that, even if api levels higher than 10 already have actionbar you should still use AppCompat styles. If you don't, you will have this error on launch of Acitvity on devices with android 3.0 and higher:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

Here is link this original article http://android-developers.blogspot.com/2013/08/actionbarcompat-and-io-2013-app-source.html written by Chris Banes.

P.S. Sorry for my English

SQL Server : Transpose rows to columns

I had a slightly different requirement, whereby I had to selectively transpose columns into rows.

The table had columns:

create table tbl (ID, PreviousX, PreviousY, CurrentX, CurrentY)

I needed columns for Previous and Current, and rows for X and Y. A Cartesian product generated on a static table worked nicely, eg:

select 
    ID,
    max(case when metric='X' then PreviousX
        case when metric='Y' then PreviousY end) as Previous,
    max(case when metric='X' then CurrentX
        case when metric='Y' then CurrentY end) as Current
from tbl inner join
    /* Cartesian product - transpose by repeating row and 
    picking appropriate metric column for period */
    ( VALUES (1, 'X'), (2, 'Y')) AS x (sort, metric) ON 1=1
group by ID
order by ID, sort

PostgreSQL "DESCRIBE TABLE"

When your table is not part of the default schema, you should write:

\d+ schema_name.table_name

Otherwise, you would get the error saying that "the relation doesn not exist."

Is it ok to use `any?` to check if an array is not empty?

I don't think it's bad to use any? at all. I use it a lot. It's clear and concise.

However if you are concerned about all nil values throwing it off, then you are really asking if the array has size > 0. In that case, this dead simple extension (NOT optimized, monkey-style) would get you close.

Object.class_eval do

  def size?
    respond_to?(:size) && size > 0
  end

end

> "foo".size?
 => true
> "".size?
 => false
> " ".size?
 => true
> [].size?
 => false
> [11,22].size?
 => true
> [nil].size?
 => true

This is fairly descriptive, logically asking "does this object have a size?". And it's concise, and it doesn't require ActiveSupport. And it's easy to build on.

Some extras to think about:

  1. This is not the same as present? from ActiveSupport.
  2. You might want a custom version for String, that ignores whitespace (like present? does).
  3. You might want the name length? for String or other types where it might be more descriptive.
  4. You might want it custom for Integer and other Numeric types, so that a logical zero returns false.

Android; Check if file exists without creating a new one

Kotlin Extension Properties

No file will be create when you make a File object, it is only an interface.

To make working with files easier, there is an existing .toFile function on Uri

You can also add an extension property on File and/or Uri, to simplify usage further.

val File?.exists get() = this?.exists() ?: false
val Uri?.exists get() = File(this.toString).exists()

Then just use uri.exists or file.exists to check.

WP -- Get posts by category?

add_shortcode( 'seriesposts', 'series_posts' );

function series_posts( $atts )
{ ob_start();

$myseriesoption = get_option( '_myseries', null );

$type = $myseriesoption;
$args=array(  'post_type' => $type,  'post_status' => 'publish',  'posts_per_page' => 5,  'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>'; 
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>'; 
endwhile;
echo '</ul>'; 
}
wp_reset_query();




return ob_get_clean(); }

//this will generate a shortcode function to be used on your site [seriesposts]