Programs & Examples On #Tibco

Tibco is a software company that produces infrastructure and business intelligence software, most notably an event-enabling Enterprise Information Bus.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

Edit 2: See @flodel's answer. Much better.

Try:

# assuming SFI is your data.frame
as.matrix(sapply(SFI, as.numeric))  

Edit: or as @ CarlWitthoft suggested in the comments:

matrix(as.numeric(unlist(SFI)),nrow=nrow(SFI))

Boolean vs tinyint(1) for boolean values in MySQL

My experience when using Dapper to connect to MySQL is that it does matter. I changed a non nullable bit(1) to a nullable tinyint(1) by using the following script:

ALTER TABLE TableName MODIFY Setting BOOLEAN null;

Then Dapper started throwing Exceptions. I tried to look at the difference before and after the script. And noticed the bit(1) had changed to tinyint(1).

I then ran:

ALTER TABLE TableName CHANGE COLUMN Setting Setting BIT(1) NULL DEFAULT NULL;

Which solved the problem.

Spark: subtract two DataFrames

According to the api docs, doing:

dataFrame1.except(dataFrame2)

will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.

How can I debug my JavaScript code?

You might also check out YUI Logger. All you have to do to use it is include a couple of tags in your HTML. It is a helpful addition to Firebug, which is more or less a must.

Shrink a YouTube video to responsive width

I used the CSS in the accepted answer here for my responsive YouTube videos - worked great right up until YouTube updated their system around the start of August 2015. The videos on YouTube are the same dimensions but for whatever reason the CSS in the accepted answer now letterboxes all our videos. Black bands across top and bottom.

I've tickered around with the sizes and settled on getting rid of the top padding and changing the bottom padding to 56.45%. Seems to look good.

.videowrapper {
    position: relative;
    padding-bottom: 56.45%;
    height: 0;
}

What are the differences between normal and slim package of jquery?

At this time, the most authoritative answer appears to be in this issue, which states "it is a custom build of jQuery that excludes effects, ajax, and deprecated code." Details will be announced with jQuery 3.0.

I suspect that the rationale for excluding these components of the jQuery library is in recognition of the increasingly common scenario of jQuery being used in conjunction with another JS framework like Angular or React. In these cases, the usage of jQuery is primarily for DOM traversal and manipulation, so leaving out those components that are either obsolete or are provided by the framework gains about a 20% reduction in file size.

Is there a way to instantiate a class by name in Java?

MyClass myInstance = (MyClass) Class.forName("MyClass").newInstance();

What does /p mean in set /p?

The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.

Two ways I've used it... first:

SET /P variable=

When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.

And second:

SET /P variable=<%temp%\filename.txt

Will set variable to contents (the first line) of the txt file. This method won't work unless the /P is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.

JSON to TypeScript class instance?

This question is quite broad, so I'm going to give a couple of solutions.

Solution 1: Helper Method

Here's an example of using a Helper Method that you could change to fit your needs:

class SerializationHelper {
    static toInstance<T>(obj: T, json: string) : T {
        var jsonObj = JSON.parse(json);

        if (typeof obj["fromJSON"] === "function") {
            obj["fromJSON"](jsonObj);
        }
        else {
            for (var propName in jsonObj) {
                obj[propName] = jsonObj[propName]
            }
        }

        return obj;
    }
}

Then using it:

var json = '{"name": "John Doe"}',
    foo = SerializationHelper.toInstance(new Foo(), json);

foo.GetName() === "John Doe";

Advanced Deserialization

This could also allow for some custom deserialization by adding your own fromJSON method to the class (this works well with how JSON.stringify already uses the toJSON method, as will be shown):

interface IFooSerialized {
    nameSomethingElse: string;
}

class Foo {
  name: string;
  GetName(): string { return this.name }

  toJSON(): IFooSerialized {
      return {
          nameSomethingElse: this.name
      };
  }

  fromJSON(obj: IFooSerialized) {
        this.name = obj.nameSomethingElse;
  }
}

Then using it:

var foo1 = new Foo();
foo1.name = "John Doe";

var json = JSON.stringify(foo1);

json === '{"nameSomethingElse":"John Doe"}';

var foo2 = SerializationHelper.toInstance(new Foo(), json);

foo2.GetName() === "John Doe";

Solution 2: Base Class

Another way you could do this is by creating your own base class:

class Serializable {
    fillFromJSON(json: string) {
        var jsonObj = JSON.parse(json);
        for (var propName in jsonObj) {
            this[propName] = jsonObj[propName]
        }
    }
}

class Foo extends Serializable {
    name: string;
    GetName(): string { return this.name }
}

Then using it:

var foo = new Foo();
foo.fillFromJSON(json);

There's too many different ways to implement a custom deserialization using a base class so I'll leave that up to how you want it.

How to test android apps in a real device with Android Studio?

I tried @Mr. Stark answer. It didn't work. It failed to install the drive. I have Samsung S8 plus. I enabled the debugging mode on device then installed Android USB Driver for Windows from Samsung site, it works.

Use of True, False, and None as return values in Python functions

Use if foo or if not foo. There isn't any need for either == or is for that.

For checking against None, is None and is not None are recommended. This allows you to distinguish it from False (or things that evaluate to False, like "" and []).

Whether get_attr should return None would depend on the context. You might have an attribute where the value is None, and you wouldn't be able to do that. I would interpret None as meaning "unset", and a KeyError would mean the key does not exist in the file.

What is log4j's default log file dumping path

To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Follow this tutorial to learn more about log4j usage:

http://www.mkyong.com/logging/log4j-log4j-properties-examples/

Generating a drop down list of timezones with PHP

Here's one that creates a multidimensional array sorted by offset and niceified name:

function timezones() {
    $timezones = [];

    foreach (timezone_identifiers_list() as $timezone) {
        $datetime = new \DateTime('now', new DateTimeZone($timezone));
        $timezones[] = [
            'sort' => str_replace(':', '', $datetime->format('P')),
            'offset' => $datetime->format('P'),
            'name' => str_replace('_', ' ', implode(', ', explode('/', $timezone))),
            'timezone' => $timezone,
        ];
    }

    usort($timezones, function($a, $b) {
        return $a['sort'] - $b['sort'] ?: strcmp($a['name'], $b['name']);
    });

    return $timezones;
}

foreach (timezones() as $timezone) {
    echo '(UTC '.$timezone['offset'].') '.$timezone['name'].'<br>';
}

Echos:

(UTC -11:00) Pacific, Midway
(UTC -11:00) Pacific, Niue
(UTC -11:00) Pacific, Pago Pago
(UTC -10:00) Pacific, Honolulu
(UTC -10:00) Pacific, Johnston
(UTC -10:00) Pacific, Rarotonga
(UTC -10:00) Pacific, Tahiti
(UTC -09:30) Pacific, Marquesas
(UTC -09:00) America, Adak
(UTC -09:00) Pacific, Gambier
(UTC -08:00) America, Anchorage
(UTC -08:00) America, Juneau
...

Getting started with OpenCV 2.4 and MinGW on Windows 7

If you installed opencv 2.4.2 then you need to change the -lopencv_core240 to -lopencv_core242

I made the same mistake.

Illegal mix of collations error in MySql

I also got same error, but in my case main problem was in where condition the parameter that i'm checking was having some unknown hidden character (+%A0)

When A0 convert I got 160 but 160 was out of the range of the character that db knows, that's why database cannot recognize it as character other thing is my table column is varchar

  • the solution that I did was I checked there is some characters like that and remove those before run the sql command

  • ex:- preg_replace('/\D/', '', $myParameter);

.NET Console Application Exit Event

You can use the ProcessExit event of the AppDomain:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           
        // do some work

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

Update

Here is a full example program with an empty "message pump" running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It's better to do that there than in ProcessExit for several reasons:

  • Avoid cross-threading problems; if external COM objects were created on the MessagePump thread, it's easier to deal with them there.
  • There is a time limit on ProcessExit (3 seconds by default), so if cleaning up is time consuming, it may fail if pefromed within that event handler.

Here is the code:

class Program
{
    private static bool _quitRequested = false;
    private static object _syncLock = new object();
    private static AutoResetEvent _waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        // start the message pumping thread
        Thread msgThread = new Thread(MessagePump);
        msgThread.Start();
        // read input to detect "quit" command
        string command = string.Empty;
        do
        {
            command = Console.ReadLine();
        } while (!command.Equals("quit", StringComparison.InvariantCultureIgnoreCase));
        // signal that we want to quit
        SetQuitRequested();
        // wait until the message pump says it's done
        _waitHandle.WaitOne();
        // perform any additional cleanup, logging or whatever
    }

    private static void SetQuitRequested()
    {
        lock (_syncLock)
        {
            _quitRequested = true;
        }
    }

    private static void MessagePump()
    {
        do
        {
            // act on messages
        } while (!_quitRequested);
        _waitHandle.Set();
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

How do I use the lines of a file as arguments of a command?

After editing @Wesley Rice's answer a couple times, I decided my changes were just getting too big to continue changing his answer instead of writing my own. So, I decided I need to write my own!

Read each line of a file in and operate on it line-by-line like this:

#!/bin/bash
input="/path/to/txt/file"
while IFS= read -r line
do
  echo "$line"
done < "$input"

This comes directly from author Vivek Gite here: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/. He gets the credit!

Syntax: Read file line by line on a Bash Unix & Linux shell:
1. The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line
2. while read -r line; do COMMAND; done < input.file
3. The -r option passed to read command prevents backslash escapes from being interpreted.
4. Add IFS= option before read command to prevent leading/trailing whitespace from being trimmed -
5. while IFS= read -r line; do COMMAND_on $line; done < input.file


And now to answer this now-closed question which I also had: Is it possible to `git add` a list of files from a file? - here's my answer:

Note that FILES_STAGED is a variable containing the absolute path to a file which contains a bunch of lines where each line is a relative path to a file I'd like to do git add on. This code snippet is about to become part of the "eRCaGuy_dotfiles/useful_scripts/sync_git_repo_to_build_machine.sh" file in this project, to enable easy syncing of files in development from one PC (ex: a computer I code on) to another (ex: a more powerful computer I build on): https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles.

while IFS= read -r line
do
    echo "  git add \"$line\""
    git add "$line" 
done < "$FILES_STAGED"

References:

  1. Where I copied my answer from: https://www.cyberciti.biz/faq/unix-howto-read-line-by-line-from-file/
  2. For loop syntax: https://www.cyberciti.biz/faq/bash-for-loop/

Related:

  1. How to read contents of file line-by-line and do git add on it: Is it possible to `git add` a list of files from a file?

Access Control Origin Header error using Axios in React Web throwing error in Chrome

For Spring Boot - React js apps I added @CrssOrigin annotation on the controller and it works:

@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
@RequestMapping("/api")

But take care to add localhost correct => 'http://localhost:3000', not with '/' at the end => 'http://localhost:3000/', this was my problem.

When to use "ON UPDATE CASCADE"

It's an excellent question, I had the same question yesterday. I thought about this problem, specifically SEARCHED if existed something like "ON UPDATE CASCADE" and fortunately the designers of SQL had also thought about that. I agree with Ted.strauss, and I also commented Noran's case.

When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)

So, I agree in two points:

(A.) Yes, in many times a better design can avoid it; BUT

(B.) In cases of migrations, replicating databases, or solving emergencies, it's a GREAT TOOL that fortunately was there when I went to search if it existed.

Get the filename of a fileupload in a document through JavaScript

RaYell, You don't need to parse the value returned. document.getElementById("FileUpload1").value returns only the file name with extension. This was useful for me because I wanted to copy the name of the file to be uploaded to an input box called 'title'. In my application, the uploaded file is renamed to the index generated by the backend database and the title is stored in the database.

How to create border in UIButton?

You don't need to import QuartzCore.h now. Taking iOS 8 sdk and Xcode 6.1 in referrence.

Directly use:

[[myButton layer] setBorderWidth:2.0f];
[[myButton layer] setBorderColor:[UIColor greenColor].CGColor];

Get list of all input objects using JavaScript, without accessing a form object

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
  // ...
}

How to specify table's height such that a vertical scroll bar appears?

This CSS also shows a fixed height HTML table. It sets the height of the HTML tbody to 400 pixels and the HTML tbody scrolls when the it is larger, retaining the HTML thead as a non-scrolling element.

In addition, each th cell in the heading and each td cell the body should be styled for the desired fixed width.

#the-table {
  display: block;
  background: white; /* optional */
}

#the-table thead {
  text-align: left; /* optional */
}

#the-table tbody {
  display: block;
  max-height: 400px;
  overflow-y: scroll;
}

How to return a value from a Form in C#?

delegates are the best option for sending data from one form to another.

public partial class frmImportContact : Form
{
     public delegate void callback_data(string someData);
    public event callback_data getData_CallBack;

    private void button_Click(object sender, EventArgs e)
    {
      string myData = "Top Secret Data To Share";
      getData_CallBack(myData);
    }

}

public partial class frmHireQuote : Form
{
     private void Button_Click(object sender, EventArgs e)
    {

      frmImportContact obj = new frmImportContact();
      obj.getData_CallBack += getData;
    }

