Programs & Examples On #Resource management

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

What is the difference between WCF and WPF?

Windows communication Fundation(WCF) is used for connecting different applications and passing the data's between them using endpoints.

Windows Presentation Foundation is used for designing rich internet applications in the format of xaml.

Lost httpd.conf file located apache

Get the path of running Apache

$ ps -ef | grep apache
apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2

Append -V argument to the path

$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

Using relative URL in CSS file, what location is it relative to?

This worked for me. adding two dots and slash.

body{
    background: url(../images/yourimage.png);
}

MVC 4 Razor adding input type date

You will get it by tag type="date"...then it will render beautiful calendar and all...

@Html.TextBoxFor(model => model.EndTime, new { type = "date" })

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

What I am thinking is having webpack would be easy when production release.

FYI : https://github.com/Piusha/ngx-lazyloading

Facebook Architecture

"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"

I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.

Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.

If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.

How to pause in C?

getch() can also be used which is defined in conio.h.

The sample program would look like this :

#include <stdio.h>
#include <conio.h>

int main()
{
    //your code 
    getch();
    return 0; 
} 

getch() waits for any character input from the keyboard (not necessarily enter key).

How can I compile my Perl script so it can be executed on systems without perl installed?

Perl files are scripts, not executable programs. Therefore, for them to 'run', they are going to need an interpreter.

So, you have two choices: 1) Have the interpreter on the machine that you wish to run the script, or 2) Have the script running on a networked (or Internet) machine that you remotely connect to (ie with a browser)

How to comment out a block of code in Python

Hide the triple quotes in a context that won't be mistaken for a docstring, eg:

'''
...statements...
''' and None

or:

if False: '''
...statements...
'''

Open popup and refresh parent page on close popup

You can use the below code in the parent page.

<script>
    window.onunload = refreshParent;
    function refreshParent() {
      window.opener.location.reload();
    }
</script>

How to run a function in jquery

function doosomething ()
{
  //Doo something
}


$(function () {


  $("div.class").click(doosomething);

  $("div.secondclass").click(doosomething);

});

Difference between two dates in Python

I tried the code posted by larsmans above but, there are a couple of problems:

1) The code as is will throw the error as mentioned by mauguerra 2) If you change the code to the following:

...
    d1 = d1.strftime("%Y-%m-%d")
    d2 = d2.strftime("%Y-%m-%d")
    return abs((d2 - d1).days)

This will convert your datetime objects to strings but, two things

1) Trying to do d2 - d1 will fail as you cannot use the minus operator on strings and 2) If you read the first line of the above answer it stated, you want to use the - operator on two datetime objects but, you just converted them to strings

What I found is that you literally only need the following:

import datetime

end_date = datetime.datetime.utcnow()
start_date = end_date - datetime.timedelta(days=8)
difference_in_days = abs((end_date - start_date).days)

print difference_in_days

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

How do I prevent mails sent through PHP mail() from going to spam?

There is no sure shot trick. You need to explore the reasons why your mails are classified as spam. SpamAssassin hase a page describing Some Tips for Legitimate Senders to Avoid False Positives. See also Coding Horror: So You'd Like to Send Some Email (Through Code)

How do you find the sum of all the numbers in an array in Java?

There is no 'method in a math class' for such thing. Its not like its a square root function or something like that.

You just need to have a variable for the sum and loop through the array adding each value you find to the sum.

Make Adobe fonts work with CSS3 @font-face in IE9

I can only explain you how to fix the "CSS3114" error.
You have to change the embedding level of your TTF file.

Using the appropriate tool you can set it to installable embedding allowed.
For a 64-bit version, check @user22600's answer.

How to get PID of process by specifying process name and store it in a variable to use further?

use grep [n]ame to remove that grep -v name this is first... Sec using xargs in the way how it is up there is wrong to rnu whatever it is piped you have to use -i ( interactive mode) otherwise you may have issues with the command.

ps axf | grep | grep -v grep | awk '{print "kill -9 " $1}' ? ps aux |grep [n]ame | awk '{print "kill -9 " $2}' ? isnt that better ?

Guid.NewGuid() vs. new Guid()

Guid.NewGuid() creates a new UUID using an algorithm that is designed to make collisions very, very unlikely.

new Guid() creates a UUID that is all-zeros.

Generally you would prefer the former, because that's the point of a UUID (unless you're receiving it from somewhere else of course).

There are cases where you do indeed want an all-zero UUID, but in this case Guid.Empty or default(Guid) is clearer about your intent, and there's less chance of someone reading it expecting a unique value had been created.

In all, new Guid() isn't that useful due to this lack of clarity, but it's not possible to have a value-type that doesn't have a parameterless constructor that returns an all-zeros-and-nulls value.

Edit: Actually, it is possible to have a parameterless constructor on a value type that doesn't set everything to zero and null, but you can't do it in C#, and the rules about when it will be called and when there will just be an all-zero struct created are confusing, so it's not a good idea anyway.

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

Can HTML be embedded inside PHP "if" statement?

<?php if ($my_name == 'aboutme') { ?>
    HTML_GOES_HERE
<?php } ?>

What's the quickest way to multiply multiple cells by another number?

As one of the answers above says: " then drag the formula fill handle." This KEY feature is not mentioned in MS's explanation, nor in others here. I spent over an hour trying to follow the various instructions, to no avail. This is because you have to click and hold near the bottom of the cell just right (and at least on my computer that is not at all easy) so that a sort of "handle" appears. Once you're luck enough to get that, then carefully slide ["drag"] your cursor down to the lowermost of the cells you want to be multiplied by the constant. The products should show up in each cell as you move down. Just dragging down will give you only the answer in the first cell and a lot of white space.

Is it possible to declare two variables of different types in a for loop?

You can't declare multiple types in the initialization, but you can assign to multiple types E.G.

{
   int i;
   char x;
   for(i = 0, x = 'p'; ...){
      ...
   }
}

Just declare them in their own scope.

SQL: How to perform string does not equal

NULL-safe condition would looks like:

select * from table
where NOT (tester <=> 'username')

Excel: How to check if a cell is empty with VBA?

This site uses the method isEmpty().

Edit: content grabbed from site, before the url will going to be invalid.

Worksheets("Sheet1").Range("A1").Sort _
    key1:=Worksheets("Sheet1").Range("A1")
Set currentCell = Worksheets("Sheet1").Range("A1")
Do While Not IsEmpty(currentCell)
    Set nextCell = currentCell.Offset(1, 0)
    If nextCell.Value = currentCell.Value Then
        currentCell.EntireRow.Delete
    End If
    Set currentCell = nextCell
Loop

In the first step the data in the first column from Sheet1 will be sort. In the second step, all rows with same data will be removed.

IIS: Display all sites and bindings in PowerShell

Try something like this to get the format you wanted:

Get-WebBinding | % {
    $name = $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1'
    New-Object psobject -Property @{
        Name = $name
        Binding = $_.bindinginformation.Split(":")[-1]
    }
} | Group-Object -Property Name | 
Format-Table Name, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap

How to search JSON data in MySQL?

I use this query

SELECT id FROM table_name WHERE field_name REGEXP '"key_name":"([^"])key_word([^"])"';
or
SELECT id FROM table_name WHERE field_name RLIKE '"key_name":"[[:<:]]key_word[[:>:]]"';

The first query I use it to search partial value. The second query I use it to search exact word.

Extracting text from HTML file using Python

Perl way (sorry mom, i'll never do it in production).

import re

def html2text(html):
    res = re.sub('<.*?>', ' ', html, flags=re.DOTALL | re.MULTILINE)
    res = re.sub('\n+', '\n', res)
    res = re.sub('\r+', '', res)
    res = re.sub('[\t ]+', ' ', res)
    res = re.sub('\t+', '\t', res)
    res = re.sub('(\n )+', '\n ', res)
    return res

How to determine if OpenSSL and mod_ssl are installed on Apache2

Fortunately, Most flavors of Linux have OpenSSL "out of the box".

To verify installation:

openssl version
Response:
OpenSSL 1.0.1t 3 May 2016

Note: version OpenSSL 1.0.1 through 1.0.1f (inclusive)
are vulnerable to the OpenSSL Heartbleed Bug.
Versions 1.0.1g and greater are fixed.

For additional install info:

Ubuntu/Debian
dpkg -l | grep -i openssl
Response:
ii libcrypt-openssl-random-perl 0.04-2+b1 amd64 module to access the OpenSSL pseudo-random number generator
ii libcurl3:amd64 7.38.0-4+deb8u5 amd64 easy-to-use client-side URL transfer library (OpenSSL flavour)
ii libgnutls-openssl27:amd64 3.3.8-6+deb8u4 amd64 GNU TLS library - OpenSSL wrapper
ii openssl 1.0.1t-1+deb8u6 amd64 Secure Sockets Layer toolkit - cryptographic utility
ii python-ndg-httpsclient 0.3.2-1 all enhanced HTTPS support for httplib and urllib2 using PyOpenSSL
ii python-openssl 0.14-1 all Python 2 wrapper around the OpenSSL library
ii ssl-cert 1.0.35 all simple debconf wrapper for OpenSSL

Yea, OpenSSL is installed!

To install OpenSSL if you don't have it, try:

Debian/Ubuntu:
sudo apt-get install openssl

RedHat/CentOS:
yum install openssl

Converting json results to a date

If that number represents milliseconds, use the Date's constructor :

var myDate = new Date(1238540400000);

How do I find which application is using up my port?

On the command prompt, do:

netstat -nb

jQuery datepicker, onSelect won't work

No comma after the last property.

Semicolon after alert(date);

Case on datepicker (not datePicker)

Check your other uppercase / lowercase for the properties.

$(function() {
    $('.date-pick').datepicker( {
        onSelect: function(date) {
            alert(date);
        },
        selectWeek: true,
        inline: true,
        startDate: '01/01/2000',
        firstDay: 1
    });
});

Reset C int array to zero : the fastest way?

This question, although rather old, needs some benchmarks, as it asks for not the most idiomatic way, or the way that can be written in the fewest number of lines, but the fastest way. And it is silly to answer that question without some actual testing. So I compared four solutions, memset vs. std::fill vs. ZERO of AnT's answer vs a solution I made using AVX intrinsics.

Note that this solution is not generic, it only works on data of 32 or 64 bits. Please comment if this code is doing something incorrect.

#include<immintrin.h>
#define intrin_ZERO(a,n){\
size_t x = 0;\
const size_t inc = 32 / sizeof(*(a));/*size of 256 bit register over size of variable*/\
for (;x < n-inc;x+=inc)\
    _mm256_storeu_ps((float *)((a)+x),_mm256_setzero_ps());\
if(4 == sizeof(*(a))){\
    switch(n-x){\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
    };\
}\
else if(8 == sizeof(*(a))){\
switch(n-x){\
    case 7:\
        (a)[x] = 0;x++;\
    case 6:\
        (a)[x] = 0;x++;\
    case 5:\
        (a)[x] = 0;x++;\
    case 4:\
        _mm_storeu_ps((float *)((a)+x),_mm_setzero_ps());break;\
    case 3:\
        (a)[x] = 0;x++;\
    case 2:\
        ((long long *)(a))[x] = 0;break;\
    case 1:\
        (a)[x] = 0;\
        break;\
    case 0:\
        break;\
};\
}\
}

