Programs & Examples On #Tabbing

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you have multiples docker containers launched, use this

$ docker rm $(docker ps -aq)

It will remove all the current dockers listed in the "ps -aq" command.

Source : aaam on https://github.com/docker/docker/issues/12487

Select2 open dropdown on focus

For me using Select2.full.js Version 4.0.3 none of the above solutions was working the way it should be. So I wrote a combination of the solutions above. First of all I modified Select2.full.js to transfer the internal focus and blur events to jquery events as "Thomas Molnar" did in his answer.

EventRelay.prototype.bind = function (decorated, container, $container) {
    var self = this;
    var relayEvents = [
      'open', 'opening',
      'close', 'closing',
      'select', 'selecting',
      'unselect', 'unselecting',
      'focus', 'blur'
    ];

And then I added the following code to handle focus and blur and focussing the next element

$("#myId").select2(   ...   ).one("select2:focus", select2Focus).on("select2:blur", function ()
{
    var select2 = $(this).data('select2');
    if (select2.isOpen() == false)
    {
        $(this).one("select2:focus", select2Focus);
    }
}).on("select2:close", function ()
{
    setTimeout(function ()
    {
        // Find the next element and set focus on it.
        $(":focus").closest("tr").next("tr").find("select:visible,input:visible").focus();            
    }, 0);
});
function select2Focus()
{
    var select2 = $(this).data('select2');
    setTimeout(function() {
        if (!select2.isOpen()) {
            select2.open();
        }
    }, 0);  
}

How / can I display a console window in Intellij IDEA?

More IntelliJ 13+ Shortcuts for Terminal

Mac OS X:

alt ?F12

cmd ?shift ?A then type Terminal then hit Enter

shift ?shift ?shift ?shift ? then type Terminal then hit Enter

Windows:

altF12 press Enter

ctrlshift ?A start typing Terminal then hit Enter

shift ?shift ? then type Terminal then hit Enter

How can I bind to the change event of a textarea in jQuery?

2018, without JQUERY

The question is with JQuery, it's just FYI.

JS

let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
    yourBtnID.style.display = 'none';
    if (textareaID.value.length) {
        yourBtnID.style.display = 'inline-block';
    }
});

HTML

<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>

How to reposition Chrome Developer Tools

Keyboard shortcut to toggle the docking position (side/bottom)

CTRL+SHIFT+D

And there are many shortcuts you can see them by going to

Settings » Shortcuts, as displayed here:
Settings screenshot

Alternatively, use CTRL + ? to go to the settings, from there one can reach the "Shortcuts" sub-item on the left or use the Official reference.

How to rename array keys in PHP?

foreach ($basearr as &$row)
{
    $row['value'] = $row['url'];
    unset( $row['url'] );
}

unset($row);

Setting up Vim for Python

A very good plugin management system to use. The included vimrc file is good enough for python programming and can be easily configured to your needs. See http://spf13.com/project/spf13-vim/

How do you log all events fired by an element in jQuery?

There is a nice generic way using the .data('events') collection:

function getEventsList($obj) {
    var ev = new Array(),
        events = $obj.data('events'),
        i;
    for(i in events) { ev.push(i); }
    return ev.join(' ');
}

$obj.on(getEventsList($obj), function(e) {
    console.log(e);
});

This logs every event that has been already bound to the element by jQuery the moment this specific event gets fired. This code was pretty damn helpful for me many times.

Btw: If you want to see every possible event being fired on an object use firebug: just right click on the DOM element in html tab and check "Log Events". Every event then gets logged to the console (this is sometimes a bit annoying because it logs every mouse movement...).

Why use pip over easy_install?

As an addition to fuzzyman's reply:

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers - Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.

Dynamically fill in form values with jQuery

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

Making a WinForms TextBox behave like your browser's address bar

The following solution works for me. I added OnKeyDown and OnKeyUp event override to keep the TextBox text always selected.

    public class NumericTextBox : TextBox
{
    private bool _focused;
    protected override void OnGotFocus(EventArgs e)
    {
        base.OnGotFocus(e);
        if (MouseButtons == MouseButtons.None)
        {
            this.SelectAll();
            _focused = true;
        }
    }
    protected override void OnEnter(EventArgs e)
    {
        base.OnEnter(e);
        if (MouseButtons == MouseButtons.None)
        {
            SelectAll();
            _focused = true;
        }
    }

    protected override void OnLeave(EventArgs e)
    {
        base.OnLeave(e);
        _focused = false;
    }

    protected override void OnMouseUp(MouseEventArgs mevent)
    {
        base.OnMouseUp(mevent);
        if (!_focused)
        {
            if (SelectionLength == 0)
                SelectAll();
            _focused = true;
        }
    }

    protected override void OnKeyUp(KeyEventArgs e)
    {
        base.OnKeyUp(e);

        if (SelectionLength == 0)
            SelectAll();
        _focused = true;
    }
    protected override void OnKeyDown(KeyEventArgs e)
    {
       base.OnKeyDown(e);
       if (SelectionLength == 0)
            SelectAll();
        _focused = true;
    }
}

find index of an int in a list

It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:

int index = 0; int i = accounts[index];

How to access SVG elements with Javascript

In case you use jQuery you need to wait for $(window).load, because the embedded SVG document might not be yet loaded at $(document).ready

$(window).load(function () {

    //alert("Document loaded, including graphics and embedded documents (like SVG)");
    var a = document.getElementById("alphasvg");

    //get the inner DOM of alpha.svg
    var svgDoc = a.contentDocument;

    //get the inner element by id
    var delta = svgDoc.getElementById("delta");
    delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});

View not attached to window manager crash

How to reproduce the bug:

  1. Enable this option on your device: Settings -> Developer Options -> Don't keep Activities.
  2. Press Home button while the AsyncTask is executing and the ProgressDialog is showing.

The Android OS will destroy an activity as soon as it is hidden. When onPostExecute is called the Activity will be in "finishing" state and the ProgressDialog will be not attached to Activity.

How to fix it:

  1. Check for the activity state in your onPostExecute method.
  2. Dismiss the ProgressDialog in onDestroy method. Otherwise, android.view.WindowLeaked exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing.

Try this fixed code:

public class YourActivity extends Activity {

    private void showProgressDialog() {
        if (pDialog == null) {
            pDialog = new ProgressDialog(StartActivity.this);
            pDialog.setMessage("Loading. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
        }
        pDialog.show();
    }

    private void dismissProgressDialog() {
        if (pDialog != null && pDialog.isShowing()) {
            pDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        dismissProgressDialog();
        super.onDestroy();
    }

    class LoadAllProducts extends AsyncTask<String, String, String> {

        // Before starting background thread Show Progress Dialog
        @Override
        protected void onPreExecute() {
            showProgressDialog();
        }

        //getting All products from url
        protected String doInBackground(String... args) {
            doMoreStuff("internet");
            return null;
        }

        // After completing background task Dismiss the progress dialog
        protected void onPostExecute(String file_url) {
            if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
                return;
            }
            dismissProgressDialog();
            something(note);
        }
    }
}

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

How to implement a read only property

You can do this:

public int Property { get { ... } private set { ... } }

Error: The 'brew link' step did not complete successfully

the ultimate answer: change the owner of that directory to whoever you are

sudo chown -R `whoami` /usr/local/include

which is also recommended by brew if you run brew doctor

PHP string concatenation

Just use . for concatenating. And you missed out the $personCount increment!

while ($personCount < 10) {
    $result .= $personCount . ' people';
    $personCount++;
}

echo $result;

combining results of two select statements

While it is possible to combine the results, I would advise against doing so.

You have two fundamentally different types of queries that return a different number of rows, a different number of columns and different types of data. It would be best to leave it as it is - two separate queries.

Can you get the number of lines of code from a GitHub repository?

You can run something like

git ls-files | xargs wc -l

which will give you the total count ?

lines of code

Or use this tool ? http://line-count.herokuapp.com/

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

Join a list of items with different types as string in Python

a=[1,2,3]
b=[str(x) for x in a]
print b

above method is the easiest and most general way to convert list into string. another short method is-

a=[1,2,3]
b=map(str,a)
print b

set value of input field by php variable's value

inside the Form, You can use this code. Replace your variable name (i use $variable)

<input type="text" value="<?php echo (isset($variable))?$variable:'';?>">

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

I tried all the above and found them wanting. This is the simplest most flexible solution I could figure out (thanks to all of the above for inspiration).

HTML

<div id="container">
<ul>
    <li>HOME</li>
    <li>ABOUT US</li>
    <li>SERVICES</li>
    <li>PREVIOUS PROJECTS</li>
    <li>TESTIMONIALS</li>
    <li>NEWS</li>
    <li>RESEARCH &amp; DEV</li>
    <li>CONTACT</li>
</ul>
</div>

CSS

div#container{
  width:900px;
  background-color:#eee;
    padding:20px;
}
ul {
    display:table;
    width: 100%;
    margin:0 0;
    -webkit-padding-start:0px; /* reset chrome default */
}
ul li {
    display:table-cell;
    height:30px;
    line-height:30px;
    font-size:12px;    
    padding:20px 10px;
    text-align: center;
    background-color:#999;
    border-right:2px solid #fff;
}
ul li:first-child {
    border-radius:10px 0 0 10px;
}
ul li:last-child {
    border-radius:0 10px 10px 0;
    border-right:0 none;
}

You can drop the first/last child-rounded ends, obviously, but I think they're real purdy (and so does your client ;)

The container width limits the horizontal list, but you can ditch this and just apply an absolute value to the UL if you like.

Fiddle with it, if you like..

http://jsfiddle.net/tobyworth/esehY/1/

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

Value cannot be null. Parameter name: source

I had this one a while back, and the answer isn't necessarily what you'd expect. This error message often crops up when your connection string is wrong.

At a guess, you'll need something like this:

<connectionStrings>
    <add name="hublisherEntities" connectionString="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True" />
        </parameters>
    </defaultConnectionFactory>
</entityFramework>

What's happening is that it's looking for a data source in the wrong place; Entity Framework specifies it slightly differently. If you post your connection string and EF config then we can check.

What does 'git blame' do?

The git blame command annotates lines with information from the revision which last modified the line, and... with Git 2.22 (Q2 2019), will do so faster, because of a performance fix around "git blame", especially in a linear history (which is the norm we should optimize for).

See commit f892014 (02 Apr 2019) by David Kastrup (fedelibre). (Merged by Junio C Hamano -- gitster -- in commit 4d8c4da, 25 Apr 2019)

blame.c: don't drop origin blobs as eagerly

When a parent blob already has chunks queued up for blaming, dropping the blob at the end of one blame step will cause it to get reloaded right away, doubling the amount of I/O and unpacking when processing a linear history.

Keeping such parent blobs in memory seems like a reasonable optimization that should incur additional memory pressure mostly when processing the merges from old branches.

How to get String Array from arrays.xml file

Your array.xml is not right. change it to like this

Here is array.xml file

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string-array name="testArray">  
        <item>first</item>  
        <item>second</item>  
        <item>third</item>  
        <item>fourth</item>  
        <item>fifth</item>  
   </string-array>
</resources>

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

CSS Calc Viewport Units Workaround?

<div>It's working fine.....</div>

div
{
     height: calc(100vh - 8vw);
    background: #000;
    overflow:visible;
    color: red;
}

Check here this css code right now support All browser without Opera

just check this

Live

see Live preview by jsfiddle

See Live preview by codepen.io

sql ORDER BY multiple values in specific order?

@bobflux's answer is great. I would like to extend it by adding a complete query that uses proposed approach.

select tt.id, tt.x_field
from target_table as tt
-- Here we join our target_table with order_table to specify custom ordering.
left join
    (values ('f', 1), ('p', 2), ('i', 3), ('a', 4)) as order_table (x_field, order_num)
    on order_table.x_field = tt.x_field
order by
    order_table.order_num, -- Here we order values by our custom order.
    tt.x_field;            -- Other values can be ordered alphabetically, for example.

Here is complete demo.

Insert new item in array on any position in PHP

Normally, with scalar values:

$elements = array('foo', ...);
array_splice($array, $position, $length, $elements);

To insert a single array element into your array don't forget to wrap the array in an array (as it was a scalar value!):

$element = array('key1'=>'value1');
$elements = array($element);
array_splice($array, $position, $length, $elements);

otherwise all the keys of the array will be added piece by piece.

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

Install the ASP.NET AJAX Control Toolkit

  1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.

  2. Copy the contents of this zip file directly into the bin directory of your web site.

Update web.config

  1. Put this in your web.config under the <controls> section:

    <?xml version="1.0"?>
    <configuration>
        ...
        <system.web>
            ...
            <pages>
                ...
                <controls>
                    ...
                    <add tagPrefix="ajaxtoolkit"
                        namespace="AjaxControlToolkit"
                        assembly="AjaxControlToolKit"/>
                </controls>
            </pages>
            ...
        </system.web>
        ...
    </configuration>
    