    private void getData(string someData)
    {
         MessageBox.Show("someData");
    }
}

How to style a checkbox using CSS

A simple and lightweight template as well:

_x000D_
_x000D_
input[type=checkbox] {_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:checked:before {_x000D_
  content: "\2713";_x000D_
  background: #fffed5;_x000D_
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);_x000D_
  font-size: 20px;_x000D_
  text-align: center;_x000D_
  line-height: 8px;_x000D_
  display: inline-block;_x000D_
  width: 13px;_x000D_
  height: 15px;_x000D_
  color: #00904f;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-radius: 4px;_x000D_
  margin: -3px -3px;_x000D_
  text-indent: 1px;_x000D_
}_x000D_
_x000D_
input[type=checkbox]:before {_x000D_
  content: "\202A";_x000D_
  background: #ffffff;_x000D_
  text-shadow: 1px 1px 1px rgba(0, 0, 0, .2);_x000D_
  font-size: 20px;_x000D_
  text-align: center;_x000D_
  line-height: 8px;_x000D_
  display: inline-block;_x000D_
  width: 13px;_x000D_
  height: 15px;_x000D_
  color: #00904f;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-radius: 4px;_x000D_
  margin: -3px -3px;_x000D_
  text-indent: 1px;_x000D_
}
_x000D_
<input type="checkbox" checked="checked">checked1<br>_x000D_
<input type="checkbox">unchecked2<br>_x000D_
<input type="checkbox" checked="checked" id="id1">_x000D_
<label for="id1">checked2+label</label><br>_x000D_
<label for="id2">unchecked2+label+rtl</label>_x000D_
<input type="checkbox" id="id2">_x000D_
<br>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/rvgccn5b/

MessageBox Buttons?

  1. Your call to MessageBox.Show needs to pass MessageBoxButtons.YesNo to get the Yes/No buttons instead of the OK button.

  2. Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes....

if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
    // user clicked yes
}
else
{
    // user clicked no
}

Reducing the gap between a bullet and text in a list item

You could achieve this by setting the list-style-type to none, and setting the background-image of a list element to a generic bullet, like so:

ul {
    list-style-type: none;
}

li {
    background-image: url(bullet.jpg);
    background-repeat: no-repeat;
    background-position: 0px 50%;
    padding-left: 7px;
}

The outcome would look a little something like this:

alt text

With this approach, you aren't adding unnecessary span (or other) elements to your lists, which is arguably more practical (for later extendibility and other semantic reasons).

Custom toast on Android: a simple example

This is what I used

AllMethodsInOne.java

public static Toast displayCustomToast(FragmentActivity mAct, String toastText, String toastLength, String succTypeColor) {

    final Toast toast;

    if (toastLength.equals("short")) {
        toast = Toast.makeText(mAct, toastText, Toast.LENGTH_SHORT);
    } else {
        toast = Toast.makeText(mAct, toastText, Toast.LENGTH_LONG);
    }

    View tView = toast.getView();
    tView.setBackgroundColor(Color.parseColor("#053a4d"));
    TextView mText = (TextView) tView.findViewById(android.R.id.message);

    mText.setTypeface(applyFont(mAct));
    mText.setShadowLayer(0, 0, 0, 0);

    tView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            toast.cancel();
        }
    });
    tView.invalidate();
    if (succTypeColor.equals("red")) {
        mText.setTextColor(Color.parseColor("#debe33"));
        tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_red));
        // this is to show error message
    }
    if (succTypeColor.equals("green")) {
        mText.setTextColor(Color.parseColor("#053a4d"));
        tView.setBackground(mAct.getResources().getDrawable(R.drawable.toast_rounded_green));
        // this is to show success message
    }


    return toast;
}

YourFile.java

While calling just write below.

AllMethodsInOne.displayCustomToast(act, "This is custom toast", "long", "red").show();

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:

  • Verbose - Show all log messages (the default).
  • Debug - Show debug log messages that are useful during development only, as well as the message levels lower in this list.
  • Info - Show expected log messages for regular usage, as well as the message levels lower in this list.
  • Warn - Show possible issues that are not yet errors, as well as the message levels lower in this list.
  • Error - Show issues that have caused errors, as well as the message level lower in this list.
  • Assert - Show issues that the developer expects should never happen.

java.lang.Exception: No runnable methods exception in running JUnits

I got this error because I didn't create my own test suite correctly:

Here is how I did it correctly:

Put this in Foobar.java:

public class Foobar{
    public int getfifteen(){
        return 15;
    }
}

Put this in FoobarTest.java:

import static org.junit.Assert.*;
import junit.framework.JUnit4TestAdapter;
import org.junit.Test;
public class FoobarTest {
    @Test
    public void mytest() {
        Foobar f = new Foobar();

        assert(15==f.getfifteen());
    }
    public static junit.framework.Test suite(){
       return new JUnit4TestAdapter(FoobarTest.class);
    }
}

Download junit4-4.8.2.jar I used the one from here:

http://www.java2s.com/Code/Jar/j/Downloadjunit4jar.htm

Compile it:

javac -cp .:./libs/junit4-4.8.2.jar Foobar.java FoobarTest.java

Run it:

el@failbox /home/el $ java -cp .:./libs/* org.junit.runner.JUnitCore FoobarTest
JUnit version 4.8.2
.
Time: 0.009    
OK (1 test)

One test passed.

Asp.net Validation of viewstate MAC failed

This solution worked for me in ASP.NET 4.5 using a Web Forms site.

  1. Use the following site to generate a Machine Key: http://www.blackbeltcoder.com/Resources/MachineKey.aspx
  2. Copy Full Machine Key Code.
  3. Go To your Web.Config File.
  4. Paste the Machine Key in the following code section:
    <configuration>
      <system.web>
        <machineKey ... />
      </system.web>
    </configuration> 

You should not see the viewstate Mac failed error anymore. Each website in the same app pool should have a separate machine key otherwise this error will continue.

The source was not found, but some or all event logs could not be searched

I recently experienced the error, and none of the solutions worked for me. What resolved the error for me was adding the Application pool user to the Power Users group in computer management. I couldn't use the Administrator group due to a company policy.

How to Delete node_modules - Deep Nested Folder in Windows

Since this the top google result, this is what worked for me:

Update, if you have npm v5, use npx:

npx rimraf ./**/node_modules

Otherwise install RimRaf:

npm install rimraf -g

And in the project folder delete the node_modules folder with:

rimraf node_modules

If you want to recursively delete:

rimraf .\**\node_modules