I will not claim that this is the fastest method, since I am not a low level optimization expert. Rather it is an example of a correct architecture dependent implementation that is faster than memset.

Now, onto the results. I calculated performance for size 100 int and long long arrays, both statically and dynamically allocated, but with the exception of msvc, which did a dead code elimination on static arrays, the results were extremely comparable, so I will show only dynamic array performance. Time markings are ms for 1 million iterations, using time.h's low precision clock function.

clang 3.8 (Using the clang-cl frontend, optimization flags= /OX /arch:AVX /Oi /Ot)

int:
memset:      99
fill:        97
ZERO:        98
intrin_ZERO: 90

long long:
memset:      285
fill:        286
ZERO:        285
intrin_ZERO: 188

gcc 5.1.0 (optimization flags: -O3 -march=native -mtune=native -mavx):

int:
memset:      268
fill:        268
ZERO:        268
intrin_ZERO: 91
long long:
memset:      402
fill:        399
ZERO:        400
intrin_ZERO: 185

msvc 2015 (optimization flags: /OX /arch:AVX /Oi /Ot):

int
memset:      196
fill:        613
ZERO:        221
intrin_ZERO: 95
long long:
memset:      273
fill:        559
ZERO:        376
intrin_ZERO: 188

There is a lot interesting going on here: llvm killing gcc, MSVC's typical spotty optimizations (it does an impressive dead code elimination on static arrays and then has awful performance for fill). Although my implementation is significantly faster, this may only be because it recognizes that bit clearing has much less overhead than any other setting operation.

Clang's implementation merits more looking at, as it is significantly faster. Some additional testing shows that its memset is in fact specialized for zero--non zero memsets for 400 byte array are much slower (~220ms) and are comparable to gcc's. However, the nonzero memsetting with an 800 byte array makes no speed difference, which is probably why in that case, their memset has worse performance than my implementation--the specialization is only for small arrays, and the cuttoff is right around 800 bytes. Also note that gcc 'fill' and 'ZERO' are not optimizing to memset (looking at generated code), gcc is simply generating code with identical performance characteristics.

Conclusion: memset is not really optimized for this task as well as people would pretend it is (otherwise gcc and msvc and llvm's memset would have the same performance). If performance matters then memset should not be a final solution, especially for these awkward medium sized arrays, because it is not specialized for bit clearing, and it is not hand optimized any better than the compiler can do on its own.

Create intermediate folders if one doesn't exist

A nice Java 7+ answer from Benoit Blanchon can be found here:

With Java 7, you can use Files.createDirectories().

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));

Countdown timer using Moment js

You're not using react native or react so forgive me this isn't a solution for you. - since this is a 7 year old post I'm pretty sure you figured it out by now ;)

But I was looking for something similar for react-native and it led me to this SO question. Incase anyone else winds up down the same road I thought I'd share my use-moment-countdown hook for react or react native: https://github.com/BrooklinJazz/use-moment-countdown.

For example you can make a 10 minute timer like so:

import React from 'react'

import  { useCountdown } from 'use-moment-countdown'

const App = () => {
  const {start, time} = useCountdown({m: 10})
  return (
    <div onClick={start}>
      {time.format("hh:mm:ss")}
    </div>
  )
}

export default App

What are the differences between B trees and B+ trees?

A B+tree is a balanced tree in which every path from the root of the tree to a leaf is of the same length, and each nonleaf node of the tree has between [n/2] and [n] children, where n is fixed for a particular tree. It contains index pages and data pages. Binary trees only have two children per parent node, B+ trees can have a variable number of children for each parent node

How to compare two JSON objects with the same elements in a different order equal?

Decode them and compare them as mgilson comment.

Order does not matter for dictionary as long as the keys, and values matches. (Dictionary has no order in Python)

>>> {'a': 1, 'b': 2} == {'b': 2, 'a': 1}
True

But order is important in list; sorting will solve the problem for the lists.

>>> [1, 2] == [2, 1]
False
>>> [1, 2] == sorted([2, 1])
True

>>> a = '{"errors": [{"error": "invalid", "field": "email"}, {"error": "required", "field": "name"}], "success": false}'
>>> b = '{"errors": [{"error": "required", "field": "name"}, {"error": "invalid", "field": "email"}], "success": false}'
>>> a, b = json.loads(a), json.loads(b)
>>> a['errors'].sort()
>>> b['errors'].sort()
>>> a == b
True

Above example will work for the JSON in the question. For general solution, see Zero Piraeus's answer.

Difference between Dictionary and Hashtable

Lets give an example that would explain the difference between hashtable and dictionary.

Here is a method that implements hashtable

public void MethodHashTable()
{
    Hashtable objHashTable = new Hashtable();
    objHashTable.Add(1, 100);    // int
    objHashTable.Add(2.99, 200); // float
    objHashTable.Add('A', 300);  // char
    objHashTable.Add("4", 400);  // string

    lblDisplay1.Text = objHashTable[1].ToString();
    lblDisplay2.Text = objHashTable[2.99].ToString();
    lblDisplay3.Text = objHashTable['A'].ToString();
    lblDisplay4.Text = objHashTable["4"].ToString();


    // ----------- Not Possible for HashTable ----------
    //foreach (KeyValuePair<string, int> pair in objHashTable)
    //{
    //    lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    //}
}

The following is for dictionary

  public void MethodDictionary()
  {
    Dictionary<string, int> dictionary = new Dictionary<string, int>();
    dictionary.Add("cat", 2);
    dictionary.Add("dog", 1);
    dictionary.Add("llama", 0);
    dictionary.Add("iguana", -1);

    //dictionary.Add(1, -2); // Compilation Error

    foreach (KeyValuePair<string, int> pair in dictionary)
    {
        lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
    }
  }

What is the canonical way to trim a string in Ruby without creating a new string?

If you want to use another method after you need something like this:

( str.strip || str ).split(',')

This way you can strip and still do something after :)

how to check if input field is empty

Why don't u use:

<script>
$('input').keyup(function(){
if(($('#eng').val().length > 0) && ($('#spa').val().length > 0))
    $("#submit").prop('disabled', false);
else
    $("#submit").prop('disabled', true);
});
</script>

Then delete the onkeyup function on the input.

How can I limit the visible options in an HTML <select> dropdown?

the size attribute matters, if the size=5 then first 5 items will be shown and for others you need to scroll down..

<select name="numbers" size="5">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
</select>

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

1.

Add the applicationId to the application's build.gradle:

android {
    ...
    defaultConfig {
        applicationId "com.example.my.app"
        ...
    }
}

And than Clean Project -> Build or Rebuild Project


2. If your minSdkVersion <= 20 (https://developer.android.com/studio/build/multidex)

Use Multidex correctly.

application's build.gradle

android {
...               
    defaultConfig {
    ....
        multiDexEnabled true
    }
    ...
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    ...
}

manifest.xml

<application
    ...
    android:name="android.support.multidex.MultiDexApplication" >
    ...

3.

If you use a custom Application class

public class MyApplication extends MultiDexApplication {
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}

manifest.xml

<application
    ...
    android:name="com.example.my.app.MyApplication" >
    ...

Difference between Math.Floor() and Math.Truncate()

Some examples:

Round(1.5) = 2
Round(2.5) = 2
Round(1.5, MidpointRounding.AwayFromZero) = 2
Round(2.5, MidpointRounding.AwayFromZero) = 3
Round(1.55, 1) = 1.6
Round(1.65, 1) = 1.6
Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6
Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7

Truncate(2.10) = 2
Truncate(2.00) = 2
Truncate(1.90) = 1
Truncate(1.80) = 1

How to repair COMException error 80040154?

To find the DLL, go to your 64-bit machine and open the registry. Find the key called HKEY_CLASSES_ROOT\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32. This key will have the filename of the DLL as its default value.

If you solved the problem on your 64-bit machine by recompiling your project for x86, then you'll need to look in the 32-bit portion of the registry instead of in the normal place. This is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32.

If the DLL is built for 32 bits then you can use it directly on your 32-bit machine. If it's built for 64 bits then you'll have to contact the vendor and get a 32-bit version from them.

When you have the DLL, register it by running c:\windows\system32\regsvr32.exe.

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

Typographically, the correct glyph to use in sentence punctuation is the quote mark, both single (including for apostrophes) and double quotes. The straight-looking mark that we often see on the web is called a prime, which also comes in single and double varieties and has limited uses, mostly for measurements.

This article explains how to use them correctly.

showDialog deprecated. What's the alternative?

To display dialog box, you can use the following code. This is to display a simple AlertDialog box with multiple check boxes:

AlertDialog.Builder alertDialog= new AlertDialog.Builder(MainActivity.this); .
            alertDialog.setTitle("this is a dialog box ");
            alertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(),"ok ive wrote this 'ok' here" ,Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                        Toast.makeText(getBaseContext(), "cancel ' comment same as ok'", Toast.LENGTH_SHORT).show();


                }
            });
            alertDialog.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getBaseContext(), items[which] +(isChecked?"clicked'again i've wrrten this click'":"unchecked"),Toast.LENGTH_SHORT).show();

                }
            });
            alertDialog.show();

Heading

Whereas if you are using the showDialog function to display different dialog box or anything as per the arguments passed, you can create a self function and can call it under the onClickListener() function. Something like:

 public CharSequence[] items={"google","Apple","Kaye"};