Setup Visual Studio

  1. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"

  2. Inside that tab, right-click on the Toolbox and select "Choose Items..."

  3. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.

You can now use the controls in your web sites!

Easiest way to flip a boolean value?

Clearly you need a flexible solution that can support types masquerading as boolean. The following allows for that:

template<typename T>    bool Flip(const T& t);

You can then specialize this for different types that might pretend to be boolean. For example:

template<>  bool Flip<bool>(const bool& b)  { return !b; }
template<>  bool Flip<int>(const int& i)    { return !(i == 0); }

An example of using this construct:

if(Flip(false))  { printf("flipped false\n"); }
if(!Flip(true))  { printf("flipped true\n"); }

if(Flip(0))  { printf("flipped 0\n"); }
if(!Flip(1)) { printf("flipped 1\n"); }

No, I'm not serious.

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

I got a solution!

When resetting root password at step 2), also change the auth plugin to mysql_native_password:

use mysql;
update user set authentication_string=PASSWORD("") where User='root';
update user set plugin="mysql_native_password" where User='root';  # THIS LINE

flush privileges;
quit;

This allowed me to log in successfully!


Full code solution

1. run bash commands

1. first, run these bash commands

sudo /etc/init.d/mysql stop # stop mysql service
sudo mysqld_safe --skip-grant-tables & # start mysql without password
# enter -> go
mysql -uroot # connect to mysql

2. then run mysql commands => copy paste this to cli manually

use mysql; # use mysql table
update user set authentication_string=PASSWORD("") where User='root'; # update password to nothing
update user set plugin="mysql_native_password" where User='root'; # set password resolving to default mechanism for root user

flush privileges;
quit;

3. run more bash commands

sudo /etc/init.d/mysql stop 
sudo /etc/init.d/mysql start # reset mysql
# try login to database, just press enter at password prompt because your password is now blank
mysql -u root -p 

4. Socket issue (from your comments)

When you see a socket error, a community came with 2 possible solutions:

sudo mkdir -p /var/run/mysqld; sudo chown mysql /var/run/mysqld
sudo mysqld_safe --skip-grant-tables &

(thanks to @Cerin)

Or

mkdir -p /var/run/mysqld && chown mysql:mysql /var/run/mysqld  

(thanks to @Peter Dvukhrechensky)


Blind paths and possible edge errors

Use 127.0.0.1 instead of localhost

mysql -uroot # "-hlocalhost" is default

Can lead to "missing file" or slt error.

mysql -uroot -h127.0.0.1

Works better.

Skip the socket issue

I've found many ways to create mysqld.sock file, change access rights or symlink it. It was not the issue after all.

Skip the my.cnf file

The issue also was not there. If you are not sure, this might help you.

How to filter Pandas dataframe using 'in' and 'not in' like in SQL

How to implement 'in' and 'not in' for a pandas DataFrame?

Pandas offers two methods: Series.isin and DataFrame.isin for Series and DataFrames, respectively.


Filter DataFrame Based on ONE Column (also applies to Series)

The most common scenario is applying an isin condition on a specific column to filter rows in a DataFrame.

df = pd.DataFrame({'countries': ['US', 'UK', 'Germany', np.nan, 'China']})
df
  countries
0        US
1        UK
2   Germany
3     China

c1 = ['UK', 'China']             # list
c2 = {'Germany'}                 # set
c3 = pd.Series(['China', 'US'])  # Series
c4 = np.array(['US', 'UK'])      # array

Series.isin accepts various types as inputs. The following are all valid ways of getting what you want:

df['countries'].isin(c1)

0    False
1     True
2    False
3    False
4     True
Name: countries, dtype: bool

# `in` operation
df[df['countries'].isin(c1)]

  countries
1        UK
4     China

# `not in` operation
df[~df['countries'].isin(c1)]

  countries
0        US
2   Germany
3       NaN

# Filter with `set` (tuples work too)
df[df['countries'].isin(c2)]

  countries
2   Germany

# Filter with another Series
df[df['countries'].isin(c3)]

  countries
0        US
4     China

# Filter with array
df[df['countries'].isin(c4)]

  countries
0        US
1        UK

Filter on MANY Columns

Sometimes, you will want to apply an 'in' membership check with some search terms over multiple columns,

df2 = pd.DataFrame({
    'A': ['x', 'y', 'z', 'q'], 'B': ['w', 'a', np.nan, 'x'], 'C': np.arange(4)})
df2

   A    B  C
0  x    w  0
1  y    a  1
2  z  NaN  2
3  q    x  3

c1 = ['x', 'w', 'p']

To apply the isin condition to both columns "A" and "B", use DataFrame.isin:

df2[['A', 'B']].isin(c1)

      A      B
0   True   True
1  False  False
2  False  False
3  False   True

From this, to retain rows where at least one column is True, we can use any along the first axis:

df2[['A', 'B']].isin(c1).any(axis=1)

0     True
1    False
2    False
3     True
dtype: bool

df2[df2[['A', 'B']].isin(c1).any(axis=1)]

   A  B  C
0  x  w  0
3  q  x  3

Note that if you want to search every column, you'd just omit the column selection step and do

df2.isin(c1).any(axis=1)

Similarly, to retain rows where ALL columns are True, use all in the same manner as before.

df2[df2[['A', 'B']].isin(c1).all(axis=1)]

   A  B  C
0  x  w  0

Notable Mentions: numpy.isin, query, list comprehensions (string data)

In addition to the methods described above, you can also use the numpy equivalent: numpy.isin.

# `in` operation
df[np.isin(df['countries'], c1)]

  countries
1        UK
4     China

# `not in` operation
df[np.isin(df['countries'], c1, invert=True)]

  countries
0        US
2   Germany
3       NaN

Why is it worth considering? NumPy functions are usually a bit faster than their pandas equivalents because of lower overhead. Since this is an elementwise operation that does not depend on index alignment, there are very few situations where this method is not an appropriate replacement for pandas' isin.

Pandas routines are usually iterative when working with strings, because string operations are hard to vectorise. There is a lot of evidence to suggest that list comprehensions will be faster here.. We resort to an in check now.

c1_set = set(c1) # Using `in` with `sets` is a constant time operation... 
                 # This doesn't matter for pandas because the implementation differs.
# `in` operation
df[[x in c1_set for x in df['countries']]]

  countries
1        UK
4     China

# `not in` operation
df[[x not in c1_set for x in df['countries']]]

  countries
0        US
2   Germany
3       NaN

It is a lot more unwieldy to specify, however, so don't use it unless you know what you're doing.

Lastly, there's also DataFrame.query which has been covered in this answer. numexpr FTW!

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

Assign width to half available screen width declaratively

If your widget is a Button:

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="2"
    android:orientation="horizontal">
    <Button android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="somebutton"/>

    <TextView android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
</LinearLayout>

I'm assuming you want your widget to take up one half, and another widget to take up the other half. The trick is using a LinearLayout, setting layout_width="fill_parent" on both widgets, and setting layout_weight to the same value on both widgets as well. If there are two widgets, both with the same weight, the LinearLayout will split the width between the two widgets.

Using a remote repository with non-standard port

This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config file and having something like this

Host git_host
HostName git.host.de
User root
Port 4019

then you can have

url = git_host:/var/cache/git/project.git

and you can also ssh git_host and scp git_host ... and everything will work out.

"%%" and "%/%" for the remainder and the quotient

In R, you can assign your own operators using %[characters]%. A trivial example:

'%p%' <- function(x, y){x^2 + y}

2 %p% 3 # result: 7

While I agree with BlueTrin that %% is pretty standard, I have a suspicion %/% may have something to do with the sort of operator definitions I showed above - perhaps it was easier to implement, and makes sense: %/% means do a special sort of division (integer division)

WRONGTYPE Operation against a key holding the wrong kind of value php

I faced this issue when trying to set something to redis. The problem was that I previously used "set" method to set data with a certain key, like

$redis->set('persons', $persons)

Later I decided to change to "hSet" method, and I tried it this way

foreach($persons as $person){
    $redis->hSet('persons', $person->id, $person);
}

Then I got the aforementioned error. So, what I had to do is to go to redis-cli and manually delete "persons" entry with

del persons

It simply couldn't write different data structure under existing key, so I had to delete the entry and hSet then.

ASP.net Repeater get current index, pointer, or counter

To display the item number on the repeater you can use the Container.ItemIndex property.

<asp:repeater id="rptRepeater" runat="server">
    <itemtemplate>
        Item <%# Container.ItemIndex + 1 %>| <%# Eval("Column1") %>
    </itemtemplate>
    <separatortemplate>
        <br />
    </separatortemplate>
</asp:repeater>

How do I delete an entity from symfony2

From what I understand, you struggle with what to put into your template.

I'll show an example:

<ul>
    {% for guest in guests %}
    <li>{{ guest.name }} <a href="{{ path('your_delete_route_name',{'id': guest.id}) }}">[[DELETE]]</a></li>
    {% endfor %}
</ul>

Now what happens is it iterates over every object within guests (you'll have to rename this if your object collection is named otherwise!), shows the name and places the correct link. The route name might be different.

Find duplicate values in R

A terser way, either with rev :

x[!(!duplicated(x) & rev(!duplicated(rev(x))))]

... rather than fromLast:

x[!(!duplicated(x) & !duplicated(x, fromLast = TRUE))]

... and as a helper function to provide either logical vector or elements from original vector :

duplicates <- function(x, as.bool = FALSE) {
    is.dup <- !(!duplicated(x) & rev(!duplicated(rev(x))))
    if (as.bool) { is.dup } else { x[is.dup] }
}

Treating vectors as data frames to pass to table is handy but can get difficult to read, and the data.table solution is fine but I'd prefer base R solutions for dealing with simple vectors like IDs.

Converting string to title case

String TitleCaseString(String s)
{
    if (s == null || s.Length == 0) return s;

    string[] splits = s.Split(' ');

    for (int i = 0; i < splits.Length; i++)
    {
        switch (splits[i].Length)
        {
            case 1:
                break;

            default:
                splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1);
                break;
        }
    }

    return String.Join(" ", splits);
}

How to get all options of a select using jQuery?

$('select#id').find('option').each(function() {
    alert($(this).val());
});

Disable asp.net button after click to prevent double clicking

You can use the client-side onclick event to do that:

yourButton.Attributes.Add("onclick", "this.disabled=true;");

Determine Whether Integer Is Between Two Other Integers?

if number >= 10000 and number <= 30000:
    print ("you have to pay 5% taxes")

Git:nothing added to commit but untracked files present

If you have already tried using the git add . command to add all your untracked files, make sure you're not under a subfolder of your root project.

git add . will stage all your files under the current subfolder.

Is it possible to use jQuery .on and hover?

If you need it to have as a condition in an other event, I solved it this way:

$('.classname').hover(
     function(){$(this).data('hover',true);},
     function(){$(this).data('hover',false);}
);

Then in another event, you can easily use it:

 if ($(this).data('hover')){
      //...
 }

(I see some using is(':hover') to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)

How to check if function exists in JavaScript?

Didn't see this suggested: me.onChange && me.onChange(str);