[ http://www.nikola-breznjak.com/blog/nodejs/how-to-delete-node_modules-folder-on-windows-machine/ ]

How do I check if a directory exists? "is_dir", "file_exists" or both?

Second variant in question post is not ok, because, if you already have file with the same name, but it is not a directory, !file_exists($dir) will return false, folder will not be created, so error "failed to open stream: No such file or directory" will be occured. In Windows there is a difference between 'file' and 'folder' types, so need to use file_exists() and is_dir() at the same time, for ex.:

if (file_exists('file')) {
    if (!is_dir('file')) { //if file is already present, but it's not a dir
        //do something with file - delete, rename, etc.
        unlink('file'); //for example
        mkdir('file', NEEDED_ACCESS_LEVEL);
    }
} else { //no file exists with this name
    mkdir('file', NEEDED_ACCESS_LEVEL);
}

How To Launch Git Bash from DOS Command Line?

I'm not sure exactly what you mean by "full Git Bash environment", but I get the nice prompt if I do

"C:\Program Files\Git\bin\sh.exe" --login

In PowerShell

& 'C:\Program Files\Git\bin\sh.exe' --login

The --login switch makes the shell execute the login shell startup files.

Check if image exists on server using JavaScript?

You can refer this link for check if a image file exists with JavaScript.

checkImageExist.js:

    var image = new Image();
    var url_image = './ImageFolder/' + variable + '.jpg';
    image.src = url_image;
    if (image.width == 0) {
       return `<img src='./ImageFolder/defaultImage.jpg'>`;
    } else {
       return `<img src='./ImageFolder/`+variable+`.jpg'`;
    } } ```

IndentationError expected an indented block

This error also occurs if you have a block with no statements in it

For example:

def my_function():
    for i in range(1,10):


def say_hello():
    return "hello"

Notice that the for block is empty. You can use the pass statement if you want to test the remaining code in the module.

How to create a release signed apk file using Gradle?

If you want to avoid hardcoding your keystore & password in build.gradle, you can use a properties file as explained here: HANDLING SIGNING CONFIGS WITH GRADLE

Basically:

1) create a myproject.properties file at /home/[username]/.signing with such contents:

keystore=[path to]\release.keystore
keystore.password=*********
keyAlias=***********
keyPassword=********

2) create a gradle.properties file (perhaps at the root of your project directory) with the contents:

MyProject.properties=/home/[username]/.signing/myproject.properties

3) refer to it in your build.gradle like this:

    if(project.hasProperty("MyProject.properties")
        && new File(project.property("MyProject.properties")).exists()) {

    Properties props = new Properties()
    props.load(new FileInputStream(file(project.property("MyProject.properties"))))

    signingConfigs {
        release {
            storeFile file(props['keystore'])
            storePassword props['keystore.password']
            keyAlias props['keyAlias']
            keyPassword props['keyPassword']
        }
    }
}

document.getElementByID is not a function

It's document.getElementById() and not document.getElementByID(). Check the casing for Id.

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

Razor view engine - How can I add Partial Views

You partial looks much like an editor template so you could include it as such (assuming of course that your partial is placed in the ~/views/controllername/EditorTemplates subfolder):

@Html.EditorFor(model => model.SomePropertyOfTypeLocaleBaseModel)

Or if this is not the case simply:

@Html.Partial("nameOfPartial", Model)

How do I resolve "HTTP Error 500.19 - Internal Server Error" on IIS7.0

ASP.Net applications come pre-wired with a handlers section in the web.config. By default, this is set to readonly within feature delegation within IIS. Take a look in IIS Manager

1.Go to IIS Manager and click Server Name

2.Go to the section Management and click Feature Delegation.

3.Select the Handler Mappings which is supposed to set as readonly.

4.Change the value to read/write and now you can get resolved the issue

JavaScript window resize event

var EM = new events_managment();

EM.addEvent(window, 'resize', function(win,doc, event_){
    console.log('resized');
    //EM.removeEvent(win,doc, event_);
});

function events_managment(){
    this.events = {};
    this.addEvent = function(node, event_, func){
        if(node.addEventListener){
            if(event_ in this.events){
                node.addEventListener(event_, function(){
                    func(node, event_);
                    this.events[event_](win_doc, event_);
                }, true);
            }else{
                node.addEventListener(event_, function(){
                    func(node, event_);
                }, true);
            }
            this.events[event_] = func;
        }else if(node.attachEvent){

            var ie_event = 'on' + event_;
            if(ie_event in this.events){
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                    this.events[ie_event]();
                });
            }else{
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                });
            }
            this.events[ie_event] = func;
        }
    }
    this.removeEvent = function(node, event_){
        if(node.removeEventListener){
            node.removeEventListener(event_, this.events[event_], true);
            this.events[event_] = null;
            delete this.events[event_];
        }else if(node.detachEvent){
            node.detachEvent(event_, this.events[event_]);
            this.events[event_] = null;
            delete this.events[event_];
        }
    }
}

Magento Product Attribute Get Value

First we must ensure that the desired attribute is loaded, and then output it. Use this:

$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);

How do I exit a foreach loop in C#?

Use break.


Unrelated to your question, I see in your code the line:

Violated = !(name.firstname == null) ? false : true;

In this line, you take a boolean value (name.firstname == null). Then, you apply the ! operator to it. Then, if the value is true, you set Violated to false; otherwise to true. So basically, Violated is set to the same value as the original expression (name.firstname == null). Why not use that, as in:

Violated = (name.firstname == null);

How to do an update + join in PostgreSQL?

For those actually wanting to do a JOIN you can also use:

UPDATE a
SET price = b_alias.unit_price
FROM      a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value' 
AND a.id = a_alias.id;

You can use the a_alias in the SET section on the right of the equals sign if needed. The fields on the left of the equals sign don't require a table reference as they are deemed to be from the original "a" table.

More Pythonic Way to Run a Process X Times

There is not a really pythonic way of repeating something. However, it is a better way:

map(lambda index:do_something(), xrange(10))

If you need to pass the index then:

map(lambda index:do_something(index), xrange(10))

Consider that it returns the results as a collection. So, if you need to collect the results it can help.

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

How to hide the soft keyboard from inside a fragment?

This worked for me in Kotlin class

fun hideKeyboard(activity: Activity) {
    try {
        val inputManager = activity
            .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val currentFocusedView = activity.currentFocus
        if (currentFocusedView != null) {
            inputManager.hideSoftInputFromWindow(currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }

}

How to preserve request url with nginx proxy_pass

In my scenario i have make this via below code in nginx vhost configuration

server {
server_name dashboards.etilize.com;

location / {
    proxy_pass http://demo.etilize.com/dashboards/;
    proxy_set_header Host $http_host;
}}

$http_host will set URL in Header same as requested

MySQL and PHP - insert NULL rather than empty string

To pass a NULL to MySQL, you do just that.

INSERT INTO table (field,field2) VALUES (NULL,3)

So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";

split string in two on given index and return both parts

You can easily expand it to split on multiple indexes, and to take an array or string

const splitOn = (slicable, ...indices) =>
  [0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));

splitOn('foo', 1);
// ["f", "oo"]

splitOn([1, 2, 3, 4], 2);
// [[1, 2], [3, 4]]

splitOn('fooBAr', 1, 4);
//  ["f", "ooB", "Ar"]

lodash issue tracker: https://github.com/lodash/lodash/issues/3014

How to store token in Local or Session Storage in Angular 2?

Save to local storage

localStorage.setItem('currentUser', JSON.stringify({ token: token, name: name }));

Load from local storage

var currentUser = JSON.parse(localStorage.getItem('currentUser'));
var token = currentUser.token; // your token

For more I suggest you go through this tutorial: Angular 2 JWT Authentication Example & Tutorial

MySQL skip first 10 results

OFFSET is what you are looking for.

SELECT * FROM table LIMIT 10 OFFSET 10

How to return value from Action()?

You can use Func<T, TResult> generic delegate. (See MSDN)

Func<MyType, ReturnType> func = (db) => { return new MyType(); }

Also there are useful generic delegates which considers a return value:

  • Converter<TInput, TOutput> (MSDN)
  • Predicate<TInput> - always return bool (MSDN)

Method:

public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory)

Generic delegate:

Func<InputArgumentType, MyType> createInstance = db => return new MyType();

Execute:

MyType myTypeInstance = SimpleUsing.DoUsing(
                            createInstance(new InputArgumentType()));

OR explicitly:

MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType());

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

If you are testing a logic class and it is calling some internal void methods the doNothing is perfect.

How to disable javax.swing.JButton in java?

For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button

You need that code to be in the actionPerformed(...) of the ActionListener registered with the Start button, not for the Start button itself.

You can add a simple ActionListener like this:

JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
        startButton.setEnabled(false);
        stopButton.setEnabled(true);
     }
   }
 );

note that your startButton above will need to be final in the above example if you want to create the anonymous listener in local scope.

How to list active / open connections in Oracle?

select
  username,
  osuser,
  terminal,
  utl_inaddr.get_host_address(terminal) IP_ADDRESS
from
  v$session
where
  username is not null
order by
  username,
  osuser;

What does -Xmn jvm option stands for

-Xmn : the size of the heap for the young generation Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor" .

Good size is 33%

Source

How can I sort one set of data to match another set of data in Excel?

You could also use INDEX MATCH, which is more "powerful" than vlookup. This would give you exactly what you are looking for:

enter image description here

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

Don't escape the underscore. Might be causing some whackness.

What's the fastest way to read a text file line-by-line?

There's a good topic about this in Stack Overflow question Is 'yield return' slower than "old school" return?.

It says:

ReadAllLines loads all of the lines into memory and returns a string[]. All well and good if the file is small. If the file is larger than will fit in memory, you'll run out of memory.

ReadLines, on the other hand, uses yield return to return one line at a time. With it, you can read any size file. It doesn't load the whole file into memory.

Say you wanted to find the first line that contains the word "foo", and then exit. Using ReadAllLines, you'd have to read the entire file into memory, even if "foo" occurs on the first line. With ReadLines, you only read one line. Which one would be faster?

Groovy String to Date

I think the best easy way in this case is to use parseToStringDate which is part of GDK (Groovy JDK enhancements):

Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy containing US-locale-constants only (e.g. Sat for Saturdays). Such a string is generated by the toString method of Date

Example:

println(Date.parseToStringDate("Tue Aug 10 16:02:43 PST 2010").format('MM-dd-yyyy'))

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I got this error while deploying to Virgo. The solution was to add this to my bundle imports:

org.springframework.transaction.config;version="[3.1,3.2)",

I noticed in the Spring jars under META-INF there is a spring.schemas and a spring.handlers section, and the class that they point to (in this case org.springframework.transaction.config.TxNamespaceHandler) must be imported.

Get today date in google appScript

The Date object is used to work with dates and times.

Date objects are created with new Date()

var now = new Date();

now - Current date and time object.

function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    var date = new Date();
    sheet.getRange(5, 2).setValue(date); 
}

How do I resolve a path relative to an ASP.NET MVC 4 application root?

To get the absolute path use this:

String path = HttpContext.Current.Server.MapPath("~/Data/data.html");

EDIT:

To get the Controller's Context remove .Current from the above line. By using HttpContext by itself it's easier to Test because it's based on the Controller's Context therefore more localized.

I realize now that I dislike how Server.MapPath works (internally eventually calls HostingEnvironment.MapPath) So I now recommend to always use HostingEnvironment.MapPath because its static and not dependent on the context unless of course you want that...

Pandas groupby: How to get a union of strings

In [4]: df = read_csv(StringIO(data),sep='\s+')

In [5]: df
Out[5]: 
   A         B       C
0  1  0.749065    This
1  2  0.301084      is
2  3  0.463468       a
3  4  0.643961  random
4  1  0.866521  string
5  2  0.120737       !

In [6]: df.dtypes
Out[6]: 
A      int64
B    float64
C     object
dtype: object

When you apply your own function, there is not automatic exclusions of non-numeric columns. This is slower, though, than the application of .sum() to the groupby

In [8]: df.groupby('A').apply(lambda x: x.sum())
Out[8]: 
   A         B           C
A                         
1  2  1.615586  Thisstring
2  4  0.421821         is!
3  3  0.463468           a
4  4  0.643961      random

sum by default concatenates

In [9]: df.groupby('A')['C'].apply(lambda x: x.sum())
Out[9]: 
A
1    Thisstring
2           is!
3             a
4        random
dtype: object

You can do pretty much what you want

In [11]: df.groupby('A')['C'].apply(lambda x: "{%s}" % ', '.join(x))
Out[11]: 
A
1    {This, string}
2           {is, !}
3               {a}
4          {random}
dtype: object

Doing this on a whole frame, one group at a time. Key is to return a Series

def f(x):
     return Series(dict(A = x['A'].sum(), 
                        B = x['B'].sum(), 
                        C = "{%s}" % ', '.join(x['C'])))

In [14]: df.groupby('A').apply(f)
Out[14]: 
   A         B               C
A                             
1  2  1.615586  {This, string}
2  4  0.421821         {is, !}
3  3  0.463468             {a}
4  4  0.643961        {random}

Remove scroll bar track from ScrollView in Android

By using below, solved the problem

android:scrollbarThumbVertical="@null"

How to center an element in the middle of the browser window?

If you don't know the size of the browser you can simply center in CSS with the following code:

HTML code:

<div class="firstDiv">Some Text</div>  

CSS code:

 .firstDiv {
  width: 500px;

  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  background-color: #F1F1F1;
 }

This also helps in any unforeseen changes in the future.

Read lines from a text file but skip the first two lines

That whole Open <file path> For Input As <some number> thing is so 1990s. It's also slow and very error-prone.

In your VBA editor, Select References from the Tools menu and look for "Microsoft Scripting Runtime" (scrrun.dll) which should be available on pretty much any XP or Vista machine. It it's there, select it. Now you have access to a (to me at least) rather more robust solution:

With New Scripting.FileSystemObject
    With .OpenTextFile(sFilename, ForReading)

        If Not .AtEndOfStream Then .SkipLine
        If Not .AtEndOfStream Then .SkipLine

        Do Until .AtEndOfStream
            DoSomethingImportantTo .ReadLine
        Loop

    End With
End With

Binary Data in JSON String. Something better than Base64

If you deal with bandwidth problems, try to compress data at the client side first, then base64-it.

Nice example of such magic is at http://jszip.stuartk.co.uk/ and more discussion to this topic is at JavaScript implementation of Gzip

CSS strikethrough different color from text?

I've used an empty :after element and decorated one border on it. You can even use CSS transforms to rotate it for a slanted line. Result: pure CSS, no extra HTML elements! Downside: doesn't wrap across multiple lines, although IMO you shouldn't use strikethrough on large blocks of text anyway.

_x000D_
_x000D_
s,_x000D_
strike {_x000D_
  text-decoration: none;_x000D_
  /*we're replacing the default line-through*/_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  /* keeps it from wrapping across multiple lines */_x000D_
}_x000D_
_x000D_
s:after,_x000D_
strike:after {_x000D_
  content: "";_x000D_
  /* required property */_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  border-top: 2px solid red;_x000D_
  height: 45%;_x000D_
  /* adjust as necessary, depending on line thickness */_x000D_
  /* or use calc() if you don't need to support IE8: */_x000D_
  height: calc(50% - 1px);_x000D_
  /* 1px = half the line thickness */_x000D_
  width: 100%;_x000D_
  transform: rotateZ(-4deg);_x000D_
}
_x000D_
<p>Here comes some <strike>strike-through</strike> text!</p>
_x000D_
_x000D_
_x000D_

nodejs mongodb object id to string

There are two ways to do this:

  1. in stead of using user._id use user.id and it will return a string for you
  2. If you really want to go the long way around you can use user._id.toString()

Consistency of hashCode() on a Java string

You should not rely on a hash code being equal to a specific value. Just that it will return consistent results within the same execution. The API docs say the following :

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

EDIT Since the javadoc for String.hashCode() specifies how a String's hash code is computed, any violation of this would violate the public API specification.

Batch command to move files to a new directory

this will also work, if you like

 xcopy  C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
 del C:\Test\Log

How do we control web page caching, across all browsers?

Setting the modified http header to some date in 1995 usually does the trick.

Here's an example:

Expires: Wed, 15 Nov 1995 04:58:08 GMT
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
Cache-Control: no-cache, must-revalidate

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

jQuery get the rendered height of an element?

So is this the answer?

"If you need to calculate something but not show it, set the element to visibility:hidden and position:absolute, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the lines last time I checked)."

I have the same problem on a number of elements. There is no jQuery or Prototype to be used on the site but I'm all in favor of borrowing the technique if it works. As an example of some things that failed to work, followed by what did, I have the following code:

// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
    var DoOffset = true;
    if (!elementPassed) { return 0; }
    if (!elementPassed.style) { return 0; }
    var thisHeight = 0;
    var heightBase = parseInt(elementPassed.style.height);
    var heightOffset = parseInt(elementPassed.offsetHeight);
    var heightScroll = parseInt(elementPassed.scrollHeight);
    var heightClient = parseInt(elementPassed.clientHeight);
    var heightNode = 0;
    var heightRects = 0;
    //
    if (DoBase) {
        if (heightBase > thisHeight) { thisHeight = heightBase; }
    }
    if (DoOffset) {
        if (heightOffset > thisHeight) { thisHeight = heightOffset; }
    }
    if (DoScroll) {
        if (heightScroll > thisHeight) { thisHeight = heightScroll; }
    }
    //
    if (thisHeight == 0) { thisHeight = heightClient; }
    //
    if (thisHeight == 0) { 
        // Dom Add:
        // all else failed so use the protype approach...
        var elBodyTempContainer = document.getElementById('BodyTempContainer');
        elBodyTempContainer.appendChild(elementPassed);
        heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
        elBodyTempContainer.removeChild(elementPassed);
        if (heightNode > thisHeight) { thisHeight = heightNode; }
        //
        // Bounding Rect:
        // Or this approach...
        var clientRects = elementPassed.getClientRects();
        heightRects = clientRects.height;
        if (heightRects > thisHeight) { thisHeight = heightRects; }
    }
    //
    // Default height not appropriate here
    // if (thisHeight == 0) { thisHeight = elementHeightDefault; }
    if (thisHeight > 3000) {
        // ERROR
        thisHeight = 3000;
    }
    return thisHeight;
}

which basically tries anything and everything only to get a zero result. ClientHeight with no affect. With the problem elements I typically get NaN in the Base and zero in the Offset and Scroll heights. I then tried the Add DOM solution and clientRects to see if it works here.

29 Jun 2011, I did indeed update the code to try both adding to DOM and clientHeight with better results than I expected.

1) clientHeight was also 0.

2) Dom actually gave me a height which was great.

3) ClientRects returns a result almost identical to the DOM technique.

Because the elements added are fluid in nature, when they are added to an otherwise empty DOM Temp element they are rendered according to the width of that container. This get weird, because that is 30px shorter than it eventually ends up.

I added a few snapshots to illustrate how the height is calculated differently. Menu block rendered normally Menu block added to DOM Temp element

The height differences are obvious. I could certainly add absolute positioning and hidden but I am sure that will have no effect. I continued to be convinced this would not work!

(I digress further) The height comes out (renders) lower than the true rendered height. This could be addressed by setting the width of the DOM Temp element to match the existing parent and could be done fairly accurately in theory. I also do not know what would result from removing them and adding them back into their existing location. As they arrived through an innerHTML technique I will be looking using this different approach.

* HOWEVER * None of that was necessary. In fact it worked as advertised and returned the correct height!!!

When I was able to get the menus visible again amazingly DOM had returned the correct height per the fluid layout at the top of the page (279px). The above code also uses getClientRects which return 280px.

This is illustrated in the following snapshot (taken from Chrome once working.)
enter image description here

Now I have noooooo idea why that prototype trick works, but it seems to. Alternatively, getClientRects also works.

I suspect the cause of all this trouble with these particular elements was the use of innerHTML instead of appendChild, but that is pure speculation at this point.

Bash or KornShell (ksh)?

Available in most UNIX system, ksh is standard-comliant, clearly designed, well-rounded. I think books,helps in ksh is enough and clear, especially the O'Reilly book. Bash is a mass. I keep it as root login shell for Linux at home only.

For interactive use, I prefer zsh on Linux/UNIX. I run scripts in zsh, but I'll test most of my scripts, functions in AIX ksh though.

Multiple submit buttons in an HTML form

I solved a very similar problem in this way:

  1. If JavaScript is enabled (in most cases nowadays) then all the submit buttons are "degraded" to buttons at page load via JavaScript (jQuery). Click events on the "degraded" button typed buttons are also handled via JavaScript.

  2. If JavaScript is not enabled then the form is served to the browser with multiple submit buttons. In this case hitting Enter on a textfield within the form will submit the form with the first button instead of the intended default, but at least the form is still usable: you can submit with both the prev and next buttons.

Working example:

_x000D_
_x000D_
<html>_x000D_
    <head>_x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
    </head>_x000D_
_x000D_
    <body>_x000D_
        <form action="http://httpbin.org/post" method="post">_x000D_
            If JavaScript  is disabled, then you CAN submit the form_x000D_
            with button1, button2 or button3._x000D_
_x000D_
            If you press enter on a text field, then the form is_x000D_
            submitted with the first submit button._x000D_
_x000D_
            If JavaScript is enabled, then the submit typed buttons_x000D_
            without the 'defaultSubmitButton' style are converted_x000D_
            to button typed buttons._x000D_
_x000D_
            If you press Enter on a text field, then the form is_x000D_
            submitted with the only submit button_x000D_
            (the one with class defaultSubmitButton)_x000D_
_x000D_
            If you click on any other button in the form, then the_x000D_
            form is submitted with that button's value._x000D_
_x000D_
            <br />_x000D_
_x000D_
            <input type="text" name="text1" ></input>_x000D_
            <button type="submit" name="action" value="button1" >button 1</button>_x000D_
            <br />_x000D_
_x000D_
            <input type="text" name="text2" ></input>_x000D_
            <button type="submit" name="action" value="button2" >button 2</button>_x000D_
            <br />_x000D_
_x000D_
            <input type="text" name="text3" ></input>_x000D_
            <button class="defaultSubmitButton" type="submit" name="action" value="button3" >default button</button>_x000D_
        </form>_x000D_
_x000D_
        <script>_x000D_
            $(document).ready(function(){_x000D_
_x000D_
                /* Change submit typed buttons without the 'defaultSubmitButton'_x000D_
                   style to button typed buttons */_x000D_
                $('form button[type=submit]').not('.defaultSubmitButton').each(function(){_x000D_
                    $(this).attr('type', 'button');_x000D_
                });_x000D_
_x000D_
                /* Clicking on button typed buttons results in:_x000D_
                   1. Setting the form's submit button's value to_x000D_
                      the clicked button's value,_x000D_
                   2. Clicking on the form's submit button */_x000D_
                $('form button[type=button]').click(function( event ){_x000D_
                    var form = event.target.closest('form');_x000D_
                    var submit = $("button[type='submit']",form).first();_x000D_
                    submit.val(event.target.value);_x000D_
                    submit.click();_x000D_
                });_x000D_
            });_x000D_
        </script>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

PHP: trying to create a new line with "\n"

If you want a new line character to be inserted into a plain text stream then you could use the OS independent global PHP_EOL

echo "foo";
echo PHP_EOL ;
echo "bar";

In HTML terms you would see a newline between foo and bar if you looked at the source code of the page.

ergo, it is useful if you are outputting say, a loop of values for a select box and you value having html source code which is "prettier" or easier to read for yourself later. e.g.

foreach( $dogs as $dog )
echo "<option>$dog</option>" . PHP_EOL ;

enum to string in modern C++11 / C++14 / C++17 and future C++20

My 3 cents, though this is not a complete match to what the op wants. Here is the relevant reference.

namespace enums
{

template <typename T, T I, char ...Chars>
struct enums : std::integral_constant<T, I>
{
  static constexpr char const chars[sizeof...(Chars)]{Chars...};
};

template <typename T, T X, typename S, std::size_t ...I>
constexpr auto make(std::index_sequence<I...>) noexcept
{
  return enums<T, X, S().chars[I]...>();
}

#define ENUM(s, n) []() noexcept{\
  struct S { char const (&chars)[sizeof(s)]{s}; };\
  return enums::make<decltype(n), n, S>(\
    std::make_index_sequence<sizeof(s)>());}()

#define ENUM_T(s, n)\
  static constexpr auto s ## _tmp{ENUM(#s, n)};\
  using s ## _enum_t = decltype(s ## _tmp)

template <typename T, typename ...A, std::size_t N>
inline auto map(char const (&s)[N]) noexcept
{
  constexpr auto invalid(~T{});

  auto r{invalid};

  return
    (
      (
        invalid == r ?
          r = std::strncmp(A::chars, s, N) ? invalid : A{} :
          r
      ),
      ...
    );
}

}

int main()
{
  ENUM_T(echo, 0);
  ENUM_T(cat, 1);
  ENUM_T(ls, 2);

  std::cout << echo_enum_t{} << " " << echo_enum_t::chars << std::endl;

  std::cout << enums::map<int, echo_enum_t, cat_enum_t, ls_enum_t>("ls")) << std::endl;

  return 0;
}

So you generate a type, that you can convert to an integer and/or a string.

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

I would use SharedSizeGroup

<Grid>
    <Grid.ColumnDefinition>
        <ColumnDefinition SharedSizeGroup="col1"></ColumnDefinition>  
        <ColumnDefinition SharedSizeGroup="col2"></ColumnDefinition>
    </Grid.ColumnDefinition>
    <TextBox Background="Azure" Text="Hello" Grid.Column="1" MaxWidth="200" />
</Grid>

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

If you are building your project with gradle, you just need to add one line to the dependencies in the build.gradle:

buildscript {
    ...
}
...

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

and then add the folder to your root project or module:

enter image description here

Then you drop your jars in there and you are good to go :-)

Prevent form redirect OR refresh on submit?

In the opening tag of your form, set an action attribute like so:

<form id="contactForm" action="#">

How to add local .jar file dependency to build.gradle file?

The accepted answer is good, however, I would have needed various library configurations within my multi-project Gradle build to use the same 3rd-party Java library.

Adding '$rootProject.projectDir' to the 'dir' path element within my 'allprojects' closure meant each sub-project referenced the same 'libs' directory, and not a version local to that sub-project:

//gradle.build snippet
allprojects {
    ...

    repositories {
        //All sub-projects will now refer to the same 'libs' directory
        flatDir {
            dirs "$rootProject.projectDir/libs"
        }
        mavenCentral()
    }

    ...
}

EDIT by Quizzie: changed "${rootProject.projectDir}" to "$rootProject.projectDir" (works in the newest Gradle version).

Error Code 1292 - Truncated incorrect DOUBLE value - Mysql

In my case it was a view (highly nested, view in view) insertion causing the error in :

CREATE TABLE tablename AS
  SELECT * FROM highly_nested_viewname
;

The workaround we ended up doing was simulating a materialized view (which is really a table) and periodically insert/update it using stored procedures.

How do I invoke a Java method when given the method name as a string?

This is working fine for me :

public class MethodInvokerClass {
    public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, ClassNotFoundException, InvocationTargetException, InstantiationException {
        Class c = Class.forName(MethodInvokerClass.class.getName());
        Object o = c.newInstance();
        Class[] paramTypes = new Class[1];
        paramTypes[0]=String.class;
        String methodName = "countWord";
         Method m = c.getDeclaredMethod(methodName, paramTypes);
         m.invoke(o, "testparam");
}
public void countWord(String input){
    System.out.println("My input "+input);
}

}

Output:

My input testparam

I am able to invoke the method by passing its name to another method (like main).

Parse JSON String into a Particular Object Prototype in JavaScript

Do you want to add JSON serialization/deserialization functionality, right? Then look at this:

You want to achieve this:

UML

toJson() is a normal method.
fromJson() is a static method.

Implementation:

var Book = function (title, author, isbn, price, stock){
    this.title = title;
    this.author = author;
    this.isbn = isbn;
    this.price = price;
    this.stock = stock;

    this.toJson = function (){
        return ("{" +
            "\"title\":\"" + this.title + "\"," +
            "\"author\":\"" + this.author + "\"," +
            "\"isbn\":\"" + this.isbn + "\"," +
            "\"price\":" + this.price + "," +
            "\"stock\":" + this.stock +
        "}");
    };
};

Book.fromJson = function (json){
    var obj = JSON.parse (json);
    return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};

Usage:

var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}

var book = Book.fromJson (json);
alert (book.title); //prints: t

Note: If you want you can change all property definitions like this.title, this.author, etc by var title, var author, etc. and add getters to them to accomplish the UML definition.

Test if a string contains any of the strings from an array

You can use String#matches method like this:

System.out.printf("Matches - [%s]%n", string.matches("^.*?(item1|item2|item3).*$"));

How to create a database from shell command?

Connect to DB using base user: mysql -u base_user -pbase_user_pass And execute CREATE DATABASE, CREATE USER and GRANT PRIVILEGES Statements.

Here's handy web wizard to help you with statements www.bugaco.com/helpers/create_database.html

Test class with a new() call in it with Mockito

I am all for Eran Harel's solution and in cases where it isn't possible, Tomasz Nurkiewicz's suggestion for spying is excellent. However, it's worth noting that there are situations where neither would apply. E.g. if the login method was a bit "beefier":

public class TestedClass {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

... and this was old code that could not be refactored to extract the initialization of a new LoginContext to its own method and apply one of the aforementioned solutions.

For completeness' sake, it's worth mentioning a third technique - using PowerMock to inject the mock object when the new operator is called. PowerMock isn't a silver bullet, though. It works by applying byte-code manipulation on the classes it mocks, which could be dodgy practice if the tested classes employ byte code manipulation or reflection and at least from my personal experience, has been known to introduce a performance hit to the test. Then again, if there are no other options, the only option must be the good option:

@RunWith(PowerMockRunner.class)
@PrepareForTest(TestedClass.class)
public class TestedClassTest {

    @Test
    public void testLogin() {
        LoginContext lcMock = mock(LoginContext.class);
        whenNew(LoginContext.class).withArguments(anyString(), anyString()).thenReturn(lcMock);
        TestedClass tc = new TestedClass();
        tc.login ("something", "something else");
        // test the login's logic
    }
}

How to extract the n-th elements from a list of tuples?

Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method

setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'

import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))

Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499

So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.

Remove all special characters from a string in R?

Convert the Special characters to apostrophe,

Data  <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)

Below code it to remove extra ''' apostrophe

Data <- gsub("''","" , Data ,ignore.case = TRUE)

Use gsub(..) function for replacing the special character with apostrophe

Change EditText hint color when using TextInputLayout

android:textColorHint="#FFFFFF" sometime works and sometime doesnt. For me below solution works perfectly

Try The Below Code It Works In your XML file and TextLabel theme is defined in style.xml

 <android.support.design.widget.TextInputLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:theme="@style/MyTextLabel">

     <EditText
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:hint="Floating Label"
         android:id="@+id/edtText"/>

 </android.support.design.widget.TextInputLayout>

In Styles Folder TextLabel Code

 <style name="MyTextLabel" parent="TextAppearance.AppCompat">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">@color/Color Name</item> 
<!--The size of the text appear on label in false state -->
    <item name="android:textSize">20sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">@color/Color Name</item>
    <item name="colorControlNormal">@color/Color Name</item>
    <item name="colorControlActivated">@color/Color Name</item>
 </style>

If you just want to change the color of label in false state then colorAccent , colorControlNormal and colorControlActivated are not required

URL Encoding using C#

I've been experimenting with the various methods .NET provide for URL encoding. Perhaps the following table will be useful (as output from a test app I wrote):

Unencoded UrlEncoded UrlEncodedUnicode UrlPathEncoded EscapedDataString EscapedUriString HtmlEncoded HtmlAttributeEncoded HexEscaped
A         A          A                 A              A                 A                A           A                    %41
B         B          B                 B              B                 B                B           B                    %42

a         a          a                 a              a                 a                a           a                    %61
b         b          b                 b              b                 b                b           b                    %62

0         0          0                 0              0                 0                0           0                    %30
1         1          1                 1              1                 1                1           1                    %31

[space]   +          +                 %20            %20               %20              [space]     [space]              %20
!         !          !                 !              !                 !                !           !                    %21
"         %22        %22               "              %22               %22              &quot;      &quot;               %22
#         %23        %23               #              %23               #                #           #                    %23
$         %24        %24               $              %24               $                $           $                    %24
%         %25        %25               %              %25               %25              %           %                    %25
&         %26        %26               &              %26               &                &amp;       &amp;                %26
'         %27        %27               '              '                 '                &#39;       &#39;                %27
(         (          (                 (              (                 (                (           (                    %28
)         )          )                 )              )                 )                )           )                    %29
*         *          *                 *              %2A               *                *           *                    %2A
+         %2b        %2b               +              %2B               +                +           +                    %2B
,         %2c        %2c               ,              %2C               ,                ,           ,                    %2C
-         -          -                 -              -                 -                -           -                    %2D
.         .          .                 .              .                 .                .           .                    %2E
/         %2f        %2f               /              %2F               /                /           /                    %2F
:         %3a        %3a               :              %3A               :                :           :                    %3A
;         %3b        %3b               ;              %3B               ;                ;           ;                    %3B
<         %3c        %3c               <              %3C               %3C              &lt;        &lt;                 %3C
=         %3d        %3d               =              %3D               =                =           =                    %3D
>         %3e        %3e               >              %3E               %3E              &gt;        >                    %3E
?         %3f        %3f               ?              %3F               ?                ?           ?                    %3F
@         %40        %40               @              %40               @                @           @                    %40
[         %5b        %5b               [              %5B               %5B              [           [                    %5B
\         %5c        %5c               \              %5C               %5C              \           \                    %5C
]         %5d        %5d               ]              %5D               %5D              ]           ]                    %5D
^         %5e        %5e               ^              %5E               %5E              ^           ^                    %5E
_         _          _                 _              _                 _                _           _                    %5F
`         %60        %60               `              %60               %60              `           `                    %60
{         %7b        %7b               {              %7B               %7B              {           {                    %7B
|         %7c        %7c               |              %7C               %7C              |           |                    %7C
}         %7d        %7d               }              %7D               %7D              }           }                    %7D
~         %7e        %7e               ~              ~                 ~                ~           ~                    %7E

A         %c4%80     %u0100            %c4%80         %C4%80            %C4%80           A           A                    [OoR]
a         %c4%81     %u0101            %c4%81         %C4%81            %C4%81           a           a                    [OoR]
E         %c4%92     %u0112            %c4%92         %C4%92            %C4%92           E           E                    [OoR]
e         %c4%93     %u0113            %c4%93         %C4%93            %C4%93           e           e                    [OoR]
I         %c4%aa     %u012a            %c4%aa         %C4%AA            %C4%AA           I           I                    [OoR]
i         %c4%ab     %u012b            %c4%ab         %C4%AB            %C4%AB           i           i                    [OoR]
O         %c5%8c     %u014c            %c5%8c         %C5%8C            %C5%8C           O           O                    [OoR]
o         %c5%8d     %u014d            %c5%8d         %C5%8D            %C5%8D           o           o                    [OoR]
U         %c5%aa     %u016a            %c5%aa         %C5%AA            %C5%AA           U           U                    [OoR]
u         %c5%ab     %u016b            %c5%ab         %C5%AB            %C5%AB           u           u                    [OoR]

The columns represent encodings as follows:

  • UrlEncoded: HttpUtility.UrlEncode

  • UrlEncodedUnicode: HttpUtility.UrlEncodeUnicode

  • UrlPathEncoded: HttpUtility.UrlPathEncode

  • EscapedDataString: Uri.EscapeDataString

  • EscapedUriString: Uri.EscapeUriString

  • HtmlEncoded: HttpUtility.HtmlEncode

  • HtmlAttributeEncoded: HttpUtility.HtmlAttributeEncode

  • HexEscaped: Uri.HexEscape

NOTES:

  1. HexEscape can only handle the first 255 characters. Therefore it throws an ArgumentOutOfRange exception for the Latin A-Extended characters (eg A).

  2. This table was generated in .NET 4.0 (see Levi Botelho's comment below that says the encoding in .NET 4.5 is slightly different).

EDIT:

I've added a second table with the encodings for .NET 4.5. See this answer: https://stackoverflow.com/a/21771206/216440

EDIT 2:

Since people seem to appreciate these tables, I thought you might like the source code that generates the table, so you can play around yourselves. It's a simple C# console application, which can target either .NET 4.0 or 4.5:

using System;
using System.Collections.Generic;
using System.Text;
// Need to add a Reference to the System.Web assembly.
using System.Web;

namespace UriEncodingDEMO2
{
    class Program
    {
        static void Main(string[] args)
        {
            EncodeStrings();

            Console.WriteLine();
            Console.WriteLine("Press any key to continue...");
            Console.Read();
        }

        public static void EncodeStrings()
        {
            string stringToEncode = "ABCD" + "abcd"
            + "0123" + " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" + "AaEeIiOoUu";

            // Need to set the console encoding to display non-ASCII characters correctly (eg the 
            //  Latin A-Extended characters such as AaEe...).
            Console.OutputEncoding = Encoding.UTF8;

            // Will also need to set the console font (in the console Properties dialog) to a font 
            //  that displays the extended character set correctly.
            // The following fonts all display the extended characters correctly:
            //  Consolas
            //  DejaVu Sana Mono
            //  Lucida Console

            // Also, in the console Properties, set the Screen Buffer Size and the Window Size 
            //  Width properties to at least 140 characters, to display the full width of the 
            //  table that is generated.

            Dictionary<string, Func<string, string>> columnDetails =
                new Dictionary<string, Func<string, string>>();
            columnDetails.Add("Unencoded", (unencodedString => unencodedString));
            columnDetails.Add("UrlEncoded",
                (unencodedString => HttpUtility.UrlEncode(unencodedString)));
            columnDetails.Add("UrlEncodedUnicode",
                (unencodedString => HttpUtility.UrlEncodeUnicode(unencodedString)));
            columnDetails.Add("UrlPathEncoded",
                (unencodedString => HttpUtility.UrlPathEncode(unencodedString)));
            columnDetails.Add("EscapedDataString",
                (unencodedString => Uri.EscapeDataString(unencodedString)));
            columnDetails.Add("EscapedUriString",
                (unencodedString => Uri.EscapeUriString(unencodedString)));
            columnDetails.Add("HtmlEncoded",
                (unencodedString => HttpUtility.HtmlEncode(unencodedString)));
            columnDetails.Add("HtmlAttributeEncoded",
                (unencodedString => HttpUtility.HtmlAttributeEncode(unencodedString)));
            columnDetails.Add("HexEscaped",
                (unencodedString
                    =>
                    {
                        // Uri.HexEscape can only handle the first 255 characters so for the 
                        //  Latin A-Extended characters, such as A, it will throw an 
                        //  ArgumentOutOfRange exception.                       
                        try
                        {
                            return Uri.HexEscape(unencodedString.ToCharArray()[0]);
                        }
                        catch
                        {
                            return "[OoR]";
                        }
                    }));

            char[] charactersToEncode = stringToEncode.ToCharArray();
            string[] stringCharactersToEncode = Array.ConvertAll<char, string>(charactersToEncode,
                (character => character.ToString()));
            DisplayCharacterTable<string>(stringCharactersToEncode, columnDetails);
        }

        private static void DisplayCharacterTable<TUnencoded>(TUnencoded[] unencodedArray,
            Dictionary<string, Func<TUnencoded, string>> mappings)
        {
            foreach (string key in mappings.Keys)
            {
                Console.Write(key.Replace(" ", "[space]") + " ");
            }
            Console.WriteLine();

            foreach (TUnencoded unencodedObject in unencodedArray)
            {
                string stringCharToEncode = unencodedObject.ToString();
                foreach (string columnHeader in mappings.Keys)
                {
                    int columnWidth = columnHeader.Length + 1;
                    Func<TUnencoded, string> encoder = mappings[columnHeader];
                    string encodedString = encoder(unencodedObject);

                    // ASSUMPTION: Column header will always be wider than encoded string.
                    Console.Write(encodedString.Replace(" ", "[space]").PadRight(columnWidth));
                }
                Console.WriteLine();
            }
        }
    }
}

Insert multiple lines into a file after specified pattern using shell script

Using GNU sed:

sed "/cdef/aline1\nline2\nline3\nline4" input.txt

If you started with:

abcd
accd
cdef
line
web

this would produce:

abcd
accd
cdef
line1
line2
line3
line4
line
web

If you want to save the changes to the file in-place, say:

sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt

How to update Ruby to 1.9.x on Mac?

With brew this is a one-liner:

(assuming that you have tapped homebrew/versions, which can be done by running brew tap homebrew/versions)

brew install ruby193

Worked out of the box for me on OS X 10.8.4. Or if you want 2.0, you just brew install ruby

More generally, brew search ruby shows you the different repos available, and if you want to get really specific you can use brew versions ruby and checkout a specific version instead.

What do I use on linux to make a python program executable

Putting these lines at the starting of the code will tell your operating systems to look up the binary program needed for the execution of the python script i.e it is the python interpreter.

So it depends on your operating system where it keeps the python interpreter. As I have Ubuntu as operating system it keeps the python interpreter in /usr/bin/python so I have to write this line at the starting of my python script;

#!/usr/bin/python

After completing and saving your code

  1. Start your command terminal

  2. Make sure the script lies in your present working directory

  3. Type chmod +x script_name.py

  4. Now you can start the script by clicking the script. An alert box will appear; press "Run" or "Run in Terminal" in the alert box; or, at the terminal prompt, type ./script_name.py

Calculating the difference between two Java date instances

Since all the answers here are correct but use legacy java or 3rd party libs like joda or similar, I will just drop another way using new java.time classes in Java 8 and later. See Oracle Tutorial.

Use LocalDate and ChronoUnit:

LocalDate d1 = LocalDate.of(2017, 5, 1);
LocalDate d2 = LocalDate.of(2017, 5, 18);

long days = ChronoUnit.DAYS.between(d1, d2);
System.out.println( days );

How to allow only numeric (0-9) in HTML inputbox using jQuery?

function Numbers(e)
{
    if($.browser.msie)
    {
        if(e.keyCode > 47 && e.keyCode < 58)
            return true;
        else
            return false;
    }
    else
    {
        if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
            return true;
        else
            return false;
    }
}

I hope this will work on all browsers.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

WebDriver - wait for element using Java

You can use Explicit wait or Fluent Wait

Example of Explicit Wait -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));     

Example of Fluent Wait -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});  

Check this TUTORIAL for more details.

How to create and write to a txt file using VBA

Dim SaveVar As Object

Sub Main()

    Console.WriteLine("Enter Text")

    Console.WriteLine("")

    SaveVar = Console.ReadLine

    My.Computer.FileSystem.WriteAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt", "Text: " & SaveVar & ", ", True)

    Console.WriteLine("")

    Console.WriteLine("File Saved")

    Console.WriteLine("")

    Console.WriteLine(My.Computer.FileSystem.ReadAllText("N:\A-Level Computing\2017!\PPE\SaveFile\SaveData.txt"))
    Console.ReadLine()

End Sub()

Java heap terminology: young, old and permanent generations?

The Heap is divided into young and old generations as follows :

Young Generation : It is place where lived for short period and divided into two spaces:

  • Eden Space : When object created using new keyword memory allocated on this space.
  • Survivor Space : This is the pool which contains objects which have survived after java garbage collection from Eden space.

Old Generation : This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.

  • Tenured Space: This memory pool contains objects which survived after multiple garbage collection means object which survived after garbage collection from Survivor space.

Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.

Java8 Update: PermGen is replaced with Metaspace which is very similar.
Main difference is that Metaspace re-sizes dynamically i.e., It can expand at runtime.
Java Metaspace space: unbounded (default)

Code Cache (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.

enter image description here

Courtesy

R color scatter plot points based on values

Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.

 # make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))

# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)

# Make a vector of thresholds 'Brks' to colour code z 
Brks <- c(seq(0,18,3),Inf)

# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')

# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")

# Make up lookup dataframe 'LkUp' of the lables and colours 
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)

# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))

# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')

# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
     Grd$Var2,
     xlim = c(0,400),
     ylim = c(0,400),
     cex = 1.0,
     col = Grd$Clrs,
     pch = 20,
     xlab = 'mX',
     ylab = 'mY',
     main = 'My Grid',
     axes = FALSE,
     labels = FALSE,
     las = 1
)

axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')

legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')

What exactly is Spring Framework for?

Spring was dependency injection in the begining, then add king of wrappers for almost everything (wrapper over JPA implementations etc).

Long story ... most parts of Spring preffer XML solutions (XML scripting engine ... brrrr), so for DI I use Guice

Good library, but with growing depnedenciec, for example Spring JDBC (maybe one Java jdbc solution with real names parameters) take from maven 4-5 next.

Using Spring MVC (part of "big spring") for web development ... it is "request based" framework, there is holy war "request vs component" ... up to You

Custom li list-style with font-awesome icon

I did two things inspired by @OscarJovanny comment, with some hacks.

Step 1:

  • Download icons file as svg from Here, as I only need only this icon from font awesome

Step 2:

<style>
ul {
    list-style-type: none;
    margin-left: 10px;
}

ul li {
    margin-bottom: 12px;
    margin-left: -10px;
    display: flex;
    align-items: center;
}

ul li::before {
    color: transparent;
    font-size: 1px;
    content: " ";
    margin-left: -1.3em;
    margin-right: 15px;
    padding: 10px;
    background-color: orange;
    -webkit-mask-image: url("./assets/img/check-circle-solid.svg");
    -webkit-mask-size: cover;
}
</style>

Results

enter image description here

How can I set my Cygwin PATH to find javac?

as you write the it with double-quotes, you don't need to escape spaces with \

export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"

of course this also works:

export PATH=$PATH:/cygdrive/C/Program\ Files/Java/jdk1.6.0_23/bin/

Get content of a cell given the row and column numbers

You don't need the CELL() part of your formulas:

=INDIRECT(ADDRESS(B1,B2))

or

=OFFSET($A$1, B1-1,B2-1)

will both work. Note that both INDIRECT and OFFSET are volatile functions. Volatile functions can slow down calculation because they are calculated at every single recalculation.

AngularJS. How to call controller function from outside of controller component

The solution angular.element(document.getElementById('ID')).scope().get() stopped working for me in angular 1.5.2. Sombody mention in a comment that this doesn't work in 1.4.9 also. I fixed it by storing the scope in a global variable:

var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
    $scope = function bar(){
        console.log("foo");        
    };
    scopeHolder = $scope;
})

call from custom code:

scopeHolder.bar()

if you wants to restrict the scope to only this method. To minimize the exposure of whole scope. use following technique.

var scopeHolder;
angular.module('fooApp').controller('appCtrl', function ($scope) {
    $scope.bar = function(){
        console.log("foo");        
    };
    scopeHolder = $scope.bar;
})

call from custom code:

scopeHolder()

Javascript "Not a Constructor" Exception while creating objects

For my project, the problem turned out to be a circular reference created by the require() calls:

y.js:
var x = require("./x.js");
var y = function() { console.log("result is " + x(); }
module.exports = y;

x.js:
var y = require("./y.js");
var my_y = new y(); // <- TypeError: y is not a constructor
var x = function() { console.log("result is " + my_y; }
module.exports = x;

The reason is that when it is attempting to initialize y, it creates a temporary "y" object (not class, object!) in the dependency system that is somehow not yet a constructor. Then, when x.js is finished being defined, it can continue making y a constructor. Only, x.js has an error in it where it tries to use the non-constructor y.

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

Corrupted Access .accdb file: "Unrecognized Database Format"

Try to create a new database and import every table, query etc into this new database. With this import Access recreates all the objects from scratch. If there is some sort of corruption in an object, it should be solved.

If you're Lucky only the corrupted item(s) will be lost, if any.

can't load package: package .: no buildable Go source files

You should check the $GOPATH directory. If there is an empty directory of the package name, go get doesn't download the package from the repository.

For example, If I want to get the github.com/googollee/go-socket.io package from it's github repository, and there is already an empty directory github.com/googollee/go-socket.io in the $GOPATH, go get doesn't download the package and then complains that there is no buildable Go source file in the directory. Delete any empty directory first of all.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

In Presto you could use use

SELECT array_max(ARRAY[o.NegotiatedPrice, o.SuggestedPrice])

Getting the first character of a string with $str[0]

Speaking as a mere mortal, I would stick with $str[0]. As far as I'm concerned, it's quicker to grasp the meaning of $str[0] at a glance than substr($str, 0, 1). This probably boils down to a matter of preference.

As far as performance goes, well, profile profile profile. :) Or you could peer into the PHP source code...

React won't load local images

I just wanted to leave the following which enhances the accepted answer above.

In addition to the accepted answer, you can make your own life a bit easier by specifying an alias path in Webpack, so you don't have to worry where the image is located relative to the file you're currently in. Please see example below:

Webpack file:

module.exports = {
  resolve: {
    modules: ['node_modules'],
    alias: {
      public: path.join(__dirname, './public')
    }
  },
}

Use:

<img src={require("public/img/resto.ong")} />

Centering the pagination in bootstrap

This css works for me:

.dataTables_paginate {
   float: none !important;
   text-align: center !important;
}

replacing NA's with 0's in R dataframe

dataset <- matrix(sample(c(NA, 1:5), 25, replace = TRUE), 5);
data <- as.data.frame(dataset)
[,1] [,2] [,3] [,4] [,5] 
[1,]    2    3    5    5    4
[2,]    2    4    3    2    4
[3,]    2   NA   NA   NA    2
[4,]    2    3   NA    5    5
[5,]    2    3    2    2    3
data[is.na(data)] <- 0

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

How do I find an array item with TypeScript? (a modern, easier way)

You could just use underscore library.

Install it:

   npm install underscore --save
   npm install @types/underscore --save-dev

Import it

   import _ = require('underscore');

Use it

    var x = _.filter(
      [{ "id": 1 }, { "id": -2 }, { "id": 3 }],
      myObj => myObj.id < 0)
    );

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

How to convert Javascript datetime to C# datetime?

Newtonsoft.Json.JsonConvert.SerializeObject(Convert.ToDateTime(dr[col.ColumnName])).Replace('"', ' ').Trim();

Script for rebuilding and reindexing the fragmented index?

Two solutions: One simple and one more advanced.

Introduction

There are two solutions available to you depending on the severity of your issue

Replace with your own values, as follows:

  • Replace XXXMYINDEXXXX with the name of an index.
  • Replace XXXMYTABLEXXX with the name of a table.
  • Replace XXXDATABASENAMEXXX with the name of a database.

Solution 1. Indexing

Rebuild all indexes for a table in offline mode

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD

Rebuild one specified index for a table in offline mode

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD

Solution 2. Fragmentation

Fragmentation is an issue in tables that regularly have entries both added and removed.

Check fragmentation percentage

SELECT  
    ips.[index_id] ,
    idx.[name] ,
    ips.[avg_fragmentation_in_percent]
FROM    
    sys.dm_db_index_physical_stats(DB_ID(N'XXXMYDATABASEXXX'), OBJECT_ID(N'XXXMYTABLEXXX'), NULL, NULL, NULL) AS [ips]
    INNER JOIN sys.indexes AS [idx] ON [ips].[object_id] = [idx].[object_id] AND [ips].[index_id] = [idx].[index_id]

Fragmentation 5..30%

If the fragmentation value is greater than 5%, but less than 30% then it is worth reorganising indexes.

Reorganise all indexes for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REORGANIZE

Reorganise one specified index for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REORGANIZE

Fragmentation 30%+

If the fragmentation value is 30% or greater then it is worth rebuilding then indexes in online mode.

Rebuild all indexes in online mode for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

Rebuild one specified index in online mode for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

CSS body background image fixed to full screen even when zooming in/out

there is another technique

use

background-size:cover

That is it full set of css is

body { 
    background: url('images/body-bg.jpg') no-repeat center center fixed;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
} 

Latest browsers support the default property.

is the + operator less performant than StringBuffer.append()

Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is.

If you have long strings to concatenate then definitely use an array.join technique. (Or some StringBuffer wrapper around this, for readability.) But if your strings are short don't bother.

Is it possible to put a ConstraintLayout inside a ScrollView?

I had NestedScrollView inside ConstraintLayout, and this NestedScrollView has one ConstraintLayout.

If you're facing issue with NestedScrollView,

add android:fillViewport="true" to NestedScrollView, worked.

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

Separation of business logic and data access in django

An old question, but I'd like to offer my solution anyway. It's based on acceptance that model objects too require some additional functionality while it's awkward to place it within the models.py. Heavy business logic may be written separately depending on personal taste, but I at least like the model to do everything related to itself. This solution also supports those who like to have all the logic placed within models themselves.

As such, I devised a hack that allows me to separate logic from model definitions and still get all the hinting from my IDE.

The advantages should be obvious, but this lists a few that I have observed:

  • DB definitions remain just that - no logic "garbage" attached
  • Model-related logic is all placed neatly in one place
  • All the services (forms, REST, views) have a single access point to logic
  • Best of all: I did not have to rewrite any code once I realised that my models.py became too cluttered and had to separate the logic away. The separation is smooth and iterative: I could do a function at a time or entire class or the entire models.py.

I have been using this with Python 3.4 and greater and Django 1.8 and greater.

app/models.py

....
from app.logic.user import UserLogic

class User(models.Model, UserLogic):
    field1 = models.AnyField(....)
    ... field definitions ...

app/logic/user.py

if False:
    # This allows the IDE to know about the User model and its member fields
    from main.models import User

class UserLogic(object):
    def logic_function(self: 'User'):
        ... code with hinting working normally ...

The only thing I can't figure out is how to make my IDE (PyCharm in this case) recognise that UserLogic is actually User model. But since this is obviously a hack, I'm quite happy to accept the little nuisance of always specifying type for self parameter.

Spark RDD to DataFrame python

I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:

from pyspark.sql import SQLContext

# assuming the spark environemnt is set and sc is spark.sparkContext 
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")

How can I get the order ID in WooCommerce?

it worked. Just modified it

global $woocommerce, $post;

$order = new WC_Order($post->ID);

//to escape # from order id 

$order_id = trim(str_replace('#', '', $order->get_order_number()));

Access properties file programmatically with Spring?

As you know the newer versions of Spring don't use the PropertyPlaceholderConfigurer and now use another nightmarish construct called PropertySourcesPlaceholderConfigurer. If you're trying to get resolved properties from code, and wish the Spring team gave us a way to do this a long time ago, then vote this post up! ... Because this is how you do it the new way:

Subclass PropertySourcesPlaceholderConfigurer:

public class SpringPropertyExposer extends PropertySourcesPlaceholderConfigurer {

    private ConfigurableListableBeanFactory factory;

    /**
     * Save off the bean factory so we can use it later to resolve properties
     */
    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,
            final ConfigurablePropertyResolver propertyResolver) throws BeansException {
        super.processProperties(beanFactoryToProcess, propertyResolver);

        if (beanFactoryToProcess.hasEmbeddedValueResolver()) {
            logger.debug("Value resolver exists.");
            factory = beanFactoryToProcess;
        }
        else {
            logger.error("No existing embedded value resolver.");
        }
    }

    public String getProperty(String name) {
        Object propertyValue = factory.resolveEmbeddedValue(this.placeholderPrefix + name + this.placeholderSuffix);
        return propertyValue.toString();
    }
}

To use it, make sure to use your subclass in your @Configuration and save off a reference to it for later use.

@Configuration
@ComponentScan
public class PropertiesConfig {

    public static SpringPropertyExposer commonEnvConfig;

    @Bean(name="commonConfig")
    public static PropertySourcesPlaceholderConfigurer commonConfig() throws IOException {
        commonEnvConfig = new SpringPropertyExposer(); //This is a subclass of the return type.
        PropertiesFactoryBean commonConfig = new PropertiesFactoryBean();
        commonConfig.setLocation(new ClassPathResource("META-INF/spring/config.properties"));
        try {
            commonConfig.afterPropertiesSet();
        }
        catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
        commonEnvConfig.setProperties(commonConfig.getObject());
        return commonEnvConfig;
    }
}

Usage:

Object value = PropertiesConfig.commonEnvConfig.getProperty("key.subkey");

How to INNER JOIN 3 tables using CodeIgniter

For executing pure SQL statements (I Don't Know About the FRAMEWORK- CodeIGNITER!!!) you can use SUB QUERY! The Syntax Would be as follows

SELECT t1.id FROM example t1 INNER JOIN (select id from (example2 t1 join example3 t2 on t1.id = t2.id)) as t2 ON t1.id = t2.id;

Hope you Get My Point!

Scala Doubles, and Precision

How about :

 val value = 1.4142135623730951

//3 decimal places
println((value * 1000).round / 1000.toDouble)

//4 decimal places
println((value * 10000).round / 10000.toDouble)

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Goto processes in mysql.

So can see there is task still working.

Kill the particular process or wait until process complete.

Create dataframe from a matrix

I've found the following "cheat" to work very neatly and error-free

> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary

Et voila!

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

I personally use if/else statement in children with this kind of block statement. It only supports on Dart version 2.3.0 above.

if / else

Column(
    children: [
        if (_selectedIndex == 0) ...[
          DayScreen(),
        ] else ...[
          StatsScreen(),
        ],
    ],
 ),

if / else if

Column(
    children: [
        if (_selectedIndex == 0) ...[
          DayScreen(),
        ] else if(_selectedIndex == 1)...[
          StatsScreen(),
        ],
    ],
 ),

Finding CN of users in Active Directory

CN refers to class name, so put in your LDAP query CN=Users. Should work.

How to access site running apache server over lan without internet connection

if you did change the httpd.conf file located under conf_files folder, don't use windows notepad, you need a unix text editor, try TED pad, after making any changes to your httpd.conf file save it. ps: if you use a dos/windows editor you will end up with an "Error in Apache file changed" message. so do be careful.... Salam

How to change the application launcher icon on Flutter?

I have changed it in the following steps:

1) please add this dependency on your pubspec.yaml page

 dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_launcher_icons: ^0.7.4

2) you have to upload an image/icon on your project which you want to see as a launcher icon. (i have created a folder name:image in my project then upload the logo.png in the image folder). Now you have to add the below codes and paste your image path on image_path: in pubspec.yaml page.

flutter_icons:
  image_path: "images/logo.png"
  android: true
  ios: true

3) Go to terminal and execute this command:

flutter pub get

4) After executing the command then enter below command:

flutter pub run flutter_launcher_icons:main

5) Done

N.B: (of course add an updated dependency from

https://pub.dev/packages/flutter_launcher_icons#-installing-tab-

)

Laravel: How to Get Current Route Name? (v5 ... v7)

You can use below method :

Route::getCurrentRoute()->getPath();

In Laravel version > 6.0, You can use below methods:

$route = Route::current();

$name = Route::currentRouteName();

$action = Route::currentRouteAction();

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

fetch from origin with deleted remote branches?

This worked for me.

git remote update --prune

How can I find the last element in a List<>?

Lets get at the root of the question, how to address the last element of a List safely...

Assuming

List<string> myList = new List<string>();

Then

//NOT safe on an empty list!
string myString = myList[myList.Count -1];

//equivalent to the above line when Count is 0, bad index
string otherString = myList[-1];

"count-1" is a bad habit unless you first guarantee the list is not empty.

There is not a convenient way around checking for the empty list except to do it.

The shortest way I can think of is

string myString = (myList.Count != 0) ? myList [ myList.Count-1 ] : "";

you could go all out and make a delegate that always returns true, and pass it to FindLast, which will return the last value (or default constructed valye if the list is empty). This function starts at the end of the list so will be Big O(1) or constant time, despite the method normally being O(n).

//somewhere in your codebase, a strange delegate is defined
private static bool alwaysTrue(string in)
{
    return true;
}

//Wherever you are working with the list
string myString = myList.FindLast(alwaysTrue);

The FindLast method is ugly if you count the delegate part, but it only needs to be declared one place. If the list is empty, it will return a default constructed value of the list type "" for string. Taking the alwaysTrue delegate a step further, making it a template instead of string type, would be more useful.

PHP ini file_get_contents external url

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

is best for http url, But how to open https url help me

Creating a list of dictionaries results in a list of copies of the same dictionary

info is a pointer to a dictionary - you keep adding the same pointer to your list contact.

Insert info = {} into the loop and it should solve the problem:

...
content = []
for iframe in soup.find_all('iframe'):
    info = {}
    info['src'] = iframe.get('src')
    info['height'] = iframe.get('height')
    info['width'] = iframe.get('width')
...

Styling JQuery UI Autocomplete

Based on @md-nazrul-islam reply, This is what I did with SCSS:

ul.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    //@include border-radius(5px);
    @include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
    @include background-clip(padding-box);
    *border-right-width: 2px;
    *border-bottom-width: 2px;

    li.ui-menu-item{
        padding:0 .5em;
        line-height:2em;
        font-size:.8em;
        &.ui-state-focus{
            background: #F7F7F7;
        }
    }

}

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is supported by Chrome.

Chrome check parameters defined in : control panel/Internet option/Security.

Nevertheless,if it's possible to define four different area with IE, Chrome only check "Internet" area.

Scroll to the top of the page using JavaScript?

<script>
$(function(){
   var scroll_pos=(0);          
   $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>

Edit:

$('html, body').animate({scrollTop:(scroll_pos)}, 2000);

Another way scroll with top and left margin:

window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

Making href (anchor tag) request POST instead of GET?

Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS

$(function() {
  $("#employeeLink").on("click",function(e) {
    e.preventDefault(); // cancel the link itself
    $.post(this.href,function(data) {
      $("#someContainer").html(data);
    });
  });
});

If you insist on using frames which I strongly discourage, have a form and submit it with the link

<form action="employee.action" method="post" target="myFrame" id="myForm"></form>

and use (in plain JS)

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the link
     document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
   });
 });

Without a form we need to make one

 window.addEventListener("load",function() {
   document.getElementById("employeeLink").addEventListener("click",function(e) {
     e.preventDefault(); // cancel the actual link
     var myForm = document.createElement("form");
     myForm.action=this.href;// the href of the link
     myForm.target="myFrame";
     myForm.method="POST";
     myForm.submit();
   });
 });

Django {% with %} tags within {% if %} {% else %} tags?

if you want to stay DRY, use an include.

{% if foo %}
  {% with a as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% else %}
  {% with bar as b %}
    {% include "snipet.html" %}
  {% endwith %} 
{% endif %}

or, even better would be to write a method on the model that encapsulates the core logic:

def Patient(models.Model):
    ....
    def get_legally_responsible_party(self):
       if self.age > 18:
          return self
       else:
          return self.parent

Then in the template:

{% with patient.get_legally_responsible_party as p %}
  Do html stuff
{% endwith %} 

Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

User Authentication in ASP.NET Web API

If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.

void EnsureAuthenticated(string role)
{
    string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
    if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
    if (role != null && !Roles.IsUserInRole(parts[0], role))
        throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}

From the client side, this helper creates a HttpClient with the authentication header in place:

static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
    return client;
}

jQuery disable/enable submit button

Try

_x000D_
_x000D_
let check = inp=> inp.nextElementSibling.disabled = !inp.value;
_x000D_
<input type="text" name="textField" oninput="check(this)"/>_x000D_
<input type="submit" value="send" disabled />
_x000D_
_x000D_
_x000D_

creating array without declaring the size - java

I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

Display only date and no time

If you have a for loop such as the one below.

Change @item.StartDate to @item.StartDate.Value.ToShortDateString()

This will remove the time just in case you can't annotate your property in the model like in my case.

<table>
  <tr>
   <th>Type</th>
   <th>Start Date</th>
  </tr>
    @foreach (var item in Model.TestList) {
      <tr>
        <td>@item.TypeName</td>
        <td>@item.StartDate.Value.ToShortDateString()</td>
      </tr>
      }
</table>

How to resize superview to fit all subviews with autolayout?

You can do this by creating a constraint and connecting it via interface builder

See explanation: Auto_Layout_Constraints_in_Interface_Builder

raywenderlich beginning-auto-layout

AutolayoutPG Articles constraint Fundamentals

@interface ViewController : UIViewController {
    IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
    IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;

connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this

 self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign

I hope this clarifies it.

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

List vs tuple, when to use each?

Tuples are fixed size in nature whereas lists are dynamic.
In other words, a tuple is immutable whereas a list is mutable.

  1. You can't add elements to a tuple. Tuples have no append or extend method.
  2. You can't remove elements from a tuple. Tuples have no remove or pop method.
  3. You can find elements in a tuple, since this doesn’t change the tuple.
  4. You can also use the in operator to check if an element exists in the tuple.

  • Tuples are faster than lists. If you're defining a constant set of values and all you're ever going to do with it is iterate through it, use a tuple instead of a list.

  • It makes your code safer if you “write-protect” data that does not need to be changed. Using a tuple instead of a list is like having an implied assert statement that this data is constant, and that special thought (and a specific function) is required to override that.

  • Some tuples can be used as dictionary keys (specifically, tuples that contain immutable values like strings, numbers, and other tuples). Lists can never be used as dictionary keys, because lists are not immutable.

Source: Dive into Python 3

How to use @Nullable and @Nonnull annotations more effectively?

Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors.

As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants.

Another good tip is never returning null values, but using Null Object Pattern instead.

HTML SELECT - Change selected option by VALUE using JavaScript

try out this....

JSFIDDEL DEMO

using javascript

?document.getElementById('sel').value = 'car';??????????

using jQuery

$('#sel').val('car');

Python: Find index of minimum item in list of floats

You're effectively scanning the list once to find the min value, then scanning it again to find the index, you can do both in one go:

from operator import itemgetter
min(enumerate(a), key=itemgetter(1))[0] 

How do I style (css) radio buttons and labels?

The first part of your question can be solved with just HTML & CSS; you'll need to use Javascript for the second part.

Getting the Label Near the Radio Button

I'm not sure what you mean by "next to": on the same line and near, or on separate lines? If you want all of the radio buttons on the same line, just use margins to push them apart. If you want each of them on their own line, you have two options (unless you want to venture into float: territory):

  • Use <br />s to split the options apart and some CSS to vertically align them:
<style type='text/css'>
    .input input
    {
        width: 20px;
    }
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <br />
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

Applying a Style to the Currently Selected Label + Radio Button

Styling the <label> is why you'll need to resort to Javascript. A library like jQuery is perfect for this:

<style type='text/css'>
    .input label.focused
    {
        background-color: #EEEEEE;
        font-style: italic;
    }
</style>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
    $(document).ready(function() {
        $('.input :radio').focus(updateSelectedStyle);
        $('.input :radio').blur(updateSelectedStyle);
        $('.input :radio').change(updateSelectedStyle);
    })

    function updateSelectedStyle() {
        $('.input :radio').removeClass('focused').next().removeClass('focused');
        $('.input :radio:checked').addClass('focused').next().addClass('focused');
    }
</script>

The focus and blur hooks are needed to make this work in IE.

How to convert Observable<any> to array[]

//Component. home.ts :

  contacts:IContacts[];


ionViewDidLoad() {
this.rest.getContacts()
.subscribe( res=> this.contacts= res as IContacts[]) ;

// reorderArray. accepts only Arrays

    Reorder(indexes){
  reorderArray(this.contacts, indexes)
}

// Service . res.ts

getContacts(): Observable<IContacts[]> {
return this.http.get<IContacts[]>(this.apiUrl+"?results=5")

And it works fine

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

How do I wait until Task is finished in C#?

A clean example that answers the Title

string output = "Error";
Task task = Task.Factory.StartNew(() =>
{
    System.Threading.Thread.Sleep(2000);
    output = "Complete";
});

task.Wait();
Console.WriteLine(output);

Functional programming vs Object Oriented programming

  1. If you're in a heavily concurrent environment, then pure functional programming is useful. The lack of mutable state makes concurrency almost trivial. See Erlang.

  2. In a multiparadigm language, you may want to model some things functionally if the existence of mutable state is must an implementation detail, and thus FP is a good model for the problem domain. For example, see list comprehensions in Python or std.range in the D programming language. These are inspired by functional programming.

AngularJS $location not changing the path

I had to embed my $location.path() statement like this because my digest was still running:

       function routeMe(data) {                
            var waitForRender = function () {
                if ($http.pendingRequests.length > 0) {
                    $timeout(waitForRender);
                } else {
                    $location.path(data);
                }
            };
            $timeout(waitForRender);
        }

CMD: Export all the screen content to a text file

If you want to output ALL verbosity, not just stdout. But also any printf statements made by the program, any warnings, infos, etc, you have to add 2>&1 at the end of the command line.

In your case, the command will be

Program.exe > file.txt 2>&1

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

Could not load file or assembly "Oracle.DataAccess" or one of its dependencies

I needed a 64-bit version of oracle.dataaccess.dll but this caused problems with other libraries I was using.

[BadImageFormatException: Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format.]

I followed several steps above. Going to advance settings on the projects pool to toggle allow 32bit worked but I wasn't content to leave it like that so i turned it back on.

My project also had references that relied on Elmah and log4net references. I downloaded the latest version of these and my project was able to build and run fine without messing with the pools's allow 32bit setting.

Java correct way convert/cast object to Double

If your Object represents a number, eg, such as an Integer, you can cast it to a Number then call the doubleValue() method.

Double asDouble(Object o) {
    Double val = null;
    if (o instanceof Number) {
        val = ((Number) o).doubleValue();
    }
    return val;
}

HTTP 1.0 vs 1.1

A key compatibility issue is support for persistent connections. I recently worked on a server that "supported" HTTP/1.1, yet failed to close the connection when a client sent an HTTP/1.0 request. When writing a server that supports HTTP/1.1, be sure it also works well with HTTP/1.0-only clients.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.

My favourite is:

a = b;

Where a and b are vectors.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

On a related note: the java compiler uses int to represent boolean since JVM has a limited support for the boolean type.See Section 3.3.4 The boolean type.

In JVM, the integer zero represents false, and any non-zero integer represents true (Source : Inside Java Virtual Machine by Bill Venners)

W3WP.EXE using 100% CPU - where to start?

It's not much of an answer, but you might need to go old school and capture an image snapshot of the IIS process and debug it. You might also want to check out Tess Ferrandez's blog - she is a kick a** microsoft escalation engineer and her blog focuses on debugging windows ASP.NET, but the blog is relevant to windows debugging in general. If you select the ASP.NET tag (which is what I've linked to) then you'll see several items that are similar.

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

Use an escape clause:

select *
  from (select '123abc456' AS result from dual
        union all
        select '123abc%456' AS result from dual
       )
  WHERE result LIKE '%abc\%%' escape '\'

Result

123abc%456

You can set your escape character to whatever you want. In this case, the default '\'. The escaped '\%' becomes a literal, the second '%' is not escaped, so again wild card.

See List of special characters for SQL LIKE clause

Correct way to select from two tables in SQL Server with no common field to join on

Cross join will help to join multiple tables with no common fields.But be careful while joining as this join will give cartesian resultset of two tables. QUERY:

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
CROSS JOIN table2

Alternative way to join on some condition that is always true like

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
INNER JOIN table2 ON 1=1

But this type of query should be avoided for performance as well as coding standards.

How to search a string in multiple files and return the names of files in Powershell?

With PowerShell, go to the path where your files are and then type this command and replace ENTER THE STRING YOU SEARCH HERE (but keep the double quotes):

findstr /S /I /M /C:"ENTER THE STRING YOU SEARCH HERE" *.*

Have a nice day

Maximum Length of Command Line String

In Windows 10, it's still 8191 characters...at least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat

Changing ViewPager to enable infinite page scrolling

Actually, I've been looking at the various ways to do this "infinite" pagination, and even though the human notion of time is that it is infinite (even though we have a notion of the beginning and end of time), computers deal in the discrete. There is a minimum and maximum time (that can be adjusted as time goes on, remember the basis of the Y2K scare?).

Anyways, the point of this discussion is that it is/should be sufficient to support a relatively infinite date range through an actually finite date range. A great example of this is the Android framework's CalendarView implementation, and the WeeksAdapter within it. The default minimum date is in 1900 and the default maximum date is in 2100, this should cover 99% of the calendar use of anyone within a 10 year radius around today easily.

What they do in their implementation (focused on weeks) is compute the number of weeks between the minimum and maximum date. This becomes the number of pages in the pager. Remember that the pager doesn't need to maintain all of these pages simultaneously (setOffscreenPageLimit(int)), it just needs to be able to create the page based on the page number (or index/position). In this case the index is the number of weeks that the week is from the minimum date. With this approach you just have to maintain the minimum date and the number of pages (distance to the maximum date), then for any page you can easily compute the week associated with that page. No dancing around the fact that ViewPager doesn't support looping (a.k.a infinite pagination), and trying to force it to behave like it can scroll infinitely.

new FragmentStatePagerAdapter(getFragmentManager()) {
    @Override
    public Fragment getItem(int index) {
        final Bundle arguments = new Bundle(getArguments());
        final Calendar temp_calendar = Calendar.getInstance();
        temp_calendar.setTimeInMillis(_minimum_date.getTimeInMillis());
        temp_calendar.setFirstDayOfWeek(_calendar.getStartOfWeek());
        temp_calendar.add(Calendar.WEEK_OF_YEAR, index);
        // Moves to the first day of this week
        temp_calendar.add(Calendar.DAY_OF_YEAR,
                -UiUtils.modulus(temp_calendar.get(Calendar.DAY_OF_WEEK) - temp_calendar.getFirstDayOfWeek(),
                7));
        arguments.putLong(KEY_DATE, temp_calendar.getTimeInMillis());
        return Fragment.instantiate(getActivity(), WeekDaysFragment.class.getName(), arguments);
    }

    @Override
    public int getCount() {
        return _total_number_of_weeks;
    }
};

Then WeekDaysFragment can easily display the week starting at the date passed in its arguments.

Alternatively, it seems that some version of the Calendar app on Android uses a ViewSwitcher (which means there's only 2 pages, the one you see and the hidden page). It then changes the transition animation based on which way the user swiped and renders the next/previous page accordingly. In this way you get infinite pagination because it just switching between two pages infinitely. This requires using a View for the page though, which is way I went with the first approach.

In general, if you want "infinite pagination", it's probably because your pages are based off of dates or times somehow. If this is the case consider using a finite subset of time that is relatively infinite instead. This is how CalendarView is implemented for example. Or you can use the ViewSwitcher approach. The advantage of these two approaches is that neither does anything particularly unusual with the ViewSwitcher or ViewPager, and doesn't require any tricks or reimplementation to coerce them to behave infinitely (ViewSwitcher is already designed to switch between views infinitely, but ViewPager is designed to work on a finite, but not necessarily constant, set of pages).

'tuple' object does not support item assignment

A tuple is immutable and thus you get the error you posted.

>>> pixels = [1, 2, 3]
>>> pixels[0] = 5
>>> pixels = (1, 2, 3)
>>> pixels[0] = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

In your specific case, as correctly pointed out in other answers, you should write:

pixel = (pixel[0] + 20, pixel[1], pixel[2])

How to input matrix (2D list) in Python?

a = []
b = []

m=input("enter no of rows: ")
n=input("enter no of coloumns: ")

for i in range(n):
     a = []
     for j in range(m):
         a.append(input())
     b.append(a)

Input : 1 2 3 4 5 6 7 8 9

Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]

How to prevent "The play() request was interrupted by a call to pause()" error?

After hours of seaching and working, i found perfect solution.

// Initializing values
var isPlaying = true;

// On video playing toggle values
video.onplaying = function() {
    isPlaying = true;
};

// On video pause toggle values
video.onpause = function() {
    isPlaying = false;
};

// Play video function
function playVid() {      
    if (video.paused && !isPlaying) {
        video.play();
    }
} 

// Pause video function
function pauseVid() {     
    if (!video.paused && isPlaying) {
        video.pause();
    }
}

After that, you can toggle play/pause as fast as you can, it will work properly.

How can I set the opacity or transparency of a Panel in WinForms?

Yes, opacity can only work on top-level windows. It uses a hardware feature of the video adapter, that doesn't support child windows, like Panel. The only top-level Control derived class in Winforms is Form.

Several of the 'pure' Winform controls, the ones that do their own painting instead of letting a native Windows control do the job, do however support a transparent BackColor. Panel is one of them. It uses a trick, it asks the Parent to draw itself to produce the background pixels. One side-effect of this trick is that overlapping controls doesn't work, you only see the parent pixels, not the overlapped controls.

This sample form shows it at work:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.BackColor = Color.White;
        panel1.BackColor = Color.FromArgb(25, Color.Black);
    }
    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.DrawLine(Pens.Yellow, 0, 0, 100, 100);
    }
}

If that's not good enough then you need to consider stacking forms on top of each other. Like this.

Notable perhaps is that this restriction is lifted in Windows 8. It no longer uses the video adapter overlay feature and DWM (aka Aero) cannot be turned off anymore. Which makes opacity/transparency on child windows easy to implement. Relying on this is of course future-music for a while to come. Windows 7 will be the next XP :)

How to send push notification to web browser?

So here I am answering my own question. I have got answers to all my queries from people who have build push notification services in the past.

Update (May 2018): Here is a comprehensive and a very well written doc on web push notification from Google.

Answer to the original questions asked 3 years ago:

  1. Can we use GCM/APNS to send push notification to all Web Browsers including Firefox & Safari?

Answer: Google has deprecated GCM as of April 2018. You can now use Firebase Cloud Messaging (FCM). This supports all platforms including web browsers.

  1. If not via GCM can we have our own back-end to do the same?

Answer: Yes, push notification can be sent from our own back-end. Support for the same has come to all major browsers.

Check this codelab from Google to better understand the implementation.

Some Tutorials:

  • Implementing push notification in Django Here.
  • Using flask to send push notification Here & Here.
  • Sending push notifcaiton from Nodejs Here
  • Sending push notification using php Here & Here
  • Sending push notification from Wordpress. Here & Here
  • Sending push notification from Drupal. Here

Implementing own backend in various programming languages.:

Further Readings: - - Documentation from Firefox website can be read here. - A very good overview of Web Push by Google can be found here. - An FAQ answering most common confusions and questions.

Are there any free services to do the same? There are some companies that provide a similar solution in free, freemium and paid models. Am listing few below:

  1. https://onesignal.com/ (Free | Support all platforms)
  2. https://firebase.google.com/products/cloud-messaging/ (Free)
  3. https://clevertap.com/ (Has free plan)
  4. https://goroost.com/

Note: When choosing a free service remember to read the TOS. Free services often work by collecting user data for various purposes including analytics.

Apart from that, you need to have HTTPS to send push notifications. However, you can get https freely via letsencrypt.org

How to Use slideDown (or show) function on a table row?

function hideTr(tr) {
  tr.find('td').wrapInner('<div style="display: block;" />').parent().find('td > div').slideUp(50, function () {
    tr.hide();
    var $set = jQuery(this);
    $set.replaceWith($set.contents());
  });
}

function showTr(tr) {
  tr.show()
  tr.find('td').wrapInner('<div style="display: none;" />').parent().find('td > div').slideDown(50, function() {
    var $set = jQuery(this);
    $set.replaceWith($set.contents());
  });
}

you can use these methods like:

jQuery("[data-toggle-tr-trigger]").click(function() {
  var $tr = jQuery(this).parents(trClass).nextUntil(trClass);
  if($tr.is(':hidden')) {
    showTr($tr);
  } else {
    hideTr($tr);
  }
});

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

good points already made here, but while there is lots of information about how rendering of margins is accomplished by the browser, the why isn't quite answered yet:

"Why is margin-top:-8px not the same as margin-bottom:8px?"

what we also could ask is:

Why doesn't a positive bottom margin 'bump up' preceding elements, whereas a positive top-margin 'bumps down' following elements?

so what we see is that there is a difference in the rendering of margins depending on the side they are applied to - top (and left) margins are different from bottom (and right) ones.

things are becoming clearer when having a (simplified) look at how styles are applied by the browser: elements are rendered top-down in the viewport, starting in the top left corner (let's stick with the vertical rendering for now, keeping in mind that the horizontal one is treated the same).

consider the following html:

<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>

analogous to their position in code, these three boxes appear stacked 'top-down' in the browser (keeping things simple, we won't consider here the order property of the css3 'flex-box' module). so, whenever styles are applied to box 3, preceding element's positions (for box 1 and 2) have already been determined, and shouldn't be altered any more for the sake of rendering speed.

now, imagine a top margin of -10px for box 3. instead of shifting up all preceding elements to gather some space, the browser will just push box 3 up, so it's rendered on top of (or underneath, depending on the z-index) any preceding elements. even if performance wasn't an issue, moving all elements up could mean shifting them out of the viewport, thus the current scrolling position would have to be altered to have everything visible again.

same applies to a bottom margin for box 3, both negative and positive: instead of influencing already evaluated elements, only a new 'starting point' for upcoming elements is determined. thus setting a positive bottom margin will push the following elements down; a negative one will push them up.

Create a button with rounded border

If you don't want to use OutlineButton and want to stick to normal RaisedButton, you can wrap your button in ClipRRect or ClipOval like:

ClipRRect(
  borderRadius: BorderRadius.circular(40),
  child: RaisedButton(
    child: Text("Button"),
    onPressed: () {},
  ),
),

Installing tensorflow with anaconda in windows

I have python 3.5 with anaconda. First I tried everything given above but it did not work for me on windows 10 64bit. So I simply tried:-

  1. Open the command prompt
  2. Check for python version for which you want to install tensorflow, if you have multiple versions of python.
  3. If you just have one version, then type in cmd:

    C:/>conda install tensorflow 
    

    for multiple versions of python, type in cmd:

    C:/>conda install tensorflow python=version(e.g.python=3.5)
    

It works, just give it a try.
After installation open ipython console and import tensorflow:

import tensorflow

If tensorflow installed properly then you are ready to go. Enjoy machine learning:-)

How to bind Dataset to DataGridView in windows application

you can set the dataset to grid as follows:

//assuming your dataset object is ds

datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();

tablename is the name of the table, which you want to show on the grid.

I hope, it helps.

B.R.

Write objects into file with Node.js

In my experience JSON.stringify is slightly faster than util.inspect. I had to save the result object of a DB2 query as a json file, The query returned an object of 92k rows, the conversion took very long to complete with util.inspect, so I did the following test by writing the same 1000 record object to a file with both methods.

  1. JSON.Stringify

    fs.writeFile('./data.json', JSON.stringify(obj, null, 2));
    

Time: 3:57 (3 min 57 sec)

Result's format:

[
  {
    "PROB": "00001",
    "BO": "AXZ",
    "CNTRY": "649"
   },
  ...
]
  1. util.inspect

    var util = require('util');
    fs.writeFile('./data.json', util.inspect(obj, false, 2, false));
    

Time: 4:12 (4 min 12 sec)

Result's format:

[ { PROB: '00001',
    BO: 'AXZ',
    CNTRY: '649' },
    ...
]

How to add Certificate Authority file in CentOS 7

Find *.pem file and place it to the anchors sub-directory or just simply link the *.pem file to there.

yum install -y ca-certificates
update-ca-trust force-enable
sudo ln -s /etc/ssl/your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
update-ca-trust

Create PDF from a list of images

Here is ilovecomputer's answer packed into a function and directly usable. It also allows to reduce image sizes and works well.

The code assumes a folder inside input_dir that contains images ordered alphabetically by their name and outputs a pdf with the name of the folder and potentially a prefix string for the name.

import os
from PIL import Image

def convert_images_to_pdf(export_dir, input_dir, folder, prefix='', quality=20):
    current_dir = os.path.join(input_dir, folder)
    image_files = os.listdir(current_dir)
    im_list = [Image.open(os.path.join(current_dir, image_file)) for image_file in image_files]

    pdf_filename = os.path.join(export_dir, prefix + folder + '.pdf')
    im_list[0].save(pdf_filename, "PDF", quality=quality, optimize=True, save_all=True, append_images=im_list[1:])

export_dir = r"D:\pdfs"
input_dir = r"D:\image_folders"
folders = os.listdir(input_dir)
[convert_images_to_pdf(export_dir, input_dir, folder, prefix='') for folder in folders];