public boolean[] checkedItems=new boolean[items.length];
Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bt=(Button) findViewById(R.id.bt);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            display(0);             
        }       
    });
}

and add the code of dialog box given above in the function definition.

why should I make a copy of a data frame in pandas

This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:

df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)

You'll get:

x
0 -1
1  2

In contrast, the following leaves df unchanged:

df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1

How to select/get drop down option in Selenium 2

Take a look at the section about filling in forms using webdriver in the selenium documentation and the javadoc for the Select class.

To select an option based on the label:

Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");

To get the first selected value:

WebElement option = select.getFirstSelectedOption()

How to determine the current language of a wordpress page when using polylang?

We can use the get_locale function:

if (get_locale() == 'en_GB') {
    // drink tea
}

How do I turn off autocommit for a MySQL client?

You do this in 3 different ways:

  1. Before you do an INSERT, always issue a BEGIN; statement. This will turn off autocommits. You will need to do a COMMIT; once you want your data to be persisted in the database.

  2. Use autocommit=0; every time you instantiate a database connection.

  3. For a global setting, add a autocommit=0 variable in your my.cnf configuration file in MySQL.

Determine when a ViewPager changes pages

ViewPager.setOnPageChangeListener is deprecated now. You now need to use ViewPager.addOnPageChangeListener instead.

for example,

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

How do I print out the contents of an object in Rails for easy debugging?

I generally first try .inspect, if that doesn't give me what I want, I'll switch to .to_yaml.

class User
  attr_accessor :name, :age
end

user = User.new
user.name = "John Smith"
user.age = 30

puts user.inspect
#=> #<User:0x423270c @name="John Smith", @age=30>
puts user.to_yaml
#=> --- !ruby/object:User
#=> age: 30
#=> name: John Smith

Hope that helps.

How do I restrict an input to only accept numbers?

There are a few ways to do this.

You could use type="number":

<input type="number" />

Alternatively - I created a reuseable directive for this that uses a regular expression.

Html

<div ng-app="myawesomeapp">
    test: <input restrict-input="^[0-9-]*$" maxlength="20" type="text" class="test" />
</div>

Javascript

;(function(){
    var app = angular.module('myawesomeapp',[])
    .directive('restrictInput', [function(){

        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var ele = element[0];
                var regex = RegExp(attrs.restrictInput);
                var value = ele.value;

                ele.addEventListener('keyup',function(e){
                    if (regex.test(ele.value)){
                        value = ele.value;
                    }else{
                        ele.value = value;
                    }
                });
            }
        };
    }]);    
}());

Determine whether a key is present in a dictionary

In terms of bytecode, in saves a LOAD_ATTR and replaces a CALL_FUNCTION with a COMPARE_OP.

>>> dis.dis(indict)
  2           0 LOAD_GLOBAL              0 (name)
              3 LOAD_GLOBAL              1 (d)
              6 COMPARE_OP               6 (in)
              9 POP_TOP             


>>> dis.dis(haskey)
  2           0 LOAD_GLOBAL              0 (d)
              3 LOAD_ATTR                1 (haskey)
              6 LOAD_GLOBAL              2 (name)
              9 CALL_FUNCTION            1
             12 POP_TOP             

My feelings are that in is much more readable and is to be preferred in every case that I can think of.

In terms of performance, the timing reflects the opcode

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "'foo' in d"
 10000000 loops, best of 3: 0.11 usec per loop

$ python -mtimeit -s'd = dict((i, i) for i in range(10000))' "d.has_key('foo')"
  1000000 loops, best of 3: 0.205 usec per loop

in is almost twice as fast.

How to know elastic search installed version from kibana?

If you are logged into your Kibana, you can click on the Management tab and that will show your Kibana version. Alternatively, you can click on the small tube-like icon enter image description here and that will show the version number.

Remove carriage return in Unix

Once more a solution... Because there's always one more:

perl -i -pe 's/\r//' filename

It's nice because it's in place and works in every flavor of unix/linux I've worked with.

How to specify the private SSH-key to use when executing shell command on Git?

if you have directory on your path where you want to sign with a given identifyfile you can specify to use a specific identify file via the .ssh/config file by setting the ControlPath e.g.:

host github.com
  ControlPath ~/Projects/work/**
  HostName github.com
  IdentityFile ~/.ssh/id_work
  User git

Then ssh will use the specified identity file when doing git commands under the given work path.

How to create a unique index on a NULL column?

Pretty sure you can't do that, as it violates the purpose of uniques.

However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html

Hide Text with CSS, Best Practice?

I realize this is an old question, but the Bootstrap framework has a built in class (sr-only) to handle hiding text on everything but screen readers:

<a href="/" class="navbar-brand"><span class="sr-only">Home</span></a>

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.


See also How can I add to List<? extends Number> data structures?

push object into array

I'm not really sure, but you can try some like this:

var pack = function( arr ) {
    var length = arr.length,
        result = {},
        i;

    for ( i = 0; i < length; i++ ) {
        result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
    }

    return result;
};

pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}

Same font except its weight seems different on different browsers

Try text-rendering: geometricPrecision;.

Different from text-rendering: optimizeLegibility;, it takes care of kerning problems when scaling fonts, while the last enables kerning and ligatures.

Node / Express: EADDRINUSE, Address already in use - Kill server

For windows open Task Manager and find node.exe processes. Kill all of them with End Task.

enter image description here

Difference between @Mock and @InjectMocks

@Mock annotation mocks the concerned object.

@InjectMocks annotation allows to inject into the underlying object the different (and relevant) mocks created by @Mock.

Both are complementary.

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

Calling Javascript from a html form

Pretty example by Miquel (#32) should be refilled:

<html>
 <head>
  <script type="text/javascript">
   function handleIt(txt) {   // txt == content of form input
    alert("Entered value: " + txt);
   }
  </script>
 </head>
 <body>
 <!-- javascript function in form action must have a parameter. This 
    parameter contains a value of named input -->
  <form name="myform" action="javascript:handleIt(lastname.value)">  
   <input type="text" name="lastname" id="lastname" maxlength="40"> 
   <input name="Submit"  type="submit" value="Update"/>
  </form>
 </body>
</html>

And the form should have:

<form name="myform" action="javascript:handleIt(lastname.value)"> 

How to embed a video into GitHub README.md?

A good way to do so is to convert the video into a gif using any online mp4 to gif converter. Then,

Step:1 Create a folder in the repository where you can store all the images and videos you want to show.

Step:2 Then copy the link of the video or image in the repository you are trying to show. For example, you want to show the video of the GAME PROCESS from the link: (https://github.com/Faizun-Faria/Thief_Police_Game/blob/main/Preview/GameVideo.gif). You can simply write the following code in your README.md file to show the gif:

![Game Process](https://github.com/Faizun-Faria/Thief_Police_Game/blob/main/Preview/GameVideo.gif)

How to get current local date and time in Kotlin

To get the current Date in Kotlin do this:

val dateNow = Calendar.getInstance().time

In Python, how to check if a string only contains certain characters?

EDIT: Changed the regular expression to exclude A-Z

Regular expression solution is the fastest pure python solution so far

reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True
>>> timeit.Timer("reg.match('jsdlfjdsf12324..3432jsdflsdf')", "import re; reg=re.compile('^[a-z0-9\.]+$')").timeit()
0.70509696006774902

Compared to other solutions:

>>> timeit.Timer("set('jsdlfjdsf12324..3432jsdflsdf') <= allowed", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
3.2119350433349609
>>> timeit.Timer("all(c in allowed for c in 'jsdlfjdsf12324..3432jsdflsdf')", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
6.7066690921783447

If you want to allow empty strings then change it to:

reg=re.compile('^[a-z0-9\.]*$')
>>>reg.match('')
False

Under request I'm going to return the other part of the answer. But please note that the following accept A-Z range.

You can use isalnum

test_str.replace('.', '').isalnum()

>>> 'test123.3'.replace('.', '').isalnum()
True
>>> 'test123-3'.replace('.', '').isalnum()
False

EDIT Using isalnum is much more efficient than the set solution

>>> timeit.Timer("'jsdlfjdsf12324..3432jsdflsdf'.replace('.', '').isalnum()").timeit()
0.63245487213134766

EDIT2 John gave an example where the above doesn't work. I changed the solution to overcome this special case by using encode

test_str.replace('.', '').encode('ascii', 'replace').isalnum()

And it is still almost 3 times faster than the set solution

timeit.Timer("u'ABC\u0131\u0661'.encode('ascii', 'replace').replace('.','').isalnum()", "import string; allowed = set(string.ascii_lowercase + string.digits + '.')").timeit()
1.5719811916351318

In my opinion using regular expressions is the best to solve this problem

How to get Domain name from URL using jquery..?

In a browser

You can leverage the browser's URL parser using an <a> element:

var hostname = $('<a>').prop('href', url).prop('hostname');

or without jQuery:

var a = document.createElement('a');
a.href = url;
var hostname = a.hostname;

(This trick is particularly useful for resolving paths relative to the current page.)

Outside of a browser (and probably more efficiently):

Use the following function:

function get_hostname(url) {
    var m = url.match(/^http:\/\/[^/]+/);
    return m ? m[0] : null;
}

Use it like this:

get_hostname("http://example.com/path");

This will return http://example.com/ as in your example output.

Hostname of the current page

If you are only trying the get the hostname of the current page, use document.location.hostname.

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

I also got this error many times and I solved it. This error will be faced in case of memory management in native side.

Your application is accessing memory outside of its address space. This is most likely an invalid pointer access. SIGSEGV = segmentation fault in native code. Since it is not occurring in Java code you won't see a stack trace with details. However, you may still see some stack trace information in the logcat if you look around a bit after the application process crashes. It will not tell you the line number within the file, but will tell you which object files and addresses were in use in the call chain. From there you can often figure out which area of the code is problematic. You can also setup a gdb native connection to the target process and catch it in the debugger.

How to cut a string after a specific character in unix

You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

Parameter Expansion

...

${parameter#word}

Remove Smallest Prefix Pattern.
The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

In other words, you can write

$var="${var#*:}"

which will remove anything matching *: from $var (i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ## in place of #.

This is all assuming that the part to remove does not contain : (true for IPv4 addresses, but not for IPv6 addresses)

How to resolve git's "not something we can merge" error

As shown in How does "not something we can merge" arise?, this error can arise from a typo in the branch name because you are trying to pull a branch that doesn't exist.

If that is not the problem (as in my case), it is likely that you don't have a local copy of the branch that you want to merge. Git requires local knowledge of both branches in order to merge those branches. You can resolve this by checking out the branch to merge and then going back to the branch you want to merge into.

git checkout branch-name
git checkout master
git merge branch-name

This should work, but if you receive an error saying

error: pathspec 'remote-name/branch-name' did not match any file(s) known to git.

you need to fetch the remote (probably, but not necessarily, "origin") before checking out the branch:

git fetch remote-name

Limit the length of a string with AngularJS

I use nice set of useful filter library "Angular-filter" and one of them called "truncate" is useful too.

https://github.com/a8m/angular-filter#truncate

usage is:

text | truncate: [length]: [suffix]: [preserve-boolean]

How to find if directory exists in Python

Two things

  1. check if the directory exist?
  2. if not, create a directory (optional).
import os
dirpath = "<dirpath>" # Replace the "<dirpath>" with actual directory path.

if os.path.exists(dirpath):
   print("Directory exist")
else: #this is optional if you want to create a directory if doesn't exist.
   os.mkdir(dirpath):
   print("Directory created")

How to ignore conflicts in rpm installs

Try Freshen command:

rpm -Fvh *.rpm

Maximum length for MySQL type text

See for maximum numbers: http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html

TINYBLOB, TINYTEXT       L + 1 bytes, where L < 2^8    (255 Bytes)
BLOB, TEXT               L + 2 bytes, where L < 2^16   (64 Kilobytes)
MEDIUMBLOB, MEDIUMTEXT   L + 3 bytes, where L < 2^24   (16 Megabytes)
LONGBLOB, LONGTEXT       L + 4 bytes, where L < 2^32   (4 Gigabytes)

L is the number of bytes in your text field. So the maximum number of chars for text is 216-1 (using single-byte characters). Means 65 535 chars(using single-byte characters).

UTF-8/MultiByte encoding: using MultiByte encoding each character might consume more than 1 byte of space. For UTF-8 space consumption is between 1 to 4 bytes per char.

Run php function on button click

You are trying to call a javascript function. If you want to call a PHP function, you have to use for example a form:

    <form action="action_page.php">
       First name:<br>
       <input type="text" name="firstname" value="Mickey">
       <br>
       Last name:<br>
       <input type="text" name="lastname" value="Mouse">
       <br><br>
       <input type="submit" value="Submit">
     </form> 

(Original Code from: http://www.w3schools.com/html/html_forms.asp)

So if you want do do a asynchron call, you could use 'Ajax' - and yeah, that's the Javascript-Way. But I think, that my code example is enough for this time :)

Working with $scope.$emit and $scope.$on

The Easiest way :

HTML

  <div ng-app="myApp" ng-controller="myCtrl"> 

        <button ng-click="sendData();"> Send Data </button>

    </div>

JavaScript

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function($scope, $rootScope) {
            function sendData($scope) {
                var arrayData = ['sam','rumona','cubby'];
                $rootScope.$emit('someEvent', arrayData);
            }

        });
        app.controller('yourCtrl', function($scope, $rootScope) {
            $rootScope.$on('someEvent', function(event, data) {
                console.log(data); 
            }); 
        });
    </script>

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :

df[df['a']==1]['b'].sum()

or you can also try :

sum(df[df['a']==1]['b'])

Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Send POST data on redirect with JavaScript/jQuery?

The answers here can be confusing so i will give you a sample code that i am working with.

To start with note that there is no POST parameter to java script windows.location function that you are referring to.

So you have to...

  1. Dynamically make a form with a POST parameter.

  2. Dynamically put a textbox or textboxes with your desired values to post

  3. Invoke the submit form you dynamically created.

And for the example.

     //---------- make sure to link to your jQuery library ----//

<script type="text/javascript" >

    var form = $(document.createElement('form'));
    $(form).attr("action", "test2.php");
    $(form).attr("method", "POST");
    $(form).css("display", "none");

    var input_employee_name = $("<input>")
    .attr("type", "text")
    .attr("name", "employee_name")
    .val("Peter" );
    $(form).append($(input_employee_name));


    var input_salary = $("<input>")
    .attr("type", "text")
    .attr("name", "salary")
    .val("1000" );
    $(form).append($(input_salary));

    form.appendTo( document.body );
    $(form).submit();

</script>

If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.

On test2.php you can get your values thus.

$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];

Needless to say , make sure you sanitize your passed values.

Return outside function error in Python

You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.

How to get the <html> tag HTML with JavaScript / jQuery?

In jQuery:

var html_string = $('html').outerHTML()

In plain Javascript:

var html_string = document.documentElement.outerHTML

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

Customizing Bootstrap CSS template

Use LESS with Bootstrap...

Here are the Bootstrap docs for how to use LESS

(they have moved since previous answers)

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Call the toISOString() method:

var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());

// Output:
//  2010-07-30T15:05:00.000Z

How do I PHP-unserialize a jQuery-serialized form?

In HTML page:

<script>
function insert_tag()
{
    $.ajax({
        url: "aaa.php",
        type: "POST",
        data: {
            ssd: "yes",
            data: $("#form_insert").serialize()
        },
        dataType: "JSON",
        success: function (jsonStr) {
            $("#result1").html(jsonStr['back_message']);
        }
    });
}
</script>

<form id="form_insert">
    <input type="text" name="f1" value="a"/>
    <input type="text" name="f2" value="b"/>
    <input type="text" name="f3" value="c"/>
    <input type="text" name="f4" value="d"/>
    <div onclick="insert_tag();"><b>OK</b></div>
    <div id="result1">...</div>
</form>

on PHP page:

<?php
if(isset($_POST['data']))
{
    parse_str($_POST['data'], $searcharray);
    $data = array(
        "back_message"   => $searcharray['f1']
    );
    echo json_encode($data);
}
?>

on this php code, return f1 field.

round up to 2 decimal places in java?

     double d = 2.34568;
     DecimalFormat f = new DecimalFormat("##.00");
     System.out.println(f.format(d));

Using Application context everywhere?

There are a couple of potential problems with this approach, though in a lot of circumstances (such as your example) it will work well.

In particular you should be careful when dealing with anything that deals with the GUI that requires a Context. For example, if you pass the application Context into the LayoutInflater you will get an Exception. Generally speaking, your approach is excellent: it's good practice to use an Activity's Context within that Activity, and the Application Context when passing a context beyond the scope of an Activity to avoid memory leaks.

Also, as an alternative to your pattern you can use the shortcut of calling getApplicationContext() on a Context object (such as an Activity) to get the Application Context.

How to show row number in Access query like ROW_NUMBER in SQL

One way to do this with MS Access is with a subquery but it does not have anything like the same functionality:

SELECT a.ID, 
       a.AText, 
       (SELECT Count(ID) 
        FROM table1 b WHERE b.ID <= a.ID 
        AND b.AText Like "*a*") AS RowNo
FROM Table1 AS a
WHERE a.AText Like "*a*"
ORDER BY a.ID;

Git merge two local branches

For merging first branch to second one:

on first branch: git merge secondBranch

on second branch: Move to first branch-> git checkout firstBranch-> git merge secondBranch

any tool for java object to object mapping?

I suggest you try JMapper Framework.

It is a Java bean to Java bean mapper, allows you to perform the passage of data dynamically with annotations and / or XML.

With JMapper you can:

  • Create and enrich target objects
  • Apply a specific logic to the mapping
  • Automatically manage the XML file
  • Implement the 1 to N and N to 1 relationships
  • Implement explicit conversions
  • Apply inherited configurations

document.getElementById vs jQuery $()

No, actually the same result would be:

$('#contents')[0] 

jQuery does not know how many results would be returned from the query. What you get back is a special jQuery object which is a collection of all the controls that matched the query.

Part of what makes jQuery so convenient is that MOST methods called on this object that look like they are meant for one control, are actually in a loop called on all the members int he collection

When you use the [0] syntax you take the first element from the inner collection. At this point you get a DOM object

How to overplot a line on a scatter plot in python?

I'm partial to scikits.statsmodels. Here an example:

import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1

results = sm.OLS(Y,sm.add_constant(X)).fit()

print results.summary()

plt.scatter(X,Y)

X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

plt.show()

The only tricky part is sm.add_constant(X) which adds a columns of ones to X in order to get an intercept term.

     Summary of Regression Results
=======================================
| Dependent Variable:            ['y']|
| Model:                           OLS|
| Method:                Least Squares|
| Date:               Sat, 28 Sep 2013|
| Time:                       09:22:59|
| # obs:                         100.0|
| Df residuals:                   98.0|
| Df model:                        1.0|
==============================================================================
|                   coefficient     std. error    t-statistic          prob. |
------------------------------------------------------------------------------
| x1                      1.007       0.008466       118.9032         0.0000 |
| const                 0.05165       0.005138        10.0515         0.0000 |
==============================================================================
|                          Models stats                      Residual stats  |
------------------------------------------------------------------------------
| R-squared:                     0.9931   Durbin-Watson:              1.484  |
| Adjusted R-squared:            0.9930   Omnibus:                    12.16  |
| F-statistic:                1.414e+04   Prob(Omnibus):           0.002294  |
| Prob (F-statistic):        9.137e-108   JB:                        0.6818  |
| Log likelihood:                 223.8   Prob(JB):                  0.7111  |
| AIC criterion:                 -443.7   Skew:                     -0.2064  |
| BIC criterion:                 -438.5   Kurtosis:                   2.048  |
------------------------------------------------------------------------------

example plot

TabLayout tab selection

If it so happens that your default tab is the first one(0) and you happen to switch to a fragment, then you must manually replace the fragment for the first time. This is because the tab is selected before the listener gets registered.

private TabLayout mTabLayout;

...

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_tablayout, container, false);
    mTabLayout = view.findViewById(R.id.sliding_tabs);
    mTabLayout.addOnTabSelectedListener(mOnTabSelectedListener);

    getActivity().getSupportFragmentManager().beginTransaction()
        .replace(R.id.tabContent, MyFirstFragment.newInstance()).commit();
    return view;
}

Alternatively, you can consider calling getTabAt(0).select() and overriding onTabReselected like so:

@Override
public void onTabReselected(TabLayout.Tab tab) {
    // Replace the corresponding tab fragment.
}

This would work because you are essentially replacing the fragment on every tab reselect.

Why do I always get the same sequence of random numbers with rand()?

rand() returns pseudo-random numbers. It generates numbers based on a given algorithm. The starting point of that algorithm is always the same, so you'll see the same sequence generated for each invocation. This is handy when you need to verify the behavior and consistency of your program.

You can set the "seed" of the random generator with the srand function(only call srand once in a program) One common way to get different sequences from the rand() generator is to set the seed to the current time or the id of the process:

srand(time(NULL)); or srand(getpid()); at the start of the program.

Generating real randomness is very very hard for a computer, but for practical non-crypto related work, an algorithm that tries to evenly distribute the generated sequences works fine.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

You need to put your directory structure in your project directory. And then click "Show All Files" icon in the top of Solution Explorer toolbox. After that, the added directory will be shown up. You will then need to select this directory, right click, and choose "Include in Project."

How to set default value for HTML select?

You could use...

<option <?= ($temp == $value) ? "SELECTED" : "" ?> >$value</opton>

Edit: I thought I was looking at PHP questions... Sorry.

How can I install Visual Studio Code extensions offline?

As of today the download URL for the latest version of the extension is embedded verbatim in the source of the page on Marketplace, e.g. source at URL:

https://marketplace.visualstudio.com/items?itemName=lukasz-wronski.ftp-sync

contains string:

https://lukasz-wronski.gallerycdn.vsassets.io/extensions/lukasz-wronski/ftp-sync/0.3.3/1492669004156/Microsoft.VisualStudio.Services.VSIXPackage

I use following Python regexp to extract dl URL:

urlre = re.search(r'source.+(http.+Microsoft\.VisualStudio\.Services\.VSIXPackage)', content)
if urlre:
    return urlre.group(1)

How to Create simple drag and Drop in angularjs

Using HTML 5 Drag and Drop
You can easily archive this using HTML 5 drag and drop feature along with angular directives.

  1. Enable drag by setting draggable = true.
  2. Add directives for parent container and child items.
  3. Override drag and drop functions - 'ondragstart' for parent and 'ondrop' for child.

Find the example below in which list is array of items.
HTML code:

    <div class="item_content" ng-repeat="item in list" draggrble-container>
        <div class="item" draggable-item draggable="true">{{item}}</div>
    </div>

Javascript:

    module.directive("draggableItem",function(){
     return {
      link:function(scope,elem,attr){
        elem[0].ondragstart = function(event){
            scope.$parent.selectedItem = scope.item;
        };
      }
     };
    });


    module.directive("draggrbleContainer",function(){
     return {
        link:function(scope,elem,attr){
            elem[0].ondrop = function(event){
                event.preventDefault();
                let selectedIndex = scope.list.indexOf(scope.$parent.selectedItem);
                let newPosition = scope.list.indexOf(scope.item);
                scope.$parent.list.splice(selectedIndex,1);
                scope.$parent.list.splice(newPosition,0,scope.$parent.selectedItem);
                scope.$apply();
            };
            elem[0].ondragover = function(event){
                event.preventDefault();

            };
        }
     };
    });

Find the complete code here https://github.com/raghavendrarai/SimpleDragAndDrop

Extract hostname name from string

This is not a full answer, but the below code should help you:

function myFunction() {
    var str = "https://www.123rf.com/photo_10965738_lots-oop.html";
    matches = str.split('/');
    return matches[2];
}

I would like some one to create code faster than mine. It help to improve my-self also.

Make view 80% width of parent in React Native

You can also try react-native-extended-stylesheet that supports percentage for single-orientation apps:

import EStyleSheet from 'react-native-extended-stylesheet';

const styles = EStyleSheet.create({
  column: {
    width: '80%',
    height: '50%',
    marginLeft: '10%'
  }
});

Can Powershell Run Commands in Parallel?

This has been answered thoroughly. Just want to post this method i have created based on Powershell-Jobs as a reference.

Jobs are passed on as a list of script-blocks. They can be parameterized. Output of the jobs is color-coded and prefixed with a job-index (just like in a vs-build-process, as this will be used in a build) Can be used to startup multiple servers at a time or running build steps in parallel or so..

function Start-Parallel {
    param(
        [ScriptBlock[]]
        [Parameter(Position = 0)]
        $ScriptBlock,

        [Object[]]
        [Alias("arguments")]
        $parameters
    )

    $jobs = $ScriptBlock | ForEach-Object { Start-Job -ScriptBlock $_ -ArgumentList $parameters }
    $colors = "Blue", "Red", "Cyan", "Green", "Magenta"
    $colorCount = $colors.Length

    try {
        while (($jobs | Where-Object { $_.State -ieq "running" } | Measure-Object).Count -gt 0) {
            $jobs | ForEach-Object { $i = 1 } {
                $fgColor = $colors[($i - 1) % $colorCount]
                $out = $_ | Receive-Job
                $out = $out -split [System.Environment]::NewLine
                $out | ForEach-Object {
                    Write-Host "$i> "-NoNewline -ForegroundColor $fgColor
                    Write-Host $_
                }
                
                $i++
            }
        }
    } finally {
        Write-Host "Stopping Parallel Jobs ..." -NoNewline
        $jobs | Stop-Job
        $jobs | Remove-Job -Force
        Write-Host " done."
    }
}

sample output:

sample output

how to count the spaces in a java string?

Here's a different way of looking at it, and it's a simple one-liner:

int spaces = s.replaceAll("[^ ]", "").length();

This works by effectively removing all non-spaces then taking the length of what’s left (the spaces).

You might want to add a null check:

int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();

Java 8 update

You can use a stream too:

int spaces = s.chars().filter(c -> c == (int)' ').count();

How can I use a local image as the base image with a dockerfile?

You can use it without doing anything special. If you have a local image called blah you can do FROM blah. If you do FROM blah in your Dockerfile, but don't have a local image called blah, then Docker will try to pull it from the registry.

In other words, if a Dockerfile does FROM ubuntu, but you have a local image called ubuntu different from the official one, your image will override it.

How to filter keys of an object with lodash?

Lodash has a _.pickBy function which does exactly what you're looking for.

_x000D_
_x000D_
var thing = {_x000D_
  "a": 123,_x000D_
  "b": 456,_x000D_
  "abc": 6789_x000D_
};_x000D_
_x000D_
var result = _.pickBy(thing, function(value, key) {_x000D_
  return _.startsWith(key, "a");_x000D_
});_x000D_
_x000D_
console.log(result.abc) // 6789_x000D_
console.log(result.b)   // undefined
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

Creating a JSON dynamically with each input value using jquery

I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];
$("input[class=email]").each(function() {
    array.push({
        title: $(this).attr("title"),
        email: $(this).val()
    });
});
// then to get the JSON string
var jsonString = JSON.stringify(array);

Suppress console output in PowerShell

Try redirecting the output like this:

$key = & 'gpg' --decrypt "secret.gpg" --quiet --no-verbose >$null 2>&1

Tips for debugging .htaccess rewrite rules

Some mistakes I observed happens when writing .htaccess

Using of ^(.*)$ repetitively in multiple rules, using ^(.*)$ causes other rules to be impotent in most cases, because it matches all of the url in single hit.

So, if we are using rule for this url sapmle/url it will also consume this url sapmle/url/string.


[L] flag should be used to ensure our rule has done processing.


Should know about:

Difference in %n and $n

%n is matched during %{RewriteCond} part and $n is matches on %{RewriteRule} part.

Working of RewriteBase

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.

This directive is required when you use a relative path in a substitution in per-directory (htaccess) context unless any of the following conditions are true:

The original request, and the substitution, are underneath the DocumentRoot (as opposed to reachable by other means, such as Alias). The filesystem path to the directory containing the RewriteRule, suffixed by the relative substitution is also valid as a URL path on the server (this is rare). In Apache HTTP Server 2.4.16 and later, this directive may be omitted when the request is mapped via Alias or mod_userdir.

Best way to get identity of inserted row?

I'm saying the same thing as the other guys, so everyone's correct, I'm just trying to make it more clear.

@@IDENTITY returns the id of the last thing that was inserted by your client's connection to the database.
Most of the time this works fine, but sometimes a trigger will go and insert a new row that you don't know about, and you'll get the ID from this new row, instead of the one you want

SCOPE_IDENTITY() solves this problem. It returns the id of the last thing that you inserted in the SQL code you sent to the database. If triggers go and create extra rows, they won't cause the wrong value to get returned. Hooray

IDENT_CURRENT returns the last ID that was inserted by anyone. If some other app happens to insert another row at an unforunate time, you'll get the ID of that row instead of your one.

If you want to play it safe, always use SCOPE_IDENTITY(). If you stick with @@IDENTITY and someone decides to add a trigger later on, all your code will break.

Can attributes be added dynamically in C#?

I tried very hard with System.ComponentModel.TypeDescriptor without success. That does not means it can't work but I would like to see code for that.

In counter part, I wanted to change some Attribute values. I did 2 functions which work fine for that purpose.

        // ************************************************************************
        public static void SetObjectPropertyDescription(this Type typeOfObject, string propertyName,  string description)
        {
            PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
            var att = pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
            if (att != null)
            {
                var fieldDescription = att.GetType().GetField("description", BindingFlags.NonPublic | BindingFlags.Instance);
                if (fieldDescription != null)
                {
                    fieldDescription.SetValue(att, description);
                }
            }
        }

        // ************************************************************************
        public static void SetPropertyAttributReadOnly(this Type typeOfObject, string propertyName, bool isReadOnly)
        {
            PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
            var att = pd.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
            if (att != null)
            {
                var fieldDescription = att.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
                if (fieldDescription != null)
                {
                    fieldDescription.SetValue(att, isReadOnly);
                }
            }
        }

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

Simulate Keypress With jQuery

This works:

var event = jQuery.Event('keypress');
event.which = 13; 
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event); 

Deleting Row in SQLite in Android

Works great!

public void deleteNewMelk(String melkCode) {
    getWritableDatabase().delete(your_table, your_column +"=?", new String[]{melkCode});
}

How to get different colored lines for different plots in a single figure?

Matplot colors your plot with different colors , but incase you wanna put specific colors

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()

How to check sbt version?

run sbt console then type sbtVersion to check sbt version, and scalaVersion for scala version

Add key value pair to all objects in array

@Redu's solution is a good solution

arrOfObj.map(o => o.isActive = true;) but Array.map still counts as looping through all items.

if you absolutely don't want to have any looping here's a dirty hack :

Object.defineProperty(Object.prototype, "isActive",{
  value: true,
  writable: true,
  configurable: true,
  enumerable: true
});

my advice is not to use it carefully though, it will patch absolutely all javascript Objects (Date, Array, Number, String or any other that inherit Object ) which is really bad practice...

Whitespace Matching Regex - Java

Java has evolved since this issue was first brought up. You can match all manner of unicode space characters by using the \p{Zs} group.

Thus if you wanted to replace one or more exotic spaces with a plain space you could do this:

String txt = "whatever my string is";
txt.replaceAll("\\p{Zs}+", " ")

Also worth knowing, if you've used the trim() string function you should take a look at the (relatively new) strip(), stripLeading(), and stripTrailing() functions on strings. The can help you trim off all sorts of squirrely white space characters. For more information on what what space is included, see Java's Character.isWhitespace() function.

Java Security: Illegal key size or default parameters?

There's a short discussion of what appears to be this issue here. The page it links to appears to be gone, but one of the responses might be what you need:

Indeed, copying US_export_policy.jar and local_policy.jar from core/lib/jce to $JAVA_HOME/jre/lib/security helped. Thanks.

VC++ fatal error LNK1168: cannot open filename.exe for writing

I've encountered this problem when the build is abruptly closed before it is loaded. No process would show up in the Task Manager, but if you navigate to the executable generated in the project folder and try to delete it, Windows claims that the application is in use. (If not, just delete the file and rebuild, which generates a new executable) In Windows(Visual Studio 2019), the file is located in this directory by default:

%USERPROFILE%\source\repos\ProjectFolderName\Debug

To end the allegedly running process, open the command prompt and type in the following command:

taskkill /F /IM ApplicationName.exe

This forces any running instance to be terminated. Rebuild and execute!

Iterate a certain number of times without storing the iteration number anywhere

Although I agree completely with delnan's answer, it's not impossible:

loop = range(NUM_ITERATIONS+1)
while loop.pop():
    do_stuff()

Note, however, that this will not work for an arbitrary list: If the first value in the list (the last one popped) does not evaluate to False, you will get another iteration and an exception on the next pass: IndexError: pop from empty list. Also, your list (loop) will be empty after the loop.

Just for curiosity's sake. ;)

List all files from a directory recursively with Java

The more efficient way I found in dealing with millions of folders and files is to capture directory listing through DOS command in some file and parse it. Once you have parsed data then you can do analysis and compute statistics.

Create a variable name with "paste" in R?

See ?assign.

> assign(paste("tra.", 1, sep = ""), 5)
> tra.1
  [1] 5

Reading HTTP headers in a Spring REST controller

The error that you get does not seem to be related to the RequestHeader.

And you seem to be confusing Spring REST services with JAX-RS, your method signature should be something like:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @RequestParam(value = "ID", defaultValue = "") String id) {
    // your code goes here
}

And your REST class should have annotations like:

@Controller
@RequestMapping("/rest/")


Regarding the actual question, another way to get HTTP headers is to insert the HttpServletRequest into your method and then get the desired header from there.

Example:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(HttpServletRequest request, @RequestParam(value = "ID", defaultValue = "") String id) {
    String userAgent = request.getHeader("user-agent");
}

Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)

How to access form methods and controls from a class in C#?

You need access to the object.... you can't simply ask the form class....

eg...

you would of done some thing like

Form1.txtLog.Text = "blah"

instead of

Form1 blah = new Form1();
blah.txtLog.Text = "hello"

add scroll bar to table body

These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.

jQuery.scrollTableBody (GitHub)

As long as you have a table with proper <thead>, <tbody>, and (optional) <tfoot>, all you need to do is this:

$('table').scrollTableBody();

DBCC SHRINKFILE on log file not reducing size even after BACKUP LOG TO DISK

I resolved this problem by taking the full and transactional backup. Sometimes, the backup process is not completed and that's one of the reason the .ldf file is not getting shrink. Try this. It worked for me.

LAST_INSERT_ID() MySQL

This enables you to insert a row into 2 different tables and creates a reference to both tables too.

START TRANSACTION;
INSERT INTO accounttable(account_username) 
    VALUES('AnAccountName');
INSERT INTO profiletable(profile_account_id) 
    VALUES ((SELECT account_id FROM accounttable WHERE account_username='AnAccountName'));
    SET @profile_id = LAST_INSERT_ID(); 
UPDATE accounttable SET `account_profile_id` = @profile_id;
COMMIT;

jQuery select all except first

Because of the way jQuery selectors are evaluated right-to-left, the quite readable li:not(:first) is slowed down by that evaluation.

An equally fast and easy to read solution is using the function version .not(":first"):

e.g.

$("li").not(":first").hide();

JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

This is only few percentage points slower than slice(1), but is very readable as "I want all except the first one".

What is the difference between Python and IPython?

IPython is basically the "recommended" Python shell, which provides extra features. There is no language called IPython.

Parsing JSON in Java without knowing JSON format

Find the following code for Unknown Json Object parsing using Gson library.

public class JsonParsing {
static JsonParser parser = new JsonParser();

public static HashMap<String, Object> createHashMapFromJsonString(String json) {

    JsonObject object = (JsonObject) parser.parse(json);
    Set<Map.Entry<String, JsonElement>> set = object.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
    HashMap<String, Object> map = new HashMap<String, Object>();

    while (iterator.hasNext()) {

        Map.Entry<String, JsonElement> entry = iterator.next();
        String key = entry.getKey();
        JsonElement value = entry.getValue();

        if (null != value) {
            if (!value.isJsonPrimitive()) {
                if (value.isJsonObject()) {

                    map.put(key, createHashMapFromJsonString(value.toString()));
                } else if (value.isJsonArray() && value.toString().contains(":")) {

                    List<HashMap<String, Object>> list = new ArrayList<>();
                    JsonArray array = value.getAsJsonArray();
                    if (null != array) {
                        for (JsonElement element : array) {
                            list.add(createHashMapFromJsonString(element.toString()));
                        }
                        map.put(key, list);
                    }
                } else if (value.isJsonArray() && !value.toString().contains(":")) {
                    map.put(key, value.getAsJsonArray());
                }
            } else {
                map.put(key, value.getAsString());
            }
        }
    }
    return map;
}
}

get string from right hand side

I Had the same problem. This worked for me:

 CASE WHEN length(sp.tele_phone_number) = 10 THEN
                   SUBSTR(sp.tele_phone_number,4)

Difference between signed / unsigned char

This because a char is stored at all effects as a 8-bit number. Speaking about a negative or positive char doesn't make sense if you consider it an ASCII code (which can be just signed*) but makes sense if you use that char to store a number, which could be in range 0-255 or in -128..127 according to the 2-complement representation.

*: it can be also unsigned, it actually depends on the implementation I think, in that case you will have access to extended ASCII charset provided by the encoding used

Evaluate expression given as a string

Nowadays you can also use lazy_eval function from lazyeval package.

> lazyeval::lazy_eval("5+5")
[1] 10

Constructor in an Interface?

A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.

Or in code:

interface Named { Named(String name); }
interface HasList { HasList(List list); }

class A implements Named, HasList {

  /** implements Named constructor.
   * This constructor should not be used from outside, 
   * because List parameter is missing
   */
  public A(String name)  { 
    ...
  }

  /** implements HasList constructor.
   * This constructor should not be used from outside, 
   * because String parameter is missing
   */
  public A(List list) {
    ...
  }

  /** This is the constructor that we would actually 
   * need to satisfy both interfaces at the same time
   */ 
  public A(String name, List list) {
    this(name);
    // the next line is illegal; you can only call one other super constructor
    this(list); 
  }
}