Basically if me.onChange is undefined (which it will be if it hasn't been initiated) then it won't execute the latter part. If me.onChange is a function, it will execute me.onChange(str).

You can even go further and do:

me && me.onChange && me.onChange(str);

in case me is async as well.

How to inspect FormData?

In certain cases, the use of :

for(var pair of formData.entries(){... 

is impossible.

I've used this code in replacement :

var outputLog = {}, iterator = myFormData.entries(), end = false;
while(end == false) {
   var item = iterator.next();
   if(item.value!=undefined) {
       outputLog[item.value[0]] = item.value[1];
   } else if(item.done==true) {
       end = true;
   }
    }
console.log(outputLog);

It's not a very smart code, but it works...

Hope it's help.

Find the 2nd largest element in an array with minimum number of comparisons

Use counting sort and then find the second largest element, starting from index 0 towards the end. There should be at least 1 comparison, at most n-1 (when there's only one element!).

MySQL select where column is not empty

To check if field is NULL use IS NULL, IS NOT NULL operators.

MySql reference http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

Can I apply multiple background colors with CSS3?

In this LIVE DEMO i've achieved this by using the :before css selector which seems to work quite nicely.

_x000D_
_x000D_
.myDiv  {_x000D_
position: relative; /*Parent MUST be relative*/_x000D_
z-index: 9;_x000D_
background: green;_x000D_
    _x000D_
/*Set width/height of the div in 'parent'*/    _x000D_
width:100px;_x000D_
height:100px;_x000D_
}_x000D_
_x000D_
_x000D_
.myDiv:before {_x000D_
content: "";_x000D_
position: absolute;/*set 'child' to be absolute*/_x000D_
z-index: -1; /*Make this lower so text appears in front*/_x000D_
   _x000D_
    _x000D_
/*You can choose to align it left, right, top or bottom here*/_x000D_
top: 0; _x000D_
right:0;_x000D_
bottom: 60%;_x000D_
left: 0;_x000D_
    _x000D_
    _x000D_
background: red;_x000D_
}
_x000D_
<div class="myDiv">this is my div with multiple colours. It work's with text too!</div>
_x000D_
_x000D_
_x000D_

I thought i would add this as I feel it could work quite well for a percentage bar/visual level of something.

It also means you're not creating multiple divs if you don't have to, and keeps this page up-to-date

Byte Array and Int conversion in Java

You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.

new BigInteger(bytes).intValue();

or to denote polarity:

new BigInteger(1, bytes).intValue();

To get bytes back just:

new BigInteger(bytes).toByteArray()

Convert Rtf to HTML

If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.

Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.

I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.

How can I clear event subscriptions in C#?

You can achieve this by using the Delegate.Remove or Delegate.RemoveAll methods.

Android emulator shows nothing except black screen and adb devices shows "device offline"

Here is how i got it solved : I ran the emulator with following command :

sudo /home/code/Android/Sdk/tools/emulator -avd Nexus_S_API_21 -netspeed full -netdelay none -debug-init -logcat '*:v'

and received the following in the output :

NAND: could not write file /tmp/android-code/TMP7.tmp, No space left on device. (similar error, could not reproduce it)

So, i just freed up some disk space from my /home directory in ubuntu (for windows free the C: drive space) and it then booted smoothly.

SSL peer shut down incorrectly in Java

I was facing same issue, for me adding certificate to trust store solved this issue.

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

How to redirect to a 404 in Rails?

I wanted to throw a 'normal' 404 for any logged in user that isn't an admin, so I ended up writing something like this in Rails 5:

class AdminController < ApplicationController
  before_action :blackhole_admin

  private

  def blackhole_admin
    return if current_user.admin?

    raise ActionController::RoutingError, 'Not Found'
  rescue ActionController::RoutingError
    render file: "#{Rails.root}/public/404", layout: false, status: :not_found
  end
end

Matplotlib: "Unknown projection '3d'" error

I encounter the same problem, and @Joe Kington and @bvanlew's answer solve my problem.

but I should add more infomation when you use pycharm and enable auto import.

when you format the code, the code from mpl_toolkits.mplot3d import Axes3D will auto remove by pycharm.

so, my solution is

from mpl_toolkits.mplot3d import Axes3D
Axes3D = Axes3D  # pycharm auto import
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

and it works well!

Google Maps API warning: NoApiKeys

I had the same problem and I found out that if you add the URL param ?v=3 you won't get the warning message anymore:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>

Reproduction online

As pointed out in the comments by @Zia Ul Rehman Mughal

Turns out specifying this means you are referring to old frozen version 3.0 not the latest version. Frozen old versions are not updated with bug fixes or anything. But this is good to mention though. https://developers.google.com/maps/documentation/javascript/versions#the-frozen-version

Update 07-Jun-2016

This solution doesn't work anymore.

Pure CSS scroll animation

Use anchor links and the scroll-behavior property (MDN reference) for the scrolling container:

scroll-behavior: smooth;

Browser support: Firefox 36+, Chrome 61+ (therefore also Edge 79+) and Opera 48+.

Intenet Explorer, non-Chromium Edge and (so far) Safari do not support scroll-behavior and simply "jump" to the link target.

Example usage:

<head>
  <style type="text/css">
    html {
      scroll-behavior: smooth;
    }
  </style>
</head>
<body id="body">
  <a href="#foo">Go to foo!</a>

  <!-- Some content -->

  <div id="foo">That's foo.</div>
  <a href="#body">Back to top</a>
</body>

Here's a Fiddle.

And here's also a Fiddle with both horizontal and vertical scrolling.

Difference between pre-increment and post-increment in a loop?

They both increment the number. ++i is equivalent to i = i + 1.

i++ and ++i are very similar but not exactly the same. Both increment the number, but ++i increments the number before the current expression is evaluated, whereas i++ increments the number after the expression is evaluated.

int i = 3;
int a = i++; // a = 3, i = 4
int b = ++a; // b = 4, a = 

Check this link.

Array.sort() doesn't sort numbers correctly

The default sort for arrays in Javascript is an alphabetical search. If you want a numerical sort, try something like this:

var a = [ 1, 100, 50, 2, 5];
a.sort(function(a,b) { return a - b; });

Changing capitalization of filenames in Git

Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv commands will tire quickly. To make things a bit easier this is what I do:

  1. Move all files outside of the directory to, let’s, say the desktop.
  2. Do a git add . -A to remove all files.
  3. Rename all files on the desktop to the proper capitalization.
  4. Move all the files back to the original directory.
  5. Do a git add .. Git should see that the files are renamed.

Now you can make a commit saying you have changed the file name capitalization.

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

INSERT with SELECT

Yes, absolutely, but check your syntax.

INSERT INTO courses (name, location, gid)
SELECT name, location, 1
FROM   courses
WHERE  cid = 2

You can put a constant of the same type as gid in its place, not just 1, of course. And, I just made up the cid value.

Understanding Apache's access log

I also don't under stand what the "-" means after the 200 140 section of the log

That value corresponds to the referer as described by Joachim. If you see a dash though, that means that there was no referer value to begin with (eg. the user went straight to a specific destination, like if he/she typed a URL in their browser)

Understanding .get() method in Python

I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections library exists to fulfill these purposes.

from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
    letter_counter[letter] += 1

>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})

In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.

As for the dict.get(a_key, default_value), there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.

How to make Bootstrap 4 cards the same height in card-columns?

I came across this problem, most people use jQuery... Here was my solution. "Do not mind, I am just a beginner in this..."

.cards-collection {
    .card-item { 
        width: 100%;
        margin: 20px 20px;
        padding:0 ;
        .card {
            border-radius: 10px;
                button {
                    border: inherit;
                }
        }
    }
}
     .container-fluid
         .row.cards-collection.justify-content-center
           .card-item.col-lg-3.col-md-4.col-sm-6.col-11
              .card.h-100

If any card item height is e.g. 400px (based on it's contents), because the default for flex-align is stretch, then .card-item (child of row or card-collection class) will be stretched. making the height of the card to be 100% of the parent will occupy this full height.

I hope I was correct. Am I?

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

So I'm not entirely sure why this works, but it saves an image with my plot:

dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')

I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas. With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.

angular2 submit form by pressing enter without submit button

Just simply add (keyup.enter)="yourFunction()"

How to display a range input slider vertically

First, set height greater than width. In theory, this is all you should need. The HTML5 Spec suggests as much:

... the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties.

Opera had it implemented this way, but Opera is now using WebKit Blink. As of today, no browser implements a vertical slider based solely on height being greater than width.

Regardless, setting height greater than width is needed to get the layout right between browsers. Applying left and right padding will also help with layout and positioning.

For Chrome, use -webkit-appearance: slider-vertical.

For IE, use writing-mode: bt-lr.

For Firefox, add an orient="vertical" attribute to the html. Pity that they did it this way. Visual styles should be controlled via CSS, not HTML.

_x000D_
_x000D_
input[type=range][orient=vertical]
{
    writing-mode: bt-lr; /* IE */
    -webkit-appearance: slider-vertical; /* WebKit */
    width: 8px;
    height: 175px;
    padding: 0 5px;
}
_x000D_
<input type="range" orient="vertical" />
_x000D_
_x000D_
_x000D_


Disclaimers:

This solution is based on current browser implementations of as yet undefined or unfinalized CSS properties. If you intend to use it in your code, be prepared to make code adjustments as newer browser versions are released and w3c recommendations are completed.

MDN contains an explicit warning against using -webkit-appearance on the web:

Do not use this property on Web sites: not only is it non-standard, but its behavior change from one browser to another. Even the keyword none has not the same behavior on each form element on different browsers, and some doesn't support it at all.

The caption for the vertical slider demo in the IE documentation erroneously indicates that setting height greater than width will display a range slider vertically, but this does not work. In the code section, it plainly does not set height or width, and instead uses writing-mode. The writing-mode property, as implemented by IE, is very robust. Sadly, the values defined in the current working draft of the spec as of this writing, are much more limited. Should future versions of IE drop support of bt-lr in favor of the currently proposed vertical-lr (which would be the equivalent of tb-lr), the slider would display upside down. Most likely, future versions would extend the writing-mode to accept new values rather than drop support for existing values. But, it's good to know what you are dealing with.

Implementing a HashMap in C

The best approach depends on the expected key distribution and number of collisions. If relatively few collisions are expected, it really doesn't matter which method is used. If lots of collisions are expected, then which to use depends on the cost of rehashing or probing vs. manipulating the extensible bucket data structure.

But here is source code example of An Hashmap Implementation in C

npm ERR! Error: EPERM: operation not permitted, rename

I face this issue multiple times. It turns out, that it has nothing to do with permissions, cache, etc. The error message is misleading. For node v 6.x you will see more detailed error stack but not after 7.x For me and my colleges, the issue is timeout function. Basically the package install has not finished yet (i.e. holding the directory) when npm tries to delete it. in node 6.x you can see that in finalize.js now it's gone! Just use yarn.

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.

Selecting/excluding sets of columns in pandas

Also have a look into the built-in DataFrame.filter function.

Minimalistic but greedy approach (sufficient for the given df):

df.filter(regex="[^BD]")

Conservative/lazy approach (exact matches only):

df.filter(regex="^(?!(B|D)$).*$")

Conservative and generic:

exclude_cols = ['B','C']
df.filter(regex="^(?!({0})$).*$".format('|'.join(exclude_cols)))

How to use jQuery to call an ASP.NET web service?

I have a decent example in jQuery AJAX and ASMX on using the jQuery AJAX call with asmx web services...

There is a line of code to uncommment in order to have it return JSON.

How to redirect single url in nginx?

Put this in your server directive:

location /issue {
   rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
 }

Or duplicate it:

location /issue1 {
   rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
   rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
 ...

What is the easiest way to clear a database from the CLI with manage.py in Django?

You can use the Django-Truncate library to delete all data of a table without destroying the table structure.

Example:

  1. First, install django-turncate using your terminal/command line:
pip install django-truncate
  1. Add "django_truncate" to your INSTALLED_APPS in the settings.py file:
INSTALLED_APPS = [
    ...
    'django_truncate',
]
  1. Use this command in your terminal to delete all data of the table from the app.
python manage.py truncate --apps app_name --models table_name

How create Date Object with values in java

import java.io.*;
import java.util.*;
import java.util.HashMap;

public class Solution 
{

    public static void main(String[] args)
    {
        HashMap<Integer,String> hm = new HashMap<Integer,String>();
        hm.put(1,"SUNDAY");
        hm.put(2,"MONDAY");
        hm.put(3,"TUESDAY");
        hm.put(4,"WEDNESDAY");
        hm.put(5,"THURSDAY");
        hm.put(6,"FRIDAY");
        hm.put(7,"SATURDAY");
        Scanner in = new Scanner(System.in);
        String month = in.next();
        String day = in.next();
        String year = in.next();

        String format = year + "/" + month + "/" + day;
        Date date = null;
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
            date = formatter.parse(format);
        }
        catch(Exception e){
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        System.out.println(hm.get(dayOfWeek));
    }
}

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

MySQL 8 changed the default charset to utf8mb4. But some clients don't know this charset. Hence when the server reports its default charset to the client, and the client doesn't know what the server means, it throws this error.

See also https://bugs.mysql.com/bug.php?id=71606

That bug is against the MySQL Connector/C++ so it's affecting more than just PHP.

Okay—I got it to work by changing the character set to utf8, to be compatible with non-upgraded clients. I added this to /etc/my.cnf and restarted mysqld:

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8


[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

I found these settings in an answer from 2010: Change MySQL default character set to UTF-8 in my.cnf?

What is the correct format to use for Date/Time in an XML file

EDIT: This is bad advice. Use "o", as above. "s" does the wrong thing.

I always use this:

dateTime.ToUniversalTime().ToString("s");

This is correct if your schema looks like this:

<xs:element name="startdate" type="xs:dateTime"/>

Which would result in:

<startdate>2002-05-30T09:00:00</startdate>

You can get more information here: http://www.w3schools.com/xml/schema_dtypes_date.asp

What is JavaScript's highest integer value that a number can go to without losing precision?

At the moment of writing, JavaScript is receiving a new data type: BigInt. It is a TC39 proposal at stage 4 to be included in EcmaScript 2020. BigInt is available in Chrome 67+, FireFox 68+, Opera 54 and Node 10.4.0. It is underway in Safari, et al... It introduces numerical literals having an "n" suffix and allows for arbitrary precision:

var a = 123456789012345678901012345678901n;

Precision will still be lost, of course, when such a number is (maybe unintentionally) coerced to a number data type.

And, obviously, there will always be precision limitations due to finite memory, and a cost in terms of time in order to allocate the necessary memory and to perform arithmetic on such large numbers.

For instance, the generation of a number with a hundred thousand decimal digits, will take a noticeable delay before completion:

console.log(BigInt("1".padEnd(100000,"0")) + 1n)

...but it works.

How to override and extend basic Django admin templates?

I couldn't find a single answer or a section in the official Django docs that had all the information I needed to override/extend the default admin templates, so I'm writing this answer as a complete guide, hoping that it would be helpful for others in the future.

Assuming the standard Django project structure:

mysite-container/         # project container directory
    manage.py
    mysite/               # project package
        __init__.py
        admin.py
        apps.py
        settings.py
        urls.py
        wsgi.py
    app1/
    app2/
    ...
    static/
    templates/

Here's what you need to do:

  1. In mysite/admin.py, create a sub-class of AdminSite:

    from django.contrib.admin import AdminSite
    
    
    class CustomAdminSite(AdminSite):
        # set values for `site_header`, `site_title`, `index_title` etc.
        site_header = 'Custom Admin Site'
        ...
    
        # extend / override admin views, such as `index()`
        def index(self, request, extra_context=None):
            extra_context = extra_context or {}
    
            # do whatever you want to do and save the values in `extra_context`
            extra_context['world'] = 'Earth'
    
            return super(CustomAdminSite, self).index(request, extra_context)
    
    
    custom_admin_site = CustomAdminSite()
    

    Make sure to import custom_admin_site in the admin.py of your apps and register your models on it to display them on your customized admin site (if you want to).

  2. In mysite/apps.py, create a sub-class of AdminConfig and set default_site to admin.CustomAdminSite from the previous step:

    from django.contrib.admin.apps import AdminConfig
    
    
    class CustomAdminConfig(AdminConfig):
        default_site = 'admin.CustomAdminSite'
    
  3. In mysite/settings.py, replace django.admin.site in INSTALLED_APPS with apps.CustomAdminConfig (your custom admin app config from the previous step).

  4. In mysite/urls.py, replace admin.site.urls from the admin URL to custom_admin_site.urls

    from .admin import custom_admin_site
    
    
    urlpatterns = [
        ...
        path('admin/', custom_admin_site.urls),
        # for Django 1.x versions: url(r'^admin/', include(custom_admin_site.urls)),
        ...
    ]
    
  5. Create the template you want to modify in your templates directory, maintaining the default Django admin templates directory structure as specified in the docs. For example, if you were modifying admin/index.html, create the file templates/admin/index.html.

    All of the existing templates can be modified this way, and their names and structures can be found in Django's source code.

  6. Now you can either override the template by writing it from scratch or extend it and then override/extend specific blocks.

    For example, if you wanted to keep everything as-is but wanted to override the content block (which on the index page lists the apps and their models that you registered), add the following to templates/admin/index.html:

    {% extends 'admin/index.html' %}
    
    {% block content %}
      <h1>
        Hello, {{ world }}!
      </h1>
    {% endblock %}
    

    To preserve the original contents of a block, add {{ block.super }} wherever you want the original contents to be displayed:

    {% extends 'admin/index.html' %}
    
    {% block content %}
      <h1>
        Hello, {{ world }}!
      </h1>
      {{ block.super }}
    {% endblock %}
    

    You can also add custom styles and scripts by modifying the extrastyle and extrahead blocks.

Propagation Delay vs Transmission delay

Transmission Delay : Amount of time required to pump all bits/packets into the electric wire/optic fibre.

Propagation delay : It's the amount of time needed for a packet to reach the destination.

If propagation delay is very high than transmission delay the chance of losing the packet is high.

"Eliminate render-blocking CSS in above-the-fold content"

Consider using a package to automatically generate inline styles from your css files. A good one is Grunt Critical or Critical css for Laravel.

Create controller for partial view in ASP.NET MVC

The most important thing is, the action created must return partial view, see below.

public ActionResult _YourPartialViewSection()
{
    return PartialView();
}

Sort a list of Class Instances Python

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

HTML5 iFrame Seamless Attribute

You only need to write

seamless

in your code. There is not need for:

seamless ="seamless"

I just found this out myself.

EDIT - this does not remove scrollbars. Strangely

scrolling="no" still seems to work in html5. I have tried using the overflow function with an inline style as recommended by html5 but this doesn't work for me.

Removing multiple keys from a dictionary safely

Found a solution with pop and map

d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'b', 'c']
list(map(d.pop, keys))
print(d)

The output of this:

{'d': 'valueD'}

I have answered this question so late just because I think it will help in the future if anyone searches the same. And this might help.

Update

The above code will throw an error if a key does not exist in the dict.

DICTIONARY = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'l', 'c']

def remove_keys(key):
    try:
        DICTIONARY.pop(key, None)
    except:
        pass  # or do any action

list(map(remove_key, keys))
print(DICTIONARY)

output:

DICTIONARY = {'b': 'valueB', 'd': 'valueD'}

How do you develop Java Servlets using Eclipse?

Alternatively you can use Jetty which is (now) part of the Eclipe Platform (the Help system is running Jetty). Besides Jetty is used by Android, Windows Mobile..

To get started check the Eclipse Wiki or if you prefer a Video And check out this related Post!

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

As an update to Joe's answer, in that you can script the creation of the repository using the API, only the API call I needed was different. This may be because we are using bitbucket server, and not bitbucket cloud.

To create a new repo within a project on our server, I used:

curl -X POST -v -u USER:PASSWORD -H "Content-Type: application/json" \
http://SERVER/rest/api/1.0/projects/PROJECTNAME/repos/ \
-d '{"scmid":"git", "name":"REPONAME"}'

where USER, PASSWORD, SERVER, PROJECTNAME and REPONAME were of course the desired/required values.

The call is documented in the API reference.

/rest/api/1.0/projects/{projectKey}/repos

Create a new repository. Requires an existing project in which this repository will be created. The only parameters which will be used are name and scmId.

The authenticated user must have PROJECT_ADMIN permission for the context project to call this resource.

Java Programming: call an exe from Java and passing parameters

Pass your arguments in constructor itself.

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();

How do I subtract minutes from a date in javascript?

Try as below:

var dt = new Date();
dt.setMinutes( dt.getMinutes() - 20 );
console.log('#####',dt);

What is the difference between VFAT and FAT32 file systems?

FAT32 along with FAT16 and FAT12 are File System Types, but vfat along with umsdos and msdos are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos driver don't have long filenames (they are 8.3 format). vfat is the most common driver for mounting FAT32 file systems nowadays.

Source: this wikipedia article

Output of commands like df and lsblk indeed show vfat as the File System Type. But sudo file -sL /dev/<partition> shows FAT (32 bit) if a File System is FAT32.

You can confirm vfat is a module and not a File System Type by running modinfo vfat.

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

How to compare binary files to check if they are the same?

Use cmp command. This will either exit cleanly if they are binary equal, or it will print out where the first difference occurs and exit.

How to select only 1 row from oracle sql?

More flexible than select max() is:

select distinct first_row(column_x) over (order by column_y,column_z,...) from Table_A

Passing two command parameters using a WPF binding

Use Tuple in Converter, and in OnExecute, cast the parameter object back to Tuple.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<string, string> tuple = new Tuple<string, string>(
            (string)values[0], (string)values[1]);
        return (object)tuple;
    }      
} 

// ...

public void OnExecute(object parameter) 
{
    var param = (Tuple<string, string>) parameter;
}

eval command in Bash and its typical uses

In my experience, a "typical" use of eval is for running commands that generate shell commands to set environment variables.

Perhaps you have a system that uses a collection of environment variables, and you have a script or program that determines which ones should be set and their values. Whenever you run a script or program, it runs in a forked process, so anything it does directly to environment variables is lost when it exits. But that script or program can send the export commands to stdout.

Without eval, you would need to redirect stdout to a temp file, source the temp file, and then delete it. With eval, you can just:

eval "$(script-or-program)"

Note the quotes are important. Take this (contrived) example:

# activate.sh
echo 'I got activated!'

# test.py
print("export foo=bar/baz/womp")
print(". activate.sh")

$ eval $(python test.py)
bash: export: `.': not a valid identifier
bash: export: `activate.sh': not a valid identifier
$ eval "$(python test.py)"
I got activated!

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

With PostgreSQL 9.5, this is now native functionality (like MySQL has had for several years):

INSERT ... ON CONFLICT DO NOTHING/UPDATE ("UPSERT")

9.5 brings support for "UPSERT" operations. INSERT is extended to accept an ON CONFLICT DO UPDATE/IGNORE clause. This clause specifies an alternative action to take in the event of a would-be duplicate violation.

...

Further example of new syntax:

INSERT INTO user_logins (username, logins)
VALUES ('Naomi',1),('James',1) 
ON CONFLICT (username)
DO UPDATE SET logins = user_logins.logins + EXCLUDED.logins;

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

Importing large sql file to MySql via command line

The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.

Here is the script https://github.com/kedarvj/mysqldumpsplitter

And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully

How to picture "for" loop in block representation of algorithm

Here's a flow chart that illustrates a for loop:

Flow Chart For Loop

The equivalent C code would be

for(i = 2; i <= 6; i = i + 2) {
    printf("%d\t", i + 1);
}

I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.

Setting Action Bar title and subtitle

Nope! You have to do it at runtime.

If you want to make your app backwards compatible, then simply check the device API level. If it is higher than 11, then you can fiddle with the ActionBar and set the subtitle.

if(Integer.valueOf(android.os.Build.VERSION.SDK) >= 11){
    //set actionbar title
}

How do I shut down a python simpleHTTPserver?

if you have started the server with

python -m SimpleHTTPServer 8888 

then you can press ctrl + c to down the server.

But if you have started the server with

python -m SimpleHTTPServer 8888 &

or

python -m SimpleHTTPServer 8888 & disown

you have to see the list first to kill the process,

run command

ps

or

ps aux | less

it will show you some running process like this ..

PID TTY          TIME CMD
7247 pts/3     00:00:00 python
7360 pts/3     00:00:00 ps
23606 pts/3    00:00:00 bash

you can get the PID from here. and kill that process by running this command..

kill -9 7247

here 7247 is the python id.

Also for some reason if the port still open you can shut down the port with this command

fuser -k 8888/tcp

here 8888 is the tcp port opened by python.

Hope its clear now.

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

Clear all fields in a form upon going back with browser back button

If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.

$(window).load(function() {
    $('form').get(0).reset(); //clear form data on page load
});

Checking oracle sid and database name

I presume SELECT user FROM dual; should give you the current user

and SELECT sys_context('userenv','instance_name') FROM dual; the name of the instance

I believe you can get SID as SELECT sys_context('USERENV', 'SID') FROM DUAL;

jQuery convert line breaks to br (nl2br equivalent)

Solution

Use this code

jQuery.nl2br = function(varTest){
  return varTest.replace(/(\r\n|\n\r|\r|\n)/g, "<br>");
};

Find all controls in WPF Window by type

This should do the trick

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

then you enumerate over the controls like so

foreach (TextBlock tb in FindVisualChildren<TextBlock>(window))
{
    // do something with tb here
}

Hibernate Delete query

To understand this peculiar behavior of hibernate, it is important to understand a few hibernate concepts -

Hibernate Object States

Transient - An object is in transient status if it has been instantiated and is still not associated with a Hibernate session.

Persistent - A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session.

Detached - A detached instance is an object that has been persistent, but its Session has been closed.

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/objectstate.html#objectstate-overview

Transaction Write-Behind

The next thing to understand is 'Transaction Write behind'. When objects attached to a hibernate session are modified they are not immediately propagated to the database. Hibernate does this for at least two different reasons.

  • To perform batch inserts and updates.
  • To propagate only the last change. If an object is updated more than once, it still fires only one update statement.

http://learningviacode.blogspot.com/2012/02/write-behind-technique-in-hibernate.html

First Level Cache

Hibernate has something called 'First Level Cache'. Whenever you pass an object to save(), update() or saveOrUpdate(), and whenever you retrieve an object using load(), get(), list(), iterate() or scroll(), that object is added to the internal cache of the Session. This is where it tracks changes to various objects.

Hibernate Intercepters and Object Lifecycle Listeners -

The Interceptor interface and listener callbacks from the session to the application, allow the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. http://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html#d0e3069


This section Updated

Cascading

Hibernate allows applications to define cascade relationships between associations. For example, 'cascade-delete' from parent to child association will result in deletion of all children when a parent is deleted.

So, why are these important.

To be able to do transaction write-behind, to be able to track multiple changes to objects (object graphs) and to be able to execute lifecycle callbacks hibernate needs to know whether the object is transient/detached and it needs to have the object in it's first level cache before it makes any changes to the underlying object and associated relationships.

That's why hibernate (sometimes) issues a 'SELECT' statement to load the object (if it's not already loaded) in to it's first level cache before it makes changes to it.