Nexus 7 (2013) and Win 7 64 - cannot install USB driver despite checking many forums and online resources

SkipSoft.net has some great toolkits. I ran into a similar problem with my Galaxy Nexus.... Ran the corresponding toolkit, which configured my system and downloaded the correct drivers. I then went into Windows Hardware manager after connecting the phone... Windows reported the exclamation that it couldn't find the device driver, so I ran update, and gave it the drivers directory the toolkit had created... and everything started working great. Hope this helps :)

How do I clear inner HTML

The h1 tags unfortunately do not receive the onmouseout events.

The simple Javascript snippet below will work for all elements and uses only 1 mouse event.

Note: "The borders in the snippet are applied to provide a visual demarcation of the elements."

_x000D_
_x000D_
document.body.onmousemove = function(){ move("The dog is in its shed"); };_x000D_
_x000D_
document.body.style.border = "2px solid red";_x000D_
document.getElementById("h1Tag").style.border = "2px solid blue";_x000D_
_x000D_
function move(what) {_x000D_
    if(event.target.id == "h1Tag"){ document.getElementById("goy").innerHTML = "what"; } else { document.getElementById("goy").innerHTML = ""; }_x000D_
}
_x000D_
<h1 id="h1Tag">lalala</h1>_x000D_
<div id="goy"></div>
_x000D_
_x000D_
_x000D_

This can also be done in pure CSS by adding the hover selector css property to the h1 tag.

Check if any type of files exist in a directory using BATCH script

For files in a directory, you can use things like:

if exist *.csv echo "csv file found"

or

if not exist *.csv goto nofile

jquery: get id from class selector

When you add a click event, this returns the element that has been clicked. So you can just use this.id;

$(".test").click(function(){
   alert(this.id); 
});

Example: http://jsfiddle.net/jonathon/rfbrp/

Maximum number of rows of CSV data in excel sheet

In my memory, excel (versions >= 2007) limits the power 2 of 20: 1.048.576 lines.

Csv is over to this boundary, like ordinary text file. So you will be care of the transfer between two formats.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Use a URL to link to a Google map with a marker on it

This URL format worked like a charm:

http://maps.google.com/maps?&z={INSERT_MAP_ZOOM}&mrt={INSERT_TYPE_OF_SEARCH}&t={INSERT_MAP_TYPE}&q={INSERT_MAP_LAT_COORDINATES}+{INSERT_MAP_LONG_COORDINATES}

Example for Mount Everest:

http://maps.google.com/maps?&z=15&mrt=yp&t=k&q=27.9879012+86.9253141

Preview

Full reference here:

https://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

-- EDIT --

Apparently the zoom parameter stopped working, here's the updated format.