Why does hibernate issue the 'SELECT' statement only sometimes?

Hibernate issues a 'SELECT' statement to determine what state the object is in. If the select statement returns an object, the object is in detached state and if it does not return an object, the object is in transient state.

Coming to your scenario -

Delete - The 'Delete' issued a SELECT statement because hibernate needs to know if the object exists in the database or not. If the object exists in the database, hibernate considers it as detached and then re-attches it to the session and processes delete lifecycle.

Update - Since you are explicitly calling 'Update' instead of 'SaveOrUpdate', hibernate blindly assumes that the object is in detached state, re-attaches the given object to the session first level cache and processes the update lifecycle. If it turns out that the object does not exist in the database contrary to hibernate's assumption, an exception is thrown when session flushes.

SaveOrUpdate - If you call 'SaveOrUpdate', hibernate has to determine the state of the object, so it uses a SELECT statement to determine if the object is in Transient/Detached state. If the object is in transient state, it processes the 'insert' lifecycle and if the object is in detached state, it processes the 'Update' lifecycle.

Table Naming Dilemma: Singular vs. Plural Names

I don't like plural table names because some nouns in English are not countable (water, soup, cash) or the meaning changes when you make it countable (chicken vs a chicken; meat vs bird). I also dislike using abbreviations for table name or column name because doing so adds extra slope to the already steep learning curve.

Ironically, I might make User an exception and call it Users because of USER (Transac-SQL), because I too don't like using brackets around tables if I don't have to.

I also like to name all the ID columns as Id, not ChickenId or ChickensId (what do plural guys do about this?).

All this is because I don't have proper respect for the database systems, I am just reapplying one-trick-pony knowledge from OO naming conventions like Java's out of habit and laziness. I wish there were better IDE support for complicated SQL.

How to get raw text from pdf file using java

Hi we can extract the pdf files using Apache Tika

The Example is :

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;

public class WebPagePdfExtractor {

    public Map<String, Object> processRecord(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream input = null;
            if (entity != null) {
                try {
                    input = entity.getContent();
                    BodyContentHandler handler = new BodyContentHandler();
                    Metadata metadata = new Metadata();
                    AutoDetectParser parser = new AutoDetectParser();
                    ParseContext parseContext = new ParseContext();
                    parser.parse(input, handler, metadata, parseContext);
                    map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
                    map.put("title", metadata.get(TikaCoreProperties.TITLE));
                    map.put("pageCount", metadata.get("xmpTPg:NPages"));
                    map.put("status_code", response.getStatusLine().getStatusCode() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
        Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
        System.out.println(extractedMap.get("text"));
    }

}

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

Vba macro to copy row from table if value in table meets condition

you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.

You should always consider a non-vba solution first.

Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):

http://www.youtube.com/watch?v=RCLUM0UMLXo

http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx


If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.

If it has to be the latter, then there is need for more details on your specification, regarding performance questions.

You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.

This would look something like that:

Public Sub CopyFilter()

  Dim wks As Worksheet
  Dim avarTemp() As Variant
  'go through each worksheet
  For Each wks In ThisWorkbook.Worksheets
        avarTemp = wks.UsedRange
        For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
          'check in the first column in each row
          If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
            'copy cell
             targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
          End If
        Next i
  Next wks
End Sub

Ok, now i have something nice which could come in handy for myself:

Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
  Dim avarTemp() As Variant
  Dim avarResult() As Variant
  Dim i As Long
  avarTemp = rng

  ReDim avarResult(0)

  For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
      If avarTemp(i, 1) = "active" Then
        avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
        'expand our result array
        ReDim Preserve avarResult(UBound(avarResult) + 1)
      End If
  Next i

  FILTER = avarResult
End Function

You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)

Polling the keyboard (detect a keypress) in python

I've come across a cross-platform implementation of kbhit at http://home.wlu.edu/~levys/software/kbhit.py (made edits to remove irrelevant code):

import os
if os.name == 'nt':
    import msvcrt
else:
    import sys, select

def kbhit():
    ''' Returns True if a keypress is waiting to be read in stdin, False otherwise.
    '''
    if os.name == 'nt':
        return msvcrt.kbhit()
    else:
        dr,dw,de = select.select([sys.stdin], [], [], 0)
        return dr != []

Make sure to read() the waiting character(s) -- the function will keep returning True until you do!

Error Message : Cannot find or open the PDB file

If that message is bother you, You need run Visual Studio with administrative rights to apply this direction on Visual Studio.

Tools-> Options-> Debugging-> Symbols and select check in a box "Microsoft Symbol Servers", mark load all modules then click Load all Symbols.

Everything else Visual Studio will do it for you, and you will have this message under Debug in Output window "Native' has exited with code 0 (0x0)"

What does "Content-type: application/json; charset=utf-8" really mean?

Dart http's implementation process the bytes thanks to that "charset=utf-8", so i'm sure several implementations out there supports this, to avoid the "latin-1" fallback charset when reading the bytes from the response. In my case, I totally lose format on the response body string, so I have to do the bytes encoding manually to utf8, or add that header "inner" parameter on my server's API response.

Best way to make WPF ListView/GridView sort on column-header clicking?

MSDN has an easy way to perform sorting on columns with up/down glyphs. The example isn't complete, though - they don't explain how to use the data templates for the glyphs. Below is what I got to work with my ListView. This works on .Net 4.

In your ListView, you have to specify an event handler to fire for a click on the GridViewColumnHeader. My ListView looks like this:

<ListView Name="results" GridViewColumnHeader.Click="results_Click">
    <ListView.View>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Path=ContactName}">
                <GridViewColumn.Header>
                    <GridViewColumnHeader Content="Contact Name" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="ContactName" />
                </GridViewColumn.Header>
            </GridViewColumn>
            <GridViewColumn DisplayMemberBinding="{Binding Path=PrimaryPhone}">
                <GridViewColumn.Header>
                    <GridViewColumnHeader Content="Contact Number" Padding="5,0,0,0" HorizontalContentAlignment="Left" MinWidth="150" Name="PrimaryPhone"/>
                </GridViewColumn.Header>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

In your code behind, set up the code to handle the sorting:

// Global objects
BindingListCollectionView blcv;
GridViewColumnHeader _lastHeaderClicked = null;
ListSortDirection _lastDirection = ListSortDirection.Ascending;

// Header click event
void results_Click(object sender, RoutedEventArgs e)
{
    GridViewColumnHeader headerClicked =
    e.OriginalSource as GridViewColumnHeader;
    ListSortDirection direction;

    if (headerClicked != null)
    {
    if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
    {
        if (headerClicked != _lastHeaderClicked)
        {
            direction = ListSortDirection.Ascending;
        }
        else
        {
            if (_lastDirection == ListSortDirection.Ascending)
            {
                direction = ListSortDirection.Descending;
            }
            else
            {
                direction = ListSortDirection.Ascending;
            }
        }

        string header = headerClicked.Column.Header as string;
        Sort(header, direction);

        if (direction == ListSortDirection.Ascending)
        {
            headerClicked.Column.HeaderTemplate =
              Resources["HeaderTemplateArrowUp"] as DataTemplate;
        }
        else
        {
            headerClicked.Column.HeaderTemplate =
              Resources["HeaderTemplateArrowDown"] as DataTemplate;
        }

        // Remove arrow from previously sorted header
        if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
        {
            _lastHeaderClicked.Column.HeaderTemplate = null;
        }

        _lastHeaderClicked = headerClicked;
        _lastDirection = direction;
    }
}

// Sort code
private void Sort(string sortBy, ListSortDirection direction)
{
    blcv.SortDescriptions.Clear();
    SortDescription sd = new SortDescription(sortBy, direction);
    blcv.SortDescriptions.Add(sd);
    blcv.Refresh();
}

And then in your XAML, you need to add two DataTemplates that you specified in the sorting method:

<DataTemplate x:Key="HeaderTemplateArrowUp">
    <DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
        <Path x:Name="arrowUp" StrokeThickness="1" Fill="Gray" Data="M 5,10 L 15,10 L 10,5 L 5,10" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
        <TextBlock Text="{Binding }" />
    </DockPanel>
</DataTemplate>

<DataTemplate x:Key="HeaderTemplateArrowDown">
    <DockPanel LastChildFill="True" Width="{Binding ActualWidth, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewColumnHeader}}}">
        <Path x:Name="arrowDown" StrokeThickness="1" Fill="Gray"  Data="M 5,5 L 10,10 L 15,5 L 5,5" DockPanel.Dock="Right" Width="20" HorizontalAlignment="Right" Margin="5,0,5,0" SnapsToDevicePixels="True"/>
        <TextBlock Text="{Binding }" />
    </DockPanel>
</DataTemplate>

Using the DockPanel with LastChildFill set to true will keep the glyph on the right of the header and let the label fill the rest of the space. I bound the DockPanel width to the ActualWidth of the GridViewColumnHeader because my columns have no width, which lets them autofit to the content. I did set MinWidths on the columns, though, so that the glyph doesn't cover up the column title. The TextBlock Text is set to an empty binding which displays the column name specified in the header.

How to use jQuery in AngularJS

This should be working. Please have a look at this fiddle.

$(function() {
   $( "#slider" ).slider();
});//Links to jsfiddle must be accompanied by code

Make sure you're loading the libraries in this order: jQuery, jQuery UI CSS, jQuery UI, AngularJS.

Creating your own header file in C

#ifndef MY_HEADER_H
# define MY_HEADER_H

//put your function headers here

#endif

MY_HEADER_H serves as a double-inclusion guard.

For the function declaration, you only need to define the signature, that is, without parameter names, like this:

int foo(char*);

If you really want to, you can also include the parameter's identifier, but it's not necessary because the identifier would only be used in a function's body (implementation), which in case of a header (parameter signature), it's missing.

This declares the function foo which accepts a char* and returns an int.

In your source file, you would have:

#include "my_header.h"

int foo(char* name) {
   //do stuff
   return 0;
}

Steps to send a https request to a rest service in Node js

Using the request module solved the issue.

// Include the request library for Node.js   
var request = require('request');
//  Basic Authentication credentials   
var username = "vinod"; 
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(   
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }  
},
 function (error, response, body) {
 console.log(body); }  );         

How to efficiently count the number of keys/properties of an object in JavaScript?

as answered above: Object.keys(obj).length

But: as we have now a real Map class in ES6, I would suggest to use it instead of using the properties of an object.

const map = new Map();
map.set("key", "value");
map.size; // THE fastest way

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

function amiLoadedInIFrame() {
    try {
         // Introduce a new propery in window.top
         window.top.dummyAttribute = true;
         // If window.dummyAttribute is there.. then window and window.top are same intances
         return !window.dummyAttribute;
    } catch(e) {
         // Exception will be raised when the top is in different domain
         return true;
    }
}

How to get a value from a cell of a dataframe?

If you have a DataFrame with only one row, then access the first (only) row as a Series using iloc, and then the value using the column name:

In [3]: sub_df
Out[3]:
          A         B
2 -0.133653 -0.030854

In [4]: sub_df.iloc[0]
Out[4]:
A   -0.133653
B   -0.030854
Name: 2, dtype: float64

In [5]: sub_df.iloc[0]['A']
Out[5]: -0.13365288513107493

CSS3 transition on click using pure CSS

As jeremyjjbrow said, :active pseudo won't persist. But there's a hack for doing it on pure css. You can wrap it on a <a> tag, and apply the :active on it, like this:

<a class="test">
    <img class="crossRotate" src="images/cross.png" alt="Cross Menu button" />
 </a>

And the css:

.test:active .crossRotate {
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    }

Try it out... It works (at least on Chrome)!

In Perl, how to remove ^M from a file?

I prefer a more general solution that will work with either DOS or Unix input. Assuming the input is from STDIN:

while (defined(my $ln = <>))
  {
    chomp($ln);
    chop($ln) if ($ln =~ m/\r$/);

    # filter and write
  }

Query to check index on a table

On Oracle:

  • Determine all indexes on table:

    SELECT index_name 
     FROM user_indexes
     WHERE table_name = :table
    
  • Determine columns indexes and columns on index:

    SELECT index_name
         , column_position
         , column_name
      FROM user_ind_columns
     WHERE table_name = :table
     ORDER BY index_name, column_order
    

References:

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How do I get Fiddler to stop ignoring traffic to localhost?

Internet Explorer has a new feature since IE9 RC: adding <-loopback> to the proxy bypass list causes WinInet (the network library used by IE) to send requests destined for localhost and 127.0.0.1 through the defined proxy.

Here's the original announcement by @EricLaw: http://blogs.msdn.com/b/fiddler/archive/2011/02/10/fiddler-is-better-with-internet-explorer-9.aspx

PHP: Possible to automatically get all POSTed data?

Yes you can use simply

     $input_data = $_POST;

or extract() may be useful for you.

how to install tensorflow on anaconda python 3.6

For Windows 10 with Anaconda 4.4 Python 3.6:

1st step) conda create -n tensorflow python=3.6

2nd step) activate tensorflow

3rd step) pip3 install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/cpu/tensorflow-1.2.1-cp36-cp36m-win_amd64.whl

How to 'grep' a continuous stream?

Turn on grep's line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)

tail -f file | grep --line-buffered my_pattern

It looks like a while ago --line-buffered didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, --line-buffered is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).

How do I find and replace all occurrences (in all files) in Visual Studio Code?

There are 2 methods technically same

  1. First put your cursor on the word and press F2. Replace your word and press Enter.

  2. First put your cursor on the word and left click it. Click "Rename Symbol" option. Replace your word and press Enter.

Measure the time it takes to execute a t-sql query

If you want a more accurate measurement than the answer above:

set statistics time on 

-- Query 1 goes here

-- Query 2 goes here

set statistics time off

The results will be in the Messages window.

Update (2015-07-29):

By popular request, I have written a code snippet that you can use to time an entire stored procedure run, rather than its components. Although this only returns the time taken by the last run, there are additional stats returned by sys.dm_exec_procedure_stats that may also be of value:

-- Use the last_elapsed_time from sys.dm_exec_procedure_stats
-- to time an entire stored procedure.

-- Set the following variables to the name of the stored proc
-- for which which you would like run duration info
DECLARE @DbName NVARCHAR(128);
DECLARE @SchemaName SYSNAME;
DECLARE @ProcName SYSNAME=N'TestProc';

SELECT CONVERT(TIME(3),DATEADD(ms,ROUND(last_elapsed_time/1000.0,0),0)) 
       AS LastExecutionTime
FROM sys.dm_exec_procedure_stats
WHERE OBJECT_NAME(object_id,database_id)=@ProcName AND
      (OBJECT_SCHEMA_NAME(object_id,database_id)=@SchemaName OR @SchemaName IS NULL) AND
      (DB_NAME(database_id)=@DbName OR @DbName IS NULL)

Pandas - How to flatten a hierarchical index in columns

And if you want to retain any of the aggregation info from the second level of the multiindex you can try this:

In [1]: new_cols = [''.join(t) for t in df.columns]
Out[1]:
['USAF',
 'WBAN',
 'day',
 'month',
 's_CDsum',
 's_CLsum',
 's_CNTsum',
 's_PCsum',
 'tempfamax',
 'tempfamin',
 'year']

In [2]: df.columns = new_cols

How to set selected value of jquery select2?

In the current version on select2 - v4.0.1 you can set the value like this:

_x000D_
_x000D_
var $example = $('.js-example-programmatic').select2();_x000D_
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });_x000D_
_x000D_
// Option 2 if you can't trigger the change event._x000D_
var $exampleDestroy = $('.js-example-programmatic-destroy').select2();_x000D_
$(".js-programmatic-set-val").on("click", function () { $exampleDestroy.val("CA").select2('destroy').select2(); });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet" />_x000D_
_x000D_
using "trigger(change)"_x000D_
<select class="js-example-programmatic">_x000D_
  <optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
    <option value="AK">Alaska</option>_x000D_
    <option value="HI">Hawaii</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Pacific Time Zone">_x000D_
    <option value="CA">California</option>_x000D_
    <option value="NV">Nevada</option>_x000D_
    <option value="OR">Oregon</option>_x000D_
    <option value="WA">Washington</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Mountain Time Zone">_x000D_
    <option value="AZ">Arizona</option>_x000D_
    <option value="CO">Colorado</option>_x000D_
    <option value="ID">Idaho</option>_x000D_
    <option value="MT">Montana</option>_x000D_
    <option value="NE">Nebraska</option>_x000D_
    <option value="NM">New Mexico</option>_x000D_
    <option value="ND">North Dakota</option>_x000D_
    <option value="UT">Utah</option>_x000D_
    <option value="WY">Wyoming</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Central Time Zone">_x000D_
    <option value="AL">Alabama</option>_x000D_
    <option value="AR">Arkansas</option>_x000D_
    <option value="IL">Illinois</option>_x000D_
    <option value="IA">Iowa</option>_x000D_
    <option value="KS">Kansas</option>_x000D_
    <option value="KY">Kentucky</option>_x000D_
    <option value="LA">Louisiana</option>_x000D_
    <option value="MN">Minnesota</option>_x000D_
    <option value="MS">Mississippi</option>_x000D_
    <option value="MO">Missouri</option>_x000D_
    <option value="OK">Oklahoma</option>_x000D_
    <option value="SD">South Dakota</option>_x000D_
    <option value="TX">Texas</option>_x000D_
    <option value="TN">Tennessee</option>_x000D_
    <option value="WI">Wisconsin</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Eastern Time Zone">_x000D_
    <option value="CT">Connecticut</option>_x000D_
    <option value="DE">Delaware</option>_x000D_
    <option value="FL">Florida</option>_x000D_
    <option value="GA">Georgia</option>_x000D_
    <option value="IN">Indiana</option>_x000D_
    <option value="ME">Maine</option>_x000D_
    <option value="MD">Maryland</option>_x000D_
    <option value="MA">Massachusetts</option>_x000D_
    <option value="MI">Michigan</option>_x000D_
    <option value="NH">New Hampshire</option>_x000D_
    <option value="NJ">New Jersey</option>_x000D_
    <option value="NY">New York</option>_x000D_
    <option value="NC">North Carolina</option>_x000D_
    <option value="OH">Ohio</option>_x000D_
    <option value="PA">Pennsylvania</option>_x000D_
    <option value="RI">Rhode Island</option>_x000D_
    <option value="SC">South Carolina</option>_x000D_
    <option value="VT">Vermont</option>_x000D_
    <option value="VA">Virginia</option>_x000D_
    <option value="WV">West Virginia</option>_x000D_
  </optgroup>_x000D_
</select>_x000D_
_x000D_
using destroy: _x000D_
<select class="js-example-programmatic">_x000D_
  <optgroup label="Alaskan/Hawaiian Time Zone">_x000D_
    <option value="AK">Alaska</option>_x000D_
    <option value="HI">Hawaii</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Pacific Time Zone">_x000D_
    <option value="CA">California</option>_x000D_
    <option value="NV">Nevada</option>_x000D_
    <option value="OR">Oregon</option>_x000D_
    <option value="WA">Washington</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Mountain Time Zone">_x000D_
    <option value="AZ">Arizona</option>_x000D_
    <option value="CO">Colorado</option>_x000D_
    <option value="ID">Idaho</option>_x000D_
    <option value="MT">Montana</option>_x000D_
    <option value="NE">Nebraska</option>_x000D_
    <option value="NM">New Mexico</option>_x000D_
    <option value="ND">North Dakota</option>_x000D_
    <option value="UT">Utah</option>_x000D_
    <option value="WY">Wyoming</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Central Time Zone">_x000D_
    <option value="AL">Alabama</option>_x000D_
    <option value="AR">Arkansas</option>_x000D_
    <option value="IL">Illinois</option>_x000D_
    <option value="IA">Iowa</option>_x000D_
    <option value="KS">Kansas</option>_x000D_
    <option value="KY">Kentucky</option>_x000D_
    <option value="LA">Louisiana</option>_x000D_
    <option value="MN">Minnesota</option>_x000D_
    <option value="MS">Mississippi</option>_x000D_
    <option value="MO">Missouri</option>_x000D_
    <option value="OK">Oklahoma</option>_x000D_
    <option value="SD">South Dakota</option>_x000D_
    <option value="TX">Texas</option>_x000D_
    <option value="TN">Tennessee</option>_x000D_
    <option value="WI">Wisconsin</option>_x000D_
  </optgroup>_x000D_
  <optgroup label="Eastern Time Zone">_x000D_
    <option value="CT">Connecticut</option>_x000D_
    <option value="DE">Delaware</option>_x000D_
    <option value="FL">Florida</option>_x000D_
    <option value="GA">Georgia</option>_x000D_
    <option value="IN">Indiana</option>_x000D_
    <option value="ME">Maine</option>_x000D_
    <option value="MD">Maryland</option>_x000D_
    <option value="MA">Massachusetts</option>_x000D_
    <option value="MI">Michigan</option>_x000D_
    <option value="NH">New Hampshire</option>_x000D_
    <option value="NJ">New Jersey</option>_x000D_
    <option value="NY">New York</option>_x000D_
    <option value="NC">North Carolina</option>_x000D_
    <option value="OH">Ohio</option>_x000D_
    <option value="PA">Pennsylvania</option>_x000D_
    <option value="RI">Rhode Island</option>_x000D_
    <option value="SC">South Carolina</option>_x000D_
    <option value="VT">Vermont</option>_x000D_
    <option value="VA">Virginia</option>_x000D_
    <option value="WV">West Virginia</option>_x000D_
  </optgroup>_x000D_
</select>_x000D_
_x000D_
<button class="js-programmatic-set-val">set value</button>
_x000D_
_x000D_
_x000D_

Preserve line breaks in angularjs

Well it depends, if you want to bind datas, there shouldn't be any formatting in it, otherwise you can bind-html and do description.replace(/\\n/g, '<br>') not sure it's what you want though.

Adding image inside table cell in HTML

Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.

MySQL Error 1215: Cannot add foreign key constraint

Another source of this error is that you have 2 or more same table names which have the same foreign key names. This sometimes happens to people who use modelling and design software, like Mysql Workbench, and later generate the script from the design.

jQuery remove all list items from an unordered list

   var ul = document.getElementById("yourElementId");

     while (ul.firstChild)
         ul.removeChild(ul.firstChild);

Border color on default input style

I would have thought this would have been answered already - but surely what you want is this: box-shadow: 0 0 3px #CC0000;

Example: http://jsfiddle.net/vmzLW/

Remove from the beginning of std::vector

Two suggestions:

  1. Use std::deque instead of std::vector for better performance in your specific case and use the method std::deque::pop_front().
  2. Rethink (I mean: delete) the & in std::vector<ScanRule>& topPriorityRules;

How to examine processes in OS X's Terminal?

Running ps -e does the trick. Found the answer here.

Nginx - Customizing 404 page

You use the error_page property in the nginx config.

For example, if you intend to set the 404 error page to /404.html, use

error_page 404 /404.html;

Setting the 500 error page to /500.html is just as easy as:

error_page 500 /500.html;

How to remove default chrome style for select Input?

When looking at an input with a type of number, you'll notice the spinner buttons (up/down) on the right-hand side of the input field. These spinners aren't always desirable, thus the code below removes such styling to render an input that resembles that of an input with a type of text.

enter image description here

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
}

Implement Stack using Two Queues

import java.util.LinkedList;
import java.util.Queue;

class MyStack {
    Queue<Integer> queue1 = new LinkedList<Integer>();
    Queue<Integer> queue2 = new LinkedList<Integer>();

    // Push element x onto stack.
    public void push(int x) {
        if(isEmpty()){
            queue1.offer(x);
        }else{
            if(queue1.size()>0){
                queue2.offer(x);
                int size = queue1.size();
                while(size>0){
                    queue2.offer(queue1.poll());
                    size--;
                }
            }else if(queue2.size()>0){
                queue1.offer(x);
                int size = queue2.size();
                while(size>0){
                    queue1.offer(queue2.poll());
                    size--;
                }
            }
        }
    }

    // Removes the element on top of the stack.
    public void pop() {
        if(queue1.size()>0){
            queue1.poll();
        }else if(queue2.size()>0){
            queue2.poll();
        }
    }

    // Get the top element. You can make it more perfect just example
    public int top() {
       if(queue1.size()>0){
            return queue1.peek();
        }else if(queue2.size()>0){
            return queue2.peek();
        }
        return 0;
    }

    // Return whether the stack is empty.
    public boolean isEmpty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
}

How can I Remove .DS_Store files from a Git repository?

When initializing your repository, skip the git command that contains

-u

and it shouldn't be an issue.

Getting value of selected item in list box as string

Get FullName in ListBox of files (full path) list (Thomas Levesque answer modificaton, thanks Thomas):

...
        string tmpStr = "";
        foreach (var item in listBoxFiles.SelectedItems)
        {
            tmpStr += listBoxFiles.GetItemText(item) + "\n";
        }
        MessageBox.Show(tmpStr);
...

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

Use the TextFieldParser class built into the .Net framework.

Here's some code copied from an MSDN forum post by Paul Clement. It converts the CSV into a new in-memory DataTable and then binds the DataGridView to the DataTable

    Dim TextFileReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\Documents and Settings\...\My Documents\My Database\Text\SemiColonDelimited.txt")

    TextFileReader.TextFieldType = FileIO.FieldType.Delimited
    TextFileReader.SetDelimiters(";")

    Dim TextFileTable As DataTable = Nothing

    Dim Column As DataColumn
    Dim Row As DataRow
    Dim UpperBound As Int32
    Dim ColumnCount As Int32
    Dim CurrentRow As String()

    While Not TextFileReader.EndOfData
        Try
            CurrentRow = TextFileReader.ReadFields()
            If Not CurrentRow Is Nothing Then
                ''# Check if DataTable has been created
                If TextFileTable Is Nothing Then
                    TextFileTable = New DataTable("TextFileTable")
                    ''# Get number of columns
                    UpperBound = CurrentRow.GetUpperBound(0)
                    ''# Create new DataTable
                    For ColumnCount = 0 To UpperBound
                        Column = New DataColumn()
                        Column.DataType = System.Type.GetType("System.String")
                        Column.ColumnName = "Column" & ColumnCount
                        Column.Caption = "Column" & ColumnCount
                        Column.ReadOnly = True
                        Column.Unique = False
                        TextFileTable.Columns.Add(Column)
                    Next
                End If
                Row = TextFileTable.NewRow
                For ColumnCount = 0 To UpperBound
                    Row("Column" & ColumnCount) = CurrentRow(ColumnCount).ToString
                Next
                TextFileTable.Rows.Add(Row)
            End If
        Catch ex As _
        Microsoft.VisualBasic.FileIO.MalformedLineException
            MsgBox("Line " & ex.Message & _
            "is not valid and will be skipped.")
        End Try
    End While
    TextFileReader.Dispose()
    frmMain.DataGrid1.DataSource = TextFileTable

Get original URL referer with PHP?

As Johnathan Suggested, you would either want to save it in a cookie or a session.

The easier way would be to use a Session variable.

session_start();
if(!isset($_SESSION['org_referer']))
{
    $_SESSION['org_referer'] = $_SERVER['HTTP_REFERER'];
}

Put that at the top of the page, and you will always be able to access the first referer that the site visitor was directed by.

Need a row count after SELECT statement: what's the optimal SQL approach?

Approach 2 will always return a count that matches your result set.

I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.

SELECT 
  mt.my_row,
 (SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt
FROM my_table mt
WHERE mt.foo = 'bar';

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

SQL Query to add a new column after an existing column in SQL Server 2005

According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.

Instead of:

SELECT * FROM MyTable

You can use:

SELECT col1, colNew, col2, col3 FROM MyTable

Guid.NewGuid() vs. new Guid()

Guid.NewGuid(), as it creates GUIDs as intended.

Guid.NewGuid() creates an empty Guid object, initializes it by calling CoCreateGuid and returns the object.

new Guid() merely creates an empty GUID (all zeros, I think).

I guess they had to make the constructor public as Guid is a struct.

Force IE9 to emulate IE8. Possible?

You can use the document compatibility mode to do this, which is what you were trying.. However, thing to note is: It must appear in the Web page's header (the HEAD section) before all other elements, except for the title element and other meta elements Hope that was the issue.. Also, The X-UA-compatible header is not case sensitive Refer: http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#SetMode

Edit: in case something happens to kill the msdn link, here is the content:

Specifying Document Compatibility Modes

You can use document modes to control the way Internet Explorer interprets and displays your webpage. To specify a specific document mode for your webpage, use the meta element to include an X-UA-Compatible header in your webpage, as shown in the following example.

<html>
<head>
  <!-- Enable IE9 Standards mode -->
  <meta http-equiv="X-UA-Compatible" content="IE=9" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

If you view this webpage in Internet Explorer 9, it will be displayed in IE9 mode.

The following example specifies EmulateIE7 mode.

<html>
<head>
  <!-- Mimic Internet Explorer 7 -->
  <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
  <title>My webpage</title>
</head>
<body>
  <p>Content goes here.</p>
</body>
</html> 

In this example, the X-UA-Compatible header directs Internet Explorer to mimic the behavior of Internet Explorer 7 when determining how to display the webpage. This means that Internet Explorer will use the directive (or lack thereof) to choose the appropriate document type. Because this page does not contain a directive, the example would be displayed in IE5 (Quirks) mode.

How to create custom view programmatically in swift having controls text field, button etc

view = MyCustomView(frame: CGRectZero)

In this line you are trying to set empty rect for your custom view. That's why you cant see your view in simulator.

linq where list contains any in list

You can use a Contains query for this:

var movies = _db.Movies.Where(p => p.Genres.Any(x => listOfGenres.Contains(x));

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

I encountered the similar problem after installing new software. In my case, the problem was solved by: (1) restoring .p2 subdirectory under my home directory; and (2) editing eclipse.init file to have the updated java directory.

Programmatically change the height and width of a UIImageView Xcode Swift

Using autoview

image.heightAnchor.constraint(equalToConstant: CGFloat(8)).isActive = true

What is the difference between JAX-RS and JAX-WS?

JAX-WS - is Java API for the XML-Based Web Services - a standard way to develop a Web- Services in SOAP notation (Simple Object Access Protocol).

Calling of the Web Services is performed via remote procedure calls. For the exchange of information between the client and the Web Service is used SOAP protocol. Message exchange between the client and the server performed through XML- based SOAP messages.

Clients of the JAX-WS Web- Service need a WSDL file to generate executable code that the clients can use to call Web- Service.

JAX-RS - Java API for RESTful Web Services. RESTful Web Services are represented as resources and can be identified by Uniform Resource Identifiers (URI). Remote procedure call in this case is represented a HTTP- request and the necessary data is passed as parameters of the query. Web Services RESTful - more flexible, can use several different MIME- types. Typically used for XML data exchange or JSON (JavaScript Object Notation) data exchange...

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

In my case, the issue was new sites had an implicit deny of all IP addresses unless an explicit allow was created. To fix: Under the site in Features View: Under the IIS Section > IP Address and Domain Restrictions > Edit Feature Settings > Set 'Access for unspecified clients:' to 'Allow'

Using getline() with file input in C++

you should do as:

getline(name, sizeofname, '\n');
strtok(name, " ");

This will give you the "joht" in name then to get next token,

temp = strtok(NULL, " ");

temp will get "smith" in it. then you should use string concatination to append the temp at end of name. as:

strcat(name, temp);

(you may also append space first, to obtain a space in between).

jQuery find parent form

You can use the form reference which exists on all inputs, this is much faster than .closest() (5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.

var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();

C# 4.0 optional out/ref arguments

ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:

p.GetCoordinates(out var x, out _); // I only care about x

P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.

Recommended way of making React component/div draggable

Here's a 2020 answer with a Hook:

function useDragging() {
  const [isDragging, setIsDragging] = useState(false);
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const ref = useRef(null);

  function onMouseMove(e) {
    if (!isDragging) return;
    setPos({
      x: e.x - ref.current.offsetWidth / 2,
      y: e.y - ref.current.offsetHeight / 2,
    });
    e.stopPropagation();
    e.preventDefault();
  }

  function onMouseUp(e) {
    setIsDragging(false);
    e.stopPropagation();
    e.preventDefault();
  }

  function onMouseDown(e) {
    if (e.button !== 0) return;
    setIsDragging(true);

    setPos({
      x: e.x - ref.current.offsetWidth / 2,
      y: e.y - ref.current.offsetHeight / 2,
    });

    e.stopPropagation();
    e.preventDefault();
  }

  // When the element mounts, attach an mousedown listener
  useEffect(() => {
    ref.current.addEventListener("mousedown", onMouseDown);

    return () => {
      ref.current.removeEventListener("mousedown", onMouseDown);
    };
  }, [ref.current]);

  // Everytime the isDragging state changes, assign or remove
  // the corresponding mousemove and mouseup handlers
  useEffect(() => {
    if (isDragging) {
      document.addEventListener("mouseup", onMouseUp);
      document.addEventListener("mousemove", onMouseMove);
    } else {
      document.removeEventListener("mouseup", onMouseUp);
      document.removeEventListener("mousemove", onMouseMove);
    }
    return () => {
      document.removeEventListener("mouseup", onMouseUp);
      document.removeEventListener("mousemove", onMouseMove);
    };
  }, [isDragging]);

  return [ref, pos.x, pos.y, isDragging];
}

Then a component that uses the hook:


function Draggable() {
  const [ref, x, y, isDragging] = useDragging();

  return (
    <div
      ref={ref}
      style={{
        position: "absolute",
        width: 50,
        height: 50,
        background: isDragging ? "blue" : "gray",
        left: x,
        top: y,
      }}
    ></div>
  );
}

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

Set a:hover based on class

Set a:hover based on class you can simply try:

a.main-nav-item:hover { }

SelectSingleNode returning null for known good xml node path using XPath

If you want to ignore namespaces completely, you can use this:

static void Main(string[] args)
{
    string xml =
        "<My_RootNode xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"\">\n" +
        "    <id root=\"2.16.840.1.113883.3.51.1.1.1\" extension=\"someIdentifier\" xmlns=\"urn:hl7-org:v3\" />\n" +
        "    <creationTime xsi:nil=\"true\" xmlns=\"urn:hl7-org:v3\" />\n" +
        "</My_RootNode>";

    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    XmlNode idNode = doc.SelectSingleNode("/*[local-name()='My_RootNode']/*[local-name()='id']");
}

Changing background colour of tr element on mouseover

Try it

<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">

<script>
function mOvr(src,clrOver) { 
  if (!src.contains(event.fromElement)) { 
  src.bgColor = clrOver; 
  } 
} 
function mOut(src,clrIn) { 
  if (!src.contains(event.toElement)) { 
  src.bgColor = clrIn; 
  } 
} 
</script>

What are abstract classes and abstract methods?

- Abstract class is one which can't be instantiated, i.e. its object cannot be created.

- Abstract method are method's declaration without its definition.

- A Non-abstract class can only have Non-abstract methods.

- An Abstract class can have both the Non-abstract as well as Abstract methods.

- If the Class has an Abstract method then the class must also be Abstract.

- An Abstract method must be implemented by the very first Non-Abstract sub-class.

- Abstract class in Design patterns are used to encapsulate the behaviors that keeps changing.

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.

 try {
     showFile();
 }
 catch(IOException e) {
    // Code to handle an IOException here
 }

Get current application physical path within Application_Start

 protected void Application_Start(object sender, EventArgs e)
 {
     string path = Server.MapPath("/");
     //or 
     string path2 = Server.MapPath("~");
     //depends on your application needs

 }

Failed to resolve: com.google.firebase:firebase-core:16.0.1

From the docs:-

Your app gradle file now has to explicitly list com.google.firebase:firebase-core as a dependency for Firebase services to work as expected.

Add:

 implementation 'com.google.firebase:firebase-core:16.0.1'

and in top level gradle file use the latest version of google play services:

classpath 'com.google.gms:google-services:4.0.2'

https://firebase.google.com/support/release-notes/android

https://bintray.com/android/android-tools/com.google.gms.google-services

Note:

You need to add the google() repo in the top level gradle file, as specified in the firebase docs and also it should be before jcenter():

 buildscript {
  repositories {
          google()
          jcenter()
      }



dependencies {
  classpath 'com.android.tools.build:gradle:3.1.3'
  classpath 'com.google.gms:google-services:4.0.2'
   }
}

allprojects {
     repositories {
              google()
             jcenter()
  }
}

task clean(type: Delete) {
  delete rootProject.buildDir
 }

https://firebase.google.com/docs/android/setup

Windows 7 SDK installation failure

I have had this same problem with the x64 version installation. It relates (in my case at least) to the dexplore.exe installation. I uninstalled dexplore, reinstalled it, did a heap of registry changes, etc. as per various blogs and SDKs all to no avail. What finally fixed it for me was editing this registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer\DisableBrowse

I changed the value to 0. Once the SDK had installed (quite happily this time) I set the value back to 1.

What alerted me to the possible error was the following in the SDK setup log:

12:19:42 PM Friday, 8 January 2010: SFX C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation started with log file C:\TEMP\Microsoft Windows SDK for Windows 7_dd2d9383-116d-441f-85b3-7c16aeb3568e_SFX.log
12:19:47 PM Friday, 8 January 2010: C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation failed with return code 1625

And this in the dexplore installation logfile:

MSI (s) (E4:7C) [12:19:46:680]: Machine policy value 'DisableBrowse' is 1
MSI (s) (E4:7C) [12:19:46:680]: Adding new sources is not allowed.
MSI (s) (E4:7C) [12:19:46:680]: Warning: rejected attempt to add new source 'c:\eb66d60e4283bfc2986755fa\' (product: {6753B40C-0FBD-3BED-8A9D-0ACAC2DCD85D})
MSI (s) (E4:7C) [12:19:46:680]: MSI_LUA: Elevation prompt disabled for silent installs
MSI (s) (E4:7C) [12:19:46:680]: Note: 1: 1729 
MSI (s) (E4:7C) [12:19:46:680]: Product: Microsoft Document Explorer 2008 -- Configuration failed.

I hope this is of assistance in your situation.

What does "var" mean in C#?

var is a "contextual keyword" in C# meaning you can only use it as a local variable implicitly in the context of the same class that you are using the variable. If you try to use it in a class that you call from "Main" or some other exterior class, or an interface for example you will get the error CS0825 < https://docs.microsoft.com/en-us/dotnet/csharp/misc/cs0825 >

See the remarks about when you can and can't use it in the documentation here: < https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables#remarks >

Basically, you should only use this when you are declaring a variable with an implicit value such as "var myValue = "This is the value"; This saves a little time in comparison to saying "string" for example but IMHO not much time is saved and places a constraint on the scalability of your project.

Multiple left joins on multiple tables in one query

You can do like this

SELECT something
FROM
    (a LEFT JOIN b ON a.a_id = b.b_id) LEFT JOIN c on a.a_aid = c.c_id
WHERE a.parent_id = 'rootID'

How to check if a file exists in Go?

The function example:

func file_is_exists(f string) bool {
    _, err := os.Stat(f)
    if os.IsNotExist(err) {
        return false
    }
    return err == nil
}

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I know this is old but this answer still applies to newer Core releases.

If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

Both -s and -p are optionals that default to the current folder.

How to make "if not true condition"?

Here is an answer by way of example:

In order to make sure data loggers are online a cron script runs every 15 minutes that looks like this:

#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
  echo "SUBJECT:  SOLAR is not responding to ping" | ssmtp [email protected]
  echo "SOLAR is not responding to ping" | ssmtp [email protected]
else
  echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
  echo "SUBJECT:  OUTSIDE is not responding to ping" | ssmtp [email protected]
  echo "OUTSIDE is not responding to ping" | ssmtp [email protected]
else
  echo "OUTSIDE is up"
fi
#

...and so on for each data logger that you can see in the montage at http://www.SDsolarBlog.com/montage


FYI, using &>/dev/null redirects all output from the command, including errors, to /dev/null

(The conditional only requires the exit status of the ping command)

Also FYI, note that since cron jobs run as root there is no need to use sudo ping in a cron script.

This application has no explicit mapping for /error

In my case the controller class was annotated with @Controller. Changing that to @RestController resolved the problem. Basically @RestController is @Controller + @ResponseBody So either use @RestController , or @Controller with @ResponseBody annotation with each method.

Some useful notes here : https://www.genuitec.com/spring-frameworkrestcontroller-vs-controller/

Passing variable from Form to Module in VBA

Siddharth's answer is nice, but relies on globally-scoped variables. There's a better, more OOP-friendly way.

A UserForm is a class module like any other - the only difference is that it has a hidden VB_PredeclaredId attribute set to True, which makes VB create a global-scope object variable named after the class - that's how you can write UserForm1.Show without creating a new instance of the class.

Step away from this, and treat your form as an object instead - expose Property Get members and abstract away the form's controls - the calling code doesn't care about controls anyway:

Option Explicit
Private cancelling As Boolean

Public Property Get UserId() As String
    UserId = txtUserId.Text
End Property

Public Property Get Password() As String
    Password = txtPassword.Text
End Property

Public Property Get IsCancelled() As Boolean
    IsCancelled = cancelling
End Property

Private Sub OkButton_Click()
    Me.Hide
End Sub

Private Sub CancelButton_Click()
    cancelling = True
    Me.Hide
End Sub

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        cancelling = True
        Cancel = True
        Me.Hide
    End If
End Sub

Now the calling code can do this (assuming the UserForm was named LoginPrompt):

With New LoginPrompt
    .Show vbModal
    If .IsCancelled Then Exit Sub
    DoSomething .UserId, .Password
End With

Where DoSomething would be some procedure that requires the two string parameters:

Private Sub DoSomething(ByVal uid As String, ByVal pwd As String)
    'work with the parameter values, regardless of where they came from
End Sub

Given a starting and ending indices, how can I copy part of a string in C?

Have you checked strncpy?

char * strncpy ( char * destination, const char * source, size_t num );

You must realize that begin and end actually defines a num of bytes to be copied from one place to another.

detect key press in python?

Python has a keyboard module with many features. Install it, perhaps with this command:

pip3 install keyboard

Then use it in code like:

import keyboard  # using module keyboard
while True:  # making a loop
    try:  # used try so that if user pressed other than the given key error will not be shown
        if keyboard.is_pressed('q'):  # if key 'q' is pressed 
            print('You Pressed A Key!')
            break  # finishing the loop
    except:
        break  # if user pressed a key other than the given key the loop will break

How do I access refs of a child component in the parent component

  1. Inside the child component add a ref to the node you need
  2. Inside the parent component add a ref to the child component.
/*
* Child component
*/
class Child extends React.Component {
  render() {
    return (
      <div id="child">
        <h1 ref={(node) => { this.heading = node; }}>
          Child
        </h1>
      </div>
    );
  }
}

/*
 * Parent component
 */
class Parent extends React.Component {
  componentDidMount() {
    // Access child component refs via parent component instance like this
    console.log(this.child.heading.getDOMNode());
  }

  render() {
    return (
      <div>
        <Child
          ref={(node) => { this.child = node; }}
        />
      </div>
    );
  }
}

Demo: https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

Round to 5 (or other number) in Python

No one actually wrote this yet I guess but you can do:

round(12, -1) --> 10
round(18, -1) --> 20

Iterate through dictionary values?

Depending on your version:

Python 2.x:

for key, val in PIX0.iteritems():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

Python 3.x:

for key, val in PIX0.items():
    NUM = input("Which standard has a resolution of {!r}?".format(val))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

You should also get in the habit of using the new string formatting syntax ({} instead of % operator) from PEP 3101:

https://www.python.org/dev/peps/pep-3101/

UITextView that expands to text using auto layout

UITextView doesn't provide an intrinsicContentSize, so you need to subclass it and provide one. To make it grow automatically, invalidate the intrinsicContentSize in layoutSubviews. If you use anything other than the default contentInset (which I do not recommend), you may need to adjust the intrinsicContentSize calculation.

@interface AutoTextView : UITextView

@end

#import "AutoTextView.h"

@implementation AutoTextView

- (void) layoutSubviews
{
    [super layoutSubviews];

    if (!CGSizeEqualToSize(self.bounds.size, [self intrinsicContentSize])) {
        [self invalidateIntrinsicContentSize];
    }
}

- (CGSize)intrinsicContentSize
{
    CGSize intrinsicContentSize = self.contentSize;

    // iOS 7.0+
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0f) {
        intrinsicContentSize.width += (self.textContainerInset.left + self.textContainerInset.right ) / 2.0f;
        intrinsicContentSize.height += (self.textContainerInset.top + self.textContainerInset.bottom) / 2.0f;
    }

    return intrinsicContentSize;
}

@end

How do I stop/start a scheduled task on a remote computer programmatically?

Here's what I found.

stop:

schtasks /end /s <machine name> /tn <task name>

start:

schtasks /run /s <machine name> /tn <task name>


C:\>schtasks /?

SCHTASKS /parameter [arguments]

Description:
    Enables an administrator to create, delete, query, change, run and
    end scheduled tasks on a local or remote system. Replaces AT.exe.

Parameter List:
    /Create         Creates a new scheduled task.

    /Delete         Deletes the scheduled task(s).

    /Query          Displays all scheduled tasks.

    /Change         Changes the properties of scheduled task.

    /Run            Runs the scheduled task immediately.

    /End            Stops the currently running scheduled task.

    /?              Displays this help message.

Examples:
    SCHTASKS
    SCHTASKS /?
    SCHTASKS /Run /?
    SCHTASKS /End /?
    SCHTASKS /Create /?
    SCHTASKS /Delete /?
    SCHTASKS /Query  /?
    SCHTASKS /Change /?

how to get yesterday's date in C#

DateTime dateTime = DateTime.Now ; 
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");

The above snippet will work. It is also advisable to make single instance of DateTime.Now;

How do I do word Stemming or Lemmatization?

If I may quote my answer to the question StompChicken mentioned:

The core issue here is that stemming algorithms operate on a phonetic basis with no actual understanding of the language they're working with.

As they have no understanding of the language and do not run from a dictionary of terms, they have no way of recognizing and responding appropriately to irregular cases, such as "run"/"ran".

If you need to handle irregular cases, you'll need to either choose a different approach or augment your stemming with your own custom dictionary of corrections to run after the stemmer has done its thing.

Multiple lines of input in <input type="text" />

If you need textarea with auto height, Use follows with pure javascript,

_x000D_
_x000D_
function auto_height(elem) {  /* javascript */_x000D_
    elem.style.height = "1px";_x000D_
    elem.style.height = (elem.scrollHeight)+"px";_x000D_
}
_x000D_
.auto_height { /* CSS */_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea rows="1" class="auto_height" oninput="auto_height(this)"></textarea>
_x000D_
_x000D_
_x000D_

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

What makes the code ugly is the special-handling for the first case. Most of the lines in this small snippet are devoted, not to doing the code's routine job, but to handling that special case. And that's what alternatives like gimel's solve, by moving the special handling outside the loop. There is one special case (well, you could see both start and end as special cases - but only one of them needs to be treated specially), so handling it inside the loop is unnecessarily complicated.

How to change the playing speed of videos in HTML5?

javascript:document.getElementsByClassName("video-stream html5-main-video")[0].playbackRate = 0.1;

you can put any number here just don't go to far so you don't overun your computer.

How do I create a custom Error in JavaScript?

The constructor needs to be like a factory method and return what you want. If you need additional methods/properties, you can add them to the object before returning it.

function NotImplementedError(message) { return new Error("Not implemented", message); }

x = new NotImplementedError();

Though I'm not sure why you'd need to do this. Why not just use new Error... ? Custom exceptions don't really add much in JavaScript (or probably any untyped language).

Variable is accessed within inner class. Needs to be declared final

Here's a funny answer.

You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.

I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.

final int[] tapCount = {0};

addSiteButton.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
       tapCount[0]++;
    }

});

stop all instances of node.js server

Multiplatform, stable, best solution:

use fkill to kill process which is taking your port:

fkill -f :8080

To install fkill use command: npm i -g fkill

Video 100% width and height

This works for me for video in a div container.

_x000D_
_x000D_
.videoContainer _x000D_
{_x000D_
    position:absolute;_x000D_
    height:100%;_x000D_
    width:100%;_x000D_
    overflow: hidden;_x000D_
}_x000D_
_x000D_
.videoContainer video _x000D_
{_x000D_
    min-width: 100%;_x000D_
    min-height: 100%;_x000D_
}
_x000D_
_x000D_
_x000D_

Reference: http://www.codesynthesis.co.uk/tutorials/html-5-full-screen-and-responsive-videos

how to add css class to html generic control div?

My approach would be:

/// <summary>
/// Appends CSS Class seprated by a space character
/// </summary>
/// <param name="control">Target control</param>
/// <param name="cssClass">CSS class name to append</param>
public static void AppendCss(HtmlGenericControl control, string cssClass)
{
    // Ensure CSS class is definied
    if (string.IsNullOrEmpty(cssClass)) return;

    // Append CSS class
    if (string.IsNullOrEmpty(control.Attributes["class"]))
    {
        // Set our CSS Class as only one
        control.Attributes["class"] = cssClass;
    }
    else
    {
        // Append new CSS class with space as seprator
        control.Attributes["class"] += (" " + cssClass);
    }
}

Determine the type of an object?

On instances of object you also have the:

__class__

attribute. Here is a sample taken from Python 3.3 console

>>> str = "str"
>>> str.__class__
<class 'str'>
>>> i = 2
>>> i.__class__
<class 'int'>
>>> class Test():
...     pass
...
>>> a = Test()
>>> a.__class__
<class '__main__.Test'>

Beware that in python 3.x and in New-Style classes (aviable optionally from Python 2.6) class and type have been merged and this can sometime lead to unexpected results. Mainly for this reason my favorite way of testing types/classes is to the isinstance built in function.

Could not create work tree dir 'example.com'.: Permission denied

Tested On Ubuntu 20, sudo chown -R $USER:$USER /var/www

Python style - line continuation with strings?

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

Find out where MySQL is installed on Mac OS X

If you run SHOW VARIABLES from a mysql console you can look for basedir.

When I run the following:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'basedir';

on my system I get /usr/local/mysql as the Value returned. (I am not using MAMP - I installed MySQL with homebrew.

mysqldon my machine is in /usr/local/mysql/bin so the basedir is where most everything will be installed to.

Also util:

mysql> SHOW VARIABLES WHERE `Variable_name` = 'datadir'; 

To find where the DBs are stored.

For more: http://dev.mysql.com/doc/refman/5.0/en/show-variables.html

and http://dev.mysql.com/doc/refman/5.0/en/server-options.html#option_mysqld_basedir