Format

https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&center={LAT},{LONG}&zoom={ZOOM}

Example

https://www.google.com/maps/@?api=1&map_action=map&basemap=satellite&center=27.9879012,86.9253141&zoom=14

Push git commits & tags simultaneously

@since Git 2.4

git push --atomic origin <branch name> <tag>

Setting network adapter metric priority in Windows 7

I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.

Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.

After this, Windows started prioritize Ethernet adapter.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I ran into this where the scripts would load once, but repeat calls would not run the script.

It turned out to be an issue with using .html() to display a wait indicator and then chaining .load() after it.

// Processes scripts as expected once per page load, but not for repeat calls
$("#id").html("<img src=wait.gif>").load("page.html");

When I made them separate calls, my inline scripts loaded every time as expected.

// Without chaining html and load together, scripts are processed as expected every time
$("#id").html("<img src=wait.gif>");
$("#id").load("page.html");

For further research, note that there are two versions of .load()

A simple .load() call (without a selector after the url) is simply a shorthand for calling $.ajax() with dataType:"html" and taking the return contents and calling .html() to put those contents in the DOM. And the documentation for dataType:"html" clearly states "included script tags are evaluated when inserted in the DOM." http://api.jquery.com/jquery.ajax/ So .load() officially runs inline scripts.

A complex .load() call has a selector such as load("page.html #content"). When used that way, jQuery purposefully filters out script tags as discussed in articles like this one: https://forum.jquery.com/topic/the-load-function-and-script-blocks#14737000000752785 In this case the scripts never run, not even once.

JPanel Padding in Java

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

Cannot execute RUN mkdir in a Dockerfile

When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p flag to mkdir ... Please update your Dockerfile with

RUN mkdir -p ... 

I tested this and it's correct.

How to change the color of a CheckBox?

Programmatic version:

int states[][] = {{android.R.attr.state_checked}, {}};
int colors[] = {color_for_state_checked, color_for_state_normal}
CompoundButtonCompat.setButtonTintList(checkbox, new ColorStateList(states, colors));

How can I set the current working directory to the directory of the script in Bash?

I take this and it works.

#!/bin/bash
cd "$(dirname "$0")"
CUR_DIR=$(pwd)

Fixing broken UTF-8 encoding

This script had a nice approach. Converting it to the language of your choice should not be too difficult:

http://plasmasturm.org/log/416/

#!/usr/bin/perl
use strict;
use warnings;

use Encode qw( decode FB_QUIET );

binmode STDIN, ':bytes';
binmode STDOUT, ':encoding(UTF-8)';

my $out;

while ( <> ) {
  $out = '';
  while ( length ) {
    # consume input string up to the first UTF-8 decode error
    $out .= decode( "utf-8", $_, FB_QUIET );
    # consume one character; all octets are valid Latin-1
    $out .= decode( "iso-8859-1", substr( $_, 0, 1 ), FB_QUIET ) if length;
  }
  print $out;
}

Clearing my form inputs after submission

Your form is being submitted already as your button is type submit. Which in most browsers would result in a form submission and loading of the server response rather than executing javascript on the page.

Change the type of the submit button to a button. Also, as this button is given the id submit, it will cause a conflict with Javascript's submit function. Change the id of this button. Try something like

<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">

Another issue in this instance is that the name of the form contains a - dash. However, Javascript translates - as a minus.

You will need to either use array based notation or use document.getElementById() / document.getElementsByName(). The getElementById() function returns the element instance directly as Id is unique (but it requires an Id to be set). The getElementsByName() returns an array of values that have the same name. In this instance as we have not set an id, we can use the getElementsByName with index 0.

Try the following

function submitForm() {
   // Get the first form with the name
   // Usually the form name is not repeated
   // but duplicate names are possible in HTML
   // Therefore to work around the issue, enforce the correct index
   var frm = document.getElementsByName('contact-form')[0];
   frm.submit(); // Submit the form
   frm.reset();  // Reset all form data
   return false; // Prevent page refresh
}

Disable Transaction Log

SQL Server requires a transaction log in order to function.

That said there are two modes of operation for the transaction log:

  • Simple
  • Full

In Full mode the transaction log keeps growing until you back up the database. In Simple mode: space in the transaction log is 'recycled' every Checkpoint.

Very few people have a need to run their databases in the Full recovery model. The only point in using the Full model is if you want to backup the database multiple times per day, and backing up the whole database takes too long - so you just backup the transaction log.

The transaction log keeps growing all day, and you keep backing just it up. That night you do your full backup, and SQL Server then truncates the transaction log, begins to reuse the space allocated in the transaction log file.

If you only ever do full database backups, you don't want the Full recovery mode.

How can I get two form fields side-by-side, with each field’s label above the field, in CSS?

How about something like this?

<div id="leftContainer">
  <span>Company Name</span>
  <br><input type="text" value="John Lewis Partnership">
</div>
<div id="rightContainer">
  <span>Contact Name</span>
  <br><input type="text" value="Timothy Patten">
</div>

Then, you can align the 2 divs by floating them left and right:-

#leftContainer {
   float:left;
}

#rightContainer {
   float:right;
}

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

How can I decrypt MySQL passwords

With luck, if the original developer was any good, you will not be able to get the plain text out. I say "luck" otherwise you probably have an insecure system.

For the admin passwords, as you have the code, you should be able to create hashed passwords from a known plain text such that you can take control of the application. Follow the algorithm used by the original developer.

If they were not salted and hashed, then make sure you do apply this as 'best practice'

Importing PNG files into Numpy?

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead.

Example:

import imageio

im = imageio.imread('my_image.png')
print(im.shape)

You can also use imageio to load from fancy sources:

im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

Edit:

To load all of the *.png files in a specific folder, you could use the glob package:

import imageio
import glob

for im_path in glob.glob("path/to/folder/*.png"):
     im = imageio.imread(im_path)
     print(im.shape)
     # do whatever with the image here

'python' is not recognized as an internal or external command

You need to add that folder to your Windows Path:

https://docs.python.org/2/using/windows.html Taken from this question.

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

I tried this and things got weird for me. (css stopped working after the :after {content: "";} part of this tutorial. I found you can color the bullets by just using color:#ddd; on the li item itself.

Here's an example.

li{
    color:#ff0000;    
    list-style:square;                
}
a {
    text-decoration: none;
    color:#00ff00;
}

a:hover {
    background-color: #ddd;
}

Make button width fit to the text

Remove the width and display: block and then add display: inline-block to the button. To have it remain centered you can either add text-align: center; on the body or do the same on a newly created container.

The advantage of this approach (as opossed to centering with auto margins) is that the button will remain centered regardless of how much text it has.

Example: http://cssdeck.com/labs/2u4kf6dv

Using set_facts and with_items together in Ansible

There is a workaround which may help. You may "register" results for each set_fact iteration and then map that results to list:

---
- hosts: localhost
  tasks:
  - name: set fact
    set_fact: foo_item="{{ item }}"
    with_items:
      - four
      - five
      - six
    register: foo_result

  - name: make a list
    set_fact: foo="{{ foo_result.results | map(attribute='ansible_facts.foo_item') | list }}"

  - debug: var=foo

Output:

< TASK: debug var=foo >
 ---------------------
    \   ^__^
     \  (oo)\_______
        (__)\       )\/\
            ||----w |
            ||     ||


ok: [localhost] => {
    "var": {
        "foo": [
            "four", 
            "five", 
            "six"
        ]
    }
}

How to configure XAMPP to send mail from localhost?

You have to configure SMTP on your server. You can use G Suite SMTP by Google for free:

<?php

$mail = new PHPMailer(true);

// Send mail using Gmail
if($send_using_gmail){
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->SMTPAuth = true; // enable SMTP authentication
    $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
    $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
    $mail->Port = 465; // set the SMTP port for the GMAIL server
    $mail->Username = "[email protected]"; // GMAIL username
    $mail->Password = "your-gmail-password"; // GMAIL password
}

// Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $name_from);
$mail->Subject = "My Subject";
$mail->Body = "Mail contents";

try{
    $mail->Send();
    echo "Success!";
} catch(Exception $e){
    // Something went bad
    echo "Fail :(";
}

?>

Read more about PHPMailer here.

Insert a new row into DataTable

// get the data table
DataTable dt = ...;

// generate the data you want to insert
DataRow toInsert = dt.NewRow();

// insert in the desired place
dt.Rows.InsertAt(toInsert, index);

Laravel Eloquent Sum of relation's column

you can do it using eloquent easily like this

$sum = Model::sum('sum_field');

its will return a sum of fields, if apply condition on it that is also simple

$sum = Model::where('status', 'paid')->sum('sum_field');

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Laravel Checking If a Record Exists

It depends if you want to work with the user afterwards or only check if one exists.

If you want to use the user object if it exists:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

And if you only want to check

if (User::where('email', '=', Input::get('email'))->count() > 0) {
   // user found
}

Or even nicer

if (User::where('email', '=', Input::get('email'))->exists()) {
   // user found
}

How to execute an Oracle stored procedure via a database link

The syntax is

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

How do I output lists as a table in Jupyter notebook?

A general purpose set of functions to render any python data structure (dicts and lists nested together) as HTML.

from IPython.display import HTML, display

def _render_list_html(l):
    o = []
    for e in l:
        o.append('<li>%s</li>' % _render_as_html(e))
    return '<ol>%s</ol>' % ''.join(o)

def _render_dict_html(d):
    o = []
    for k, v in d.items():
        o.append('<tr><td>%s</td><td>%s</td></tr>' % (str(k), _render_as_html(v)))
    return '<table>%s</table>' % ''.join(o)

def _render_as_html(e):
    o = []
    if isinstance(e, list):
        o.append(_render_list_html(e))
    elif isinstance(e, dict):
        o.append(_render_dict_html(e))
    else:
        o.append(str(e))
    return '<html><body>%s</body></html>' % ''.join(o)

def render_as_html(e):
    display(HTML(_render_as_html(e)))

Disable scrolling when touch moving certain element

Note: As pointed out in the comments by @nevf, this solution may no longer work (at least in Chrome) due to performance changes. The recommendation is to use touch-action which is also suggested by @JohnWeisz's answer.

Similar to the answer given by @Llepwryd, I used a combination of ontouchstart and ontouchmove to prevent scrolling when it is on a certain element.

Taken as-is from a project of mine:

window.blockMenuHeaderScroll = false;
$(window).on('touchstart', function(e)
{
    if ($(e.target).closest('#mobileMenuHeader').length == 1)
    {
        blockMenuHeaderScroll = true;
    }
});
$(window).on('touchend', function()
{
    blockMenuHeaderScroll = false;
});
$(window).on('touchmove', function(e)
{
    if (blockMenuHeaderScroll)
    {
        e.preventDefault();
    }
});

Essentially, what I am doing is listening on the touch start to see whether it begins on an element that is a child of another using jQuery .closest and allowing that to turn on/off the touch movement doing scrolling. The e.target refers to the element that the touch start begins with.

You want to prevent the default on the touch move event however you also need to clear your flag for this at the end of the touch event otherwise no touch scroll events will work.

This can be accomplished without jQuery however for my usage, I already had jQuery and didn't need to code something up to find whether the element has a particular parent.

Tested in Chrome on Android and an iPod Touch as of 2013-06-18

How to insert spaces/tabs in text using HTML/CSS

Alternatively referred to as a fixed space or hard space, non-breaking space (NBSP) is used in programming and word processing to create a space in a line that cannot be broken by word wrap.

With HTML, &nbsp; allows you to create multiple spaces that are visible on a web page and not only in the source code.

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.

exception in thread 'main' java.lang.NoClassDefFoundError:

Run it like this:

java -jar HelloWorld.jar

Difference between DOM parentNode and parentElement

Use .parentElement and you can't go wrong as long as you aren't using document fragments.

If you use document fragments, then you need .parentNode:

let div = document.createDocumentFragment().appendChild(document.createElement('div'));
div.parentElement // null
div.parentNode // document fragment

Also:

_x000D_
_x000D_
let div = document.getElementById('t').content.firstChild_x000D_
div.parentElement // null_x000D_
div.parentNode // document fragment
_x000D_
<template id="t"><div></div></template>
_x000D_
_x000D_
_x000D_


Apparently the <html>'s .parentNode links to the Document. This should be considered a decision phail as documents aren't nodes since nodes are defined to be containable by documents and documents can't be contained by documents.

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Removing duplicate rows in Notepad++

Since Notepad++ Version 6 you can use this regex in the search and replace dialogue:

^(.*?)$\s+?^(?=.*^\1$)

and replace with nothing. This leaves from all duplicate rows the last occurrence in the file.

No sorting is needed for that and the duplicate rows can be anywhere in the file!

You need to check the options "Regular expression" and ". matches newline":

Notepad++ Replace dialogue

  • ^ matches the start of the line.

  • (.*?) matches any characters 0 or more times, but as few as possible (It matches exactly on row, this is needed because of the ". matches newline" option). The matched row is stored, because of the brackets around and accessible using \1

  • $ matches the end of the line.

  • \s+?^ this part matches all whitespace characters (newlines!) till the start of the next row ==> This removes the newlines after the matched row, so that no empty row is there after the replacement.

  • (?=.*^\1$) this is a positive lookahead assertion. This is the important part in this regex, a row is only matched (and removed), when there is exactly the same row following somewhere else in the file.

How to close existing connections to a DB

In more recent versions of SQL Server Management studio, you can now right click on a database and 'Take Database Offline'. This gives you the option to Drop All Active Connections to the database.

Expected corresponding JSX closing tag for input Reactjs

You need to close the input element with a /> at the end.

<input id="icon_prefix" type="text" class="validate" />

ReactJS and images in public folder

1- It's good if you use webpack for configurations but you can simply use image path and react will find out that that it's in public directory.

<img src="/image.jpg">

2- If you want to use webpack which is a standard practice in React. You can use these rules in your webpack.config.dev.js file.

module: {
  rules: [
    {
      test: /\.(jpe?g|gif|png|svg)$/i,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        }
      ]
    }
  ],
},

then you can import image file in react components and use it.

import image from '../../public/images/logofooter.png'

<img src={image}/>

Mocking methods of local scope objects with Mockito

The answer from @edutesoy points to the documentation of PowerMockito and mentions constructor mocking as a hint but doesn't mention how to apply that to the current problem in the question.

Here is a solution based on that. Taking the code from the question:

public class MyClass {
    void method1 {
        MyObject obj1 = new MyObject();
        obj1.method1();
    }
}

The following test will create a mock of the MyObject instance class via preparing the class that instantiates it (in this example I am calling it MyClass) with PowerMock and letting PowerMockito to stub the constructor of MyObject class, then letting you stub the MyObject instance method1() call:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
    @Test
    public void testMethod1() {      
        MyObject myObjectMock = mock(MyObject.class);
        when(myObjectMock.method1()).thenReturn(<whatever you want to return>);   
        PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock);
        
        MyClass objectTested = new MyClass();
        objectTested.method1();
        
        ... // your assertions or verification here 
    }
}

With that your internal method1() call will return what you want.

If you like the one-liners you can make the code shorter by creating the mock and the stub inline:

MyObject myObjectMock = when(mock(MyObject.class).method1()).thenReturn(<whatever you want>).getMock();   

Is there a way to specify a default property value in Spring XML?

There is a little known feature, which makes this even better. You can use a configurable default value instead of a hard-coded one, here is an example:

config.properties:

timeout.default=30
timeout.myBean=60

context.xml:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>config.properties</value>
    </property>
</bean>

<bean id="myBean" class="Test">
    <property name="timeout" value="${timeout.myBean:${timeout.default}}" />
</bean>

To use the default while still being able to easily override later, do this in config.properties:

timeout.myBean = ${timeout.default}

Perl - If string contains text?

For case-insensitive string search, use index (or rindex) in combination with fc. This example expands on the answer by Eugene Yarmash:

use feature qw( fc ); 
my $str = "Abc"; 
my $substr = "aB"; 

print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found

$str = "Abc";
$substr = "bA";

print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing

Both index and rindex return -1 if the substring is not found.
And fc returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc or lc. Remember to enable this function, for example with use feature qw( fc );.

Extract matrix column values by matrix column name

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

Can I set text box to readonly when using Html.TextBoxFor?

   @Html.TextBoxFor(model => model.IdUsuario, new { @Value = "" + User.Identity.GetUserId() + "", @disabled = "true" })

@disabled = "true"

Work very well

Drop Down Menu/Text Field in one

Option 1

Include the script from dhtmlgoodies and initialize like this:

<input type="text" name="myText" value="Norway"
       selectBoxOptions="Canada;Denmark;Finland;Germany;Mexico"> 
createEditableSelect(document.forms[0].myText);

Option 2

Here's a custom solution which combines a <select> element and <input> element, styles them, and toggles back and forth via JavaScript

<div style="position:relative;width:200px;height:25px;border:0;padding:0;margin:0;">
  <select style="position:absolute;top:0px;left:0px;width:200px; height:25px;line-height:20px;margin:0;padding:0;"
          onchange="document.getElementById('displayValue').value=this.options[this.selectedIndex].text; document.getElementById('idValue').value=this.options[this.selectedIndex].value;">
    <option></option>
    <option value="one">one</option>
    <option value="two">two</option>
    <option value="three">three</option>
  </select>
  <input type="text" name="displayValue" id="displayValue" 
         placeholder="add/select a value" onfocus="this.select()"
         style="position:absolute;top:0px;left:0px;width:183px;width:180px\9;#width:180px;height:23px; height:21px\9;#height:18px;border:1px solid #556;"  >
  <input name="idValue" id="idValue" type="hidden">
</div>

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

My issue was that it was in my init(). Probably the "weak self" killed him while the init wasn't finished. I moved it from the init and it solved my issue.

curl.h no such file or directory

Instead of downloading curl, down libcurl.

curl is just the application, libcurl is what you need for your C++ program

http://packages.ubuntu.com/quantal/curl

Select single item from a list

Just to complete the answer, If you are using the LINQ syntax, you can just wrap it since it returns an IEnumerable:

(from int x in intList
 where x > 5
 select x * 2).FirstOrDefault()

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Two Things you have to care..

  1. If you using the sub module, you have to import the FormModule in that sub module.

            **imports:[CommonModule,HttpModule,FormsModule]**
    
  2. you have to exports the FormModule in the module

        **exports:[FormsModule],**
    

    so together it looks like imports:[CommonModule,HttpModule,FormsModule], exports:[FormsModule],

  3. in Top u have to import the FormsModule

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


if you are using only the app.module.ts then

no need to export.. only import required

How to Install Font Awesome in Laravel Mix

For Font Awesome 5(webfont with css) and Laravel mixin add package for font awesome 5

npm i --save @fortawesome/fontawesome-free

And import font awesome scss in app.scss or your custom scss file

@import '~@fortawesome/fontawesome-free/scss/brands';
@import '~@fortawesome/fontawesome-free/scss/regular';
@import '~@fortawesome/fontawesome-free/scss/solid';
@import '~@fortawesome/fontawesome-free/scss/fontawesome';

compile your assets npm run dev or npm run production and include your compiled css into layout

How do I remove a specific element from a JSONArray?

i guess you are using Me version, i suggest to add this block of function manually, in your code (JSONArray.java) :

public Object remove(int index) {
    Object o = this.opt(index);
    this.myArrayList.removeElementAt(index);
    return o;
}

In java version they use ArrayList, in ME Version they use Vector.

Open window in JavaScript with HTML inserted

You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open

var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");

Adding the "Clear" Button to an iPhone UITextField

You can also set this directly from Interface Builder under the Attributes Inspector.

enter image description here

Taken from XCode 5.1

Reload chart data via JSON with Highcharts

If you are using push to push the data to the option.series dynamically .. just use

options.series = [];  

to clear it.

options.series = [];
$("#change").click(function(){
}

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Automated way to convert XML files to SQL database?

For Mysql please see the LOAD XML SyntaxDocs.

It should work without any additional XML transformation for the XML you've provided, just specify the format and define the table inside the database firsthand with matching column names:

LOAD XML LOCAL INFILE 'table1.xml'
    INTO TABLE table1
    ROWS IDENTIFIED BY '<table1>';

There is also a related question:

For Postgresql I do not know.

Is it possible that one domain name has multiple corresponding IP addresses?

This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse