Programs & Examples On #Dreamweaver templates

Dreamweaver Templates are predesigned web site templates that can be easily edited and customized with Adobe Dreamweaver.

Add/remove class with jquery based on vertical scroll?

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

     //>=, not <=
    if (scroll >= 500) {
        //clearHeader, not clearheader - caps H
        $(".clearHeader").addClass("darkHeader");
    }
}); //missing );

Fiddle

Also, by removing the clearHeader class, you're removing the position:fixed; from the element as well as the ability of re-selecting it through the $(".clearHeader") selector. I'd suggest not removing that class and adding a new CSS class on top of it for styling purposes.

And if you want to "reset" the class addition when the users scrolls back up:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
        $(".clearHeader").addClass("darkHeader");
    } else {
        $(".clearHeader").removeClass("darkHeader");
    }
});

Fiddle

edit: Here's version caching the header selector - better performance as it won't query the DOM every time you scroll and you can safely remove/add any class to the header element without losing the reference:

$(function() {
    //caches a jQuery object containing the header element
    var header = $(".clearHeader");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 500) {
            header.removeClass('clearHeader').addClass("darkHeader");
        } else {
            header.removeClass("darkHeader").addClass('clearHeader');
        }
    });
});

Fiddle

How to create a data file for gnuplot?

This error usually means the file couldn't be found.

Can you see the file from the command line?

  1. Try specifying the full pathname.
  2. check line ending type (use 0x0d).
  3. is file open in another program?
  4. do you have read access to it?

How Should I Set Default Python Version In Windows?

This work for me.

If you want to use the python 3.6 you must move the python3.6 on the top of the list.

The same applies to the python2.7 If you want to have the 2.7 as default then make sure you move the python2.7 on the very top on the list.

step 1

enter image description here

step 2

enter image description here

step 3

enter image description here

then close any cmd command prompt and opened again, it should work as expected.

python --version

>>> Python 3.6

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

curl : (1) Protocol https not supported or disabled in libcurl

Got the same error when using curl on https site like

curl https://api.dis...

as pointed out by ganesh, it was because my version of curl wasn't ssl enabled. went back and downloaded the version with ssl and it worked fine.

How to use 'find' to search for files created on a specific date?

You could do this:

find ./ -type f -ls |grep '10 Sep'

Example:

[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235    4 -rw-r--r--   1 root     root           29 Dec 24 03:24 /var/lib/prelink/full
798227  288 -rw-r--r--   1 root     root       292323 Dec 24 23:53 /var/log/sa/sar24
797244  320 -rw-r--r--   1 root     root       321300 Dec 24 23:50 /var/log/sa/sa24

How to tell if a connection is dead in python

It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

You can use a vector. Instead of worry about different screen sizes you only need to create an .svg file and import it to your project using Vector Asset Studio.

Difference between a User and a Login in SQL Server

In Short,

Logins will have the access of the server.

and

Users will have the access of the database.

Location for session files in Apache/PHP

If unsure of compiled default for session.save_path, look at the pertinent php.ini.
Normally, this will show the commented out default value.

Ubuntu/Debian old/new php.ini locations:
Older php5 with Apache: /etc/php5/apache2/php.ini
Older php5 with NGINX+FPM: /etc/php5/fpm/php.ini
Ubuntu 16+ with Apache: /etc/php/*/apache2/php.ini *
Ubuntu 16+ with NGINX+FPM - /etc/php/*/fpm/php.ini *

* /*/ = the current PHP version(s) installed on system.

To show the PHP version in use under Apache:

$ a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+"

7.3

Since PHP 7.3 is the version running for this example, you would use that for the php.ini:

$ grep "session.save_path" /etc/php/7.3/apache2/php.ini

;session.save_path = "/var/lib/php/sessions"

Or, combined one-liner:

$ APACHEPHPVER=$(a2query -m | grep "php" | grep -Eo "[0-9]+\.[0-9]+") \ && grep ";session.save_path" /etc/php/${APACHEPHPVER}/apache2/php.ini

Result:

;session.save_path = "/var/lib/php/sessions"


Or, use PHP itself to grab the value using the "cli" environment (see NOTE below):

$ php -r 'echo session_save_path() . "\n";'
/var/lib/php/sessions
$

These will also work:

php -i | grep session.save_path

php -r 'echo phpinfo();' | grep session.save_path

NOTE:

The 'cli' (command line) version of php.ini normally has the same default values as the Apache2/FPM versions (at least as far as the session.save_path). You could also use a similar command to echo the web server's current PHP module settings to a webpage and use wget/curl to grab the info. There are many posts regarding phpinfo() use in this regard. But, it is quicker to just use the PHP interface or grep for it in the correct php.ini to show it's default value.

EDIT: Per @aesede comment -> Added php -i. Thanks

On Duplicate Key Update same as insert

There is a MySQL specific extension to SQL that may be what you want - REPLACE INTO

However it does not work quite the same as 'ON DUPLICATE UPDATE'

  1. It deletes the old row that clashes with the new row and then inserts the new row. So long as you don't have a primary key on the table that would be fine, but if you do, then if any other table references that primary key

  2. You can't reference the values in the old rows so you can't do an equivalent of

    INSERT INTO mytable (id, a, b, c) values ( 1, 2, 3, 4) 
    ON DUPLICATE KEY UPDATE
    id=1, a=2, b=3, c=c + 1;
    

I'd like to use the work around to get the ID to!

That should work — last_insert_id() should have the correct value so long as your primary key is auto-incrementing.

However as I said, if you actually use that primary key in other tables, REPLACE INTO probably won't be acceptable to you, as it deletes the old row that clashed via the unique key.

Someone else suggested before you can reduce some typing by doing:

INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);

How to construct a WebSocket URI relative to the page URI?

Using the Window.URL API - https://developer.mozilla.org/en-US/docs/Web/API/Window/URL

Works with http(s), ports etc.

var url = new URL('/path/to/websocket', window.location.href);

url.protocol = url.protocol.replace('http', 'ws');

url.href // => ws://www.example.com:9999/path/to/websocket

How to vertically align elements in a div?

<div id="header" style="display: table-cell; vertical-align:middle;">

...

or CSS

.someClass
{
   display: table-cell;
   vertical-align:middle;
}

Browser Coverage

How do I open a Visual Studio project in design view?

From the Solution Explorer window select your form, right-click, click on View Designer. Voila! The form should display.

I tried posting a couple screenshots, but this is my first post; therefore, I could not post any images.

How do I launch the Android emulator from the command line?

I think the best way to reach it via terminal is :

cd ~/Library/Android/sdk/emulator

To run a certain AVD directly:

./emulator -avd {AVD_NAME}

To list your AVDs use :

./emulator -list-avds

How to set selectedIndex of select element using display text?

Add name attribute to your option:

<option value="0" name="Chicken">Chicken</option>

With that you can use the HTMLOptionsCollection.namedItem("Chicken").value to set the value of your select element.

Error in plot.window(...) : need finite 'xlim' values

This error appears when the column contains character, if you check the data type it would be of type 'chr' converting the column to 'Factor' would solve this issue.

For e.g. In case you plot 'City' against 'Sales', you have to convert column 'City' to type 'Factor'

JSF rendered multiple combined conditions

Assuming that "a" and "b" are bean properties

rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"

You may look at JSF EL operators

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

Thanks Oleg Vaskevich. Using a WeakReference of the FragmentActivity solved the problem. My code looks as follows now:

public class MyFragmentActivity extends FragmentActivity implements OnFriendAddedListener {

    private static WeakReference<MyFragmentActivity> wrActivity = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        wrActivity = new WeakReference<MyFragmentActivity>(this);
        ...

    private class onFriendAddedAsyncTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            DummyFragment dummyFragment = DummyFragment.newInstance();
            ft.add(R.id.dummy_fragment_layout, dummyFragment);
            ft.commit();
        }

        @Override
        protected void onPostExecute(String result) {
            final Activity activity = wrActivity.get();
            if (activity != null && !activity.isFinishing()) {
                FragmentManager fm = activity.getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                DummyFragment dummyFragment = (DummyFragment) fm.findFragmentById(R.id.dummy_fragment_layout);
                ft.remove(dummyFragment);
                ft.commitAllowingStateLoss();
            }
        }

How to split strings into text and number?

I would approach this by using re.match in the following way:

import re
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
    items = match.groups()
print(items)
>> ("foofo", "21")

Is there an exponent operator in C#?

Since no-one has yet wrote a function to do this with two integers, here's one way:

private long CalculatePower(int number, int powerOf)
{
    for (int i = powerOf; i > 1; i--)
        number *= number;
    return number;
}
CalculatePower(5, 3); // 125
CalculatePower(8, 4); // 4096
CalculatePower(6, 2); // 36

Alternatively in VB.NET:

Private Function CalculatePower(number As Integer, powerOf As Integer) As Long
    For i As Integer = powerOf To 2 Step -1
        number *= number
    Next
    Return number
End Function
CalculatePower(5, 3) ' 125
CalculatePower(8, 4) ' 4096
CalculatePower(6, 2) ' 36

ImportError: No module named request

You can do that using Python 2.

  1. Remove request
  2. Make that line: from urllib2 import urlopen

You cannot have request in Python 2, you need to have Python 3 or above.

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

For users of SQL 2000, the actual command that will provide this information is:

select c.text
from sysobjects     o
join syscomments    c on c.id = o.id
where o.name = '<view_name_here>'
  and o.type      = 'V'

Angular and Typescript: Can't find names - Error: cannot find name

I was getting this on Angular 2 rc1. Turns out some names changed with typings v1 vs the old 0.x. The browser.d.ts files became index.d.ts.

After running typings install locate your startup file (where you bootstrap) and add:

/// <reference path="../typings/index.d.ts" /> (or without the ../ if your startup file is in the same folder as the typings folder)

Adding index.d.ts to the files list in tsconfig.json did not work for some reason.

Also, the es6-shim package was not needed.

Add inline style using Javascript

Try something like this

document.getElementById("vid-holder").style.width=300 + "px";

How to decode a Base64 string?

Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.

Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.

While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.

I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.

Base64decode("the answer to life the universe and everything") = 00101010

onclick go full screen

I realize this is a very old question, and that the answers provided were adequate, since is active and I came across this by doing some research on fullscreen, I leave here one update to this topic:

There is a way to "simulate" the F11 key, but cannot be automated, the user actually needs to click a button for example, in order to trigger the full screen mode.

  • Toggle Fullscreen status on button click

    With this example, the user can switch to and from fullscreen mode by clicking a button:

    HTML element to act as trigger:

    <input type="button" value="click to toggle fullscreen" onclick="toggleFullScreen()">
    

    JavaScript:

    function toggleFullScreen() {
      if ((document.fullScreenElement && document.fullScreenElement !== null) ||    
       (!document.mozFullScreen && !document.webkitIsFullScreen)) {
        if (document.documentElement.requestFullScreen) {  
          document.documentElement.requestFullScreen();  
        } else if (document.documentElement.mozRequestFullScreen) {  
          document.documentElement.mozRequestFullScreen();  
        } else if (document.documentElement.webkitRequestFullScreen) {  
          document.documentElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);  
        }  
      } else {  
        if (document.cancelFullScreen) {  
          document.cancelFullScreen();  
        } else if (document.mozCancelFullScreen) {  
          document.mozCancelFullScreen();  
        } else if (document.webkitCancelFullScreen) {  
          document.webkitCancelFullScreen();  
        }  
      }  
    }
    
  • Go to Fullscreen on button click

    This example allows you to enable full screen mode without making alternation, ie you switch to full screen but to return to the normal screen will have to use the F11 key:

    HTML element to act as trigger:

    <input type="button" value="click to go fullscreen" onclick="requestFullScreen()">
    

    JavaScript:

    function requestFullScreen() {
    
      var el = document.body;
    
      // Supports most browsers and their versions.
      var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen 
      || el.mozRequestFullScreen || el.msRequestFullScreen;
    
      if (requestMethod) {
    
        // Native full screen.
        requestMethod.call(el);
    
      } else if (typeof window.ActiveXObject !== "undefined") {
    
        // Older IE.
        var wscript = new ActiveXObject("WScript.Shell");
    
        if (wscript !== null) {
          wscript.SendKeys("{F11}");
        }
      }
    }
    

Sources found along with useful information on this subject:

Mozilla Developer Network

How to make in Javascript full screen windows (stretching all over the screen)

How to make browser full screen using F11 key event through JavaScript

Chrome Fullscreen API

jQuery fullscreen event plugin, version 0.2.0

jquery-fullscreen-plugin

How do I make a <div> move up and down when I'm scrolling the page?

Just add position: fixed; in your div style.

I have checked and Its working fine in my code.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

None of the answers here worked for me. What I had to do is:

  1. Re-run the installer.
  2. Select the quick action 're-configure' next to product 'MySQL Server'
  3. Go through the options till you reach Authentication Method and select 'Use Legacy Authentication Method'

After that it works fine.

difference between width auto and width 100 percent

When we say

width:auto;

width will never exceed the total width of parent element. Maximum width is it's parent width. Even if we add border, padding and margin, content of element itself will become smaller in order to give space for border, padding and margin. In case if space required for border + padding + margin is greater than total width of parent element then width of content will become zero.

When we say

width:100%;

width of content of element will become 100% of parent element and from now if we add border, padding or margin then it will cause child element to exceed parent element's width and it will starts overflowing out of parent element.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

Apple Cover-flow effect using jQuery or other library?

jCoverflip was just released and is very customizable.

Bootstrap modal in React.js

You can try this modal:https://github.com/xue2han/react-dynamic-modal It is stateless and can be rendered only when needed.So it is very easy to use.Just like this:

    class MyModal extends Component{
       render(){
          const { text } = this.props;
          return (
             <Modal
                onRequestClose={this.props.onRequestClose}
                openTimeoutMS={150}
                closeTimeoutMS={150}
                style={customStyle}>
                <h1>What you input : {text}</h1>
                <button onClick={ModalManager.close}>Close Modal</button>
             </Modal>
          );
       }
    }

    class App extends Component{
        openModal(){
           const text = this.refs.input.value;
           ModalManager.open(<MyModal text={text} onRequestClose={() => true}/>);
        }
        render(){
           return (
              <div>
                <div><input type="text" placeholder="input something" ref="input" /></div>
                <div><button type="button" onClick={this.openModal.bind(this)}>Open Modal </button> </div>
              </div>
           );
        }
    }

    ReactDOM.render(<App />,document.getElementById('main'));

How to define static constant in a class in swift

If I understand your question correctly, you are asking how you can create class level constants (static - in C++ parlance) such that you don't a) replicate the overhead in every instance, and b have to recompute what is otherwise constant.

The language has evolved - as every reader knows, but as I test this in Xcode 6.3.1, the solution is:

import Swift

class MyClass {
    static let testStr = "test"
    static let testStrLen = count(testStr)

    init() {
        println("There are \(MyClass.testStrLen) characters in \(MyClass.testStr)")
    }
}

let a = MyClass()

// -> There are 4 characters in test

I don't know if the static is strictly necessary as the compiler surely only adds only one entry per const variable into the static section of the binary, but it does affect syntax and access. By using static, you can refer to it even when you don't have an instance: MyClass.testStrLen.

Show constraints on tables command

I use

SHOW CREATE TABLE mytable;

This shows you the SQL statement necessary to receate mytable in its current form. You can see all the columns and their types (like DESC) but it also shows you constraint information (and table type, charset, etc.).

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

Two options:

libimobiledevice is installable via homebrew and works great. Its idevicesyslog tool works similarly to deviceconsole (below), and it supports wirelessly viewing your device's syslog (!)

I've written more about that on Tumblr tl;dr:

brew install libimobiledevice
idevice_id --list // list available device UDIDs
idevicesyslog -u <device udid>

with the device connected via USB or available on the local wireless network.


(Keeping for the historical record, from 2013:) deviceconsole from rpetrich is a much less wacked-out solution than ideviceconsole above. My fork of it builds and runs in Xcode 5 out of the box, and the Build action will install the binary to /usr/local/bin for ease of use.

As an additional helpful bit of info, I use it in the following style which makes it easy to find the device I want in my shell history and removes unnecessary > lines that deviceconsole prints out.

deviceconsole -d -u <device UDID> | uniq -u && echo "<device name>"

How do I display a decimal value to 2 decimal places?

If you need to keep only 2 decimal places (i.e. cut off all the rest of decimal digits):

decimal val = 3.14789m;
decimal result = Math.Floor(val * 100) / 100; // result = 3.14

If you need to keep only 3 decimal places:

decimal val = 3.14789m;
decimal result = Math.Floor(val * 1000) / 1000; // result = 3.147

Triggering a checkbox value changed event in DataGridView

cellEndEditTimer.Start();

this line makes the datagridview update the list of checked boxes

Thank you.

Installing PDO driver on MySQL Linux server

If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!

Here's how I installed in Ubuntu-based image:

https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8

RUN docker-php-ext-install mysql mysqli pdo pdo_mysql

Building and running your application is just a 2 step process (considering you are in the current directory of the app):

$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp

How do I open multiple instances of Visual Studio Code?

In 2019, it will automatically open a new session, new instance of vs-code. By type

      C:\Apache24\htdocs\json2tree>code .

at the command window, under your project root folder.

first cd into your project folder,

        C:\Apache24\htdocs\json2tree>

then, type

         code .

How to get a web page's source code from Java

Try the following code with an added request property:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class SocketConnection
{
    public static String getURLSource(String url) throws IOException
    {
        URL urlObject = new URL(url);
        URLConnection urlConnection = urlObject.openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

        return toString(urlConnection.getInputStream());
    }

    private static String toString(InputStream inputStream) throws IOException
    {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
        {
            String inputLine;
            StringBuilder stringBuilder = new StringBuilder();
            while ((inputLine = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(inputLine);
            }

            return stringBuilder.toString();
        }
    }
}

Writing a large resultset to an Excel file using POI

Oh. I think you're writing the workbook out 944,000 times. Your wb.write(bos) call is in the inner loop. I'm not sure this is quite consistent with the semantics of the Workbook class? From what I can tell in the Javadocs of that class, that method writes out the entire workbook to the output stream specified. And it's gonna write out every row you've added so far once for every row as the thing grows.

This explains why you're seeing exactly 1 row, too. The first workbook (with one row) to be written out to the file is all that is being displayed - and then 7GB of junk thereafter.

Should I use JSLint or JSHint JavaScript validation?

tl;dr takeaway:

If you're looking for a very high standard for yourself or team, JSLint. But its not necessarily THE standard, just A standard, some of which comes to us dogmatically from a javascript god named Doug Crockford. If you want to be a bit more flexible, or have some old pros on your team that don't buy into JSLint's opinions, or are going back and forth between JS and other C-family languages on a regular basis, try JSHint.

long version:

The reasoning behind the fork explains pretty well why JSHint exists:

http://badassjs.com/post/3364925033/jshint-an-community-driven-fork-of-jslint http://anton.kovalyov.net/2011/02/20/why-i-forked-jslint-to-jshint/

So I guess the idea is that it's "community-driven" rather than Crockford-driven. In practicality, JSHint is generally a bit more lenient (or at least configurable or agnostic) on a few stylistic and minor syntactical "opinions" that JSLint is a stickler on.

As an example, if you think both the A and B below are fine, or if you want to write code with one or more of the aspects of A that aren't available in B, JSHint is for you. If you think B is the only correct option... JSLint. I'm sure there are other differences, but this highlights a few.

A) Passes JSHint out of the box - fails JSLint

(function() {
  "use strict";
  var x=0, y=2;
  function add(val1, val2){
    return val1 + val2;
  }
  var z;
  for (var i=0; i<2; i++){
    z = add(y, x+i);
  }
})();

B) Passes Both JSHint and JSLint

(function () {
    "use strict";
    var x = 0, y = 2, i, z;
    function add(val1, val2) {
       return val1 + val2;
    }
    for (i = 0; i < 2; i += 1) {
        z = add(y, x + i);
    }
}());

Personally I find JSLint code very nice to look at, and the only hard features of it that I disagree with are its hatred of more than one var declaration in a function and of for-loop var i = 0 declarations, and some of the whitespace enforcements for function declarations.

A few of the whitespace things that JSLint enforces, I find to be not necessarily bad, but out of sync with some pretty standard whitespace conventions for other languages in the family (C, Java, Python, etc...), which are often followed as conventions in Javascript as well. Since I'm writing in various of these languages throughout the day, and working with team members who don't like Lint-style whitespace in our code, I find JSHint to be a good balance. It catches stuff that's a legitimate bug or really bad form, but doesn't bark at me like JSLint does (sometimes, in ways I can't disable) for the stylistic opinions or syntactic nitpicks that I don't care for.

A lot of good libraries aren't Lint'able, which to me demonstrates that there's some truth to the idea that some of JSLint is simply just about pushing 1 version of "good code" (which is, indeed, good code). But then again, the same libraries (or other good ones) probably aren't Hint'able either, so, touché.

Java: Get last element after split

With Guava:

final Splitter splitter = Splitter.on("-").trimResults();
assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one)));
assertEquals("Madison", Iterables.getLast(splitter.split(two)));

Splitter, Iterables

What is the proper REST response code for a valid request but an empty data?

I'd say, neither is really appropriate. As has been said – e.g. by @anneb, I, too, think that part of the problems arises from using an HTTP response code to transport a status relating to a RESTful service. Anything the REST service has to say about its own processing should be transported by means of REST specific codes.

1

I'd argue that, if the HTTP server finds any service that is ready to answer a request it was sent, it should not respond with an HTTP 404 – in the end, something was found by the server – unless told so explicitly by the service that processes the request.

Let's assume for a moment the following URL: http://example.com/service/return/test.

  • Case A is that the server is “simply looking for the file on the file system“. If it is not present, 404 is correct. The same is true, if it asks some kind of service to deliver exactly this file and that service tells it that nothing of that name exists.
  • In case B, the server does not work with “real” files but actually the request is processed by some other service – e.g. some kind of templating system. Here, the server cannot make any claim about the existence of the resource as it knows nothing about it (unless told by the service handling it).

Without any response from the service explicitly requiring a different behaviour, the HTTP server can only say 3 things:

  • 503 if the service that is supposed to handle the request is not running or responding;
  • 200 otherwise as the HTTP server can actually satisfy the request – no matter what the service will say later;
  • 400 or 404 to indicate that there is no such service (as opposed to “exists but offline”) and nothing else was found.

2

To get back to the question at hand: I think the cleanest approach would be to not use an HTTP any response code at all other than said before. If the service is present and responding, the HTTP code should be 200. The response should contain the status the service returned in a separate header – here, the service can say

  • REST:EMPTY e.g. if it was asked to search for sth. and that research returned empty;
  • REST:NOT FOUND if it was asked specifically for sth. “ID-like” – be that a file name or a resource by ID or entry No. 24, etc. – and that specific resource was not found (usually, one specific resource was requested and not found);
  • REST:INVALID if any part of the request it was sent is not recognized by the service.

(note that I prefixed these with “REST:” on purpose to mark the fact that while these may have the same values or wording as do HTTP response codes, they are sth. completely different)

3

Let's get back to the URL above and inspect case B where service indicates to the HTTP server that it does not handle this request itself but passes it on to SERVICE. HTTP only serves out what it is handed back by SERVICE, it does not know anything about the return/test portion as that is handeled by SERVICE. If that service is running, HTTP should return 200 as it did indeed find something to handle the request.

The status returned by SERVICE (and which, as said above, would like to see in a separate header) depends on what action is actually expected:

  • if return/test asks for a specific resource: if it exists, return it with a status of REST:FOUND; if that resource does not exist, return REST:NOT FOUND; this could be extended to return REST:GONE if we know it once existed and will not return, and REST:MOVED if we know it has gone hollywood
  • if return/test is considered a search or filter-like operation: if the result set is empty, return an empty set in the type requested and a status of REST:EMPTY; a set of results in the type requested and a status of REST:SUCCESS
  • if return/test is not an operation recogized by SERVICE: return REST:ERROR if it is completely wrong (e.g. a typo like retrun/test), or REST:NOT IMPLEMENTED in case it is planned for later.

4

This distinction is a lot cleaner than mixing the two different things up. It will also make debugging easier and processing only slightly more complex, if at all.

  • If an HTTP 404 is returned, the server tells me, “I have no idea what you're talking about”. While the REST portion of my request might be perectly okay, I'm looking for par'Mach in all the wrong places.
  • On the other hand, HTTP 200 and REST:ERR tells me I got the service but did something wrong in my request to the service.
  • From HTTP 200 and REST:EMPTY, I know that I did nothing wrong – right server, the server found the service, right request to the service – but the search result is empty.

Summary

The problem and discussion arises from the fact that HTTP response codes are being used to denote the state of a service whose results are served by HTTP, or to denote sth. that is not in the scope of the HTTP server itself. Due to this discrepancy, the question cannot be answered and all opinions are subject to a lot of discussion.

The state of a request processed by a service and not the HTTP server REALLY SHOULD NOT (RFC 6919) be given by an HTTP response code. The HTTP code SHOULD (RFC 2119) only contain information the HTTP server can give from its own scope: namely, whether the service was found to process the request or not.

Instead, a different way SHOULD be used to tell a consumer about the state of the request to the service that is actually processing the request. My proposal is to do so via a specific header. Ideally, both the name of the header and its contents follow a standard that makes it easy for consumers to work with theses responses.

How do I handle newlines in JSON?

I guess this is what you want:

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

(You need to escape the "\" in your string (turning it into a double-"\"), otherwise it will become a newline in the JSON source, not the JSON data.)

Working Copy Locked

As you get working copy error, Just run the svn cleanup which clean all the unwanted files and folders. If still error comes, then do one thing.

Copy your files to other drive and delete the working copy folder or file and then take a update it will fetch the fresh file and after this replace with your updated copy and commit the same.

How do I make a Windows batch script completely silent?

To suppress output, use redirection to NUL.

There are two kinds of output that console commands use:

  • standard output, or stdout,

  • standard error, or stderr.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

or

COPY file1 file2 1>NUL

or

>NUL COPY file1 file2

or

1>NUL COPY file1 file2

suppresses all of COPY's standard output.

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

or

2>NUL DEL file

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

SQL/mysql - Select distinct/UNIQUE but return all columns?

Great question @aryaxt -- you can tell it was a great question because you asked it 5 years ago and I stumbled upon it today trying to find the answer!

I just tried to edit the accepted answer to include this, but in case my edit does not make it in:

If your table was not that large, and assuming your primary key was an auto-incrementing integer you could do something like this:

SELECT 
  table.*
FROM table
--be able to take out dupes later
LEFT JOIN (
  SELECT field, MAX(id) as id
  FROM table
  GROUP BY field
) as noDupes on noDupes.id = table.id
WHERE
  //this will result in only the last instance being seen
  noDupes.id is not NULL

Difference between INNER JOIN and LEFT SEMI JOIN

An INNER JOIN can return data from the columns from both tables, and can duplicate values of records on either side have more than one match. A LEFT SEMI JOIN can only return columns from the left-hand table, and yields one of each record from the left-hand table where there is one or more matches in the right-hand table (regardless of the number of matches). It's equivalent to (in standard SQL):

SELECT name
FROM table_1 a
WHERE EXISTS(
    SELECT * FROM table_2 b WHERE (a.name=b.name))

If there are multiple matching rows in the right-hand column, an INNER JOIN will return one row for each match on the right table, while a LEFT SEMI JOIN only returns the rows from the left table, regardless of the number of matching rows on the right side. That's why you're seeing a different number of rows in your result.

I am trying to get the names within table_1 that only appear in table_2.

Then a LEFT SEMI JOIN is the appropriate query to use.

Could you explain STA and MTA?

STA (Single Threaded Apartment) is basically the concept that only one thread will interact with your code at a time. Calls into your apartment are marshaled via windows messages (using a non-visible) window. This allows calls to be queued and wait for operations to complete.

MTA (Multi Threaded Apartment) is where many threads can all operate at the same time and the onus is on you as the developer to handle the thread security.

There is a lot more to learn about threading models in COM, but if you are having trouble understanding what they are then I would say that understanding what the STA is and how it works would be the best starting place because most COM objects are STA’s.

Apartment Threads, if a thread lives in the same apartment as the object it is using then it is an apartment thread. I think this is only a COM concept because it is only a way of talking about the objects and threads they interact with…

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Some convenience functions:

public static void silentCloseResultSets(Statement st) {
    try {
        while (!(!st.getMoreResults() && (st.getUpdateCount() == -1))) {}
    } catch (SQLException ignore) {}
}
public static void silentCloseResultSets(Statement ...statements) {
    for (Statement st: statements) silentCloseResultSets(st);
}

jQuery UI autocomplete with JSON

I use this script for autocomplete...

$('#custmoers_name').autocomplete({
    source: function (request, response) {

        // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
          $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
          console.log(data);
            response($.map(data, function (value, key) {
                console.log(value);
                return {
                    label: value.label,
                    value: value.value
                };
            }));
        });
    },
    minLength: 1,
    delay: 100
});

My json return :- [{"label":"Mahesh Arun Wani","value":"1"}] after search m

but it display in dropdown [object object]...

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

The head command can get the first n lines. Variations are:

head -7 file
head -n 7 file
head -7l file

which will get the first 7 lines of the file called "file". The command to use depends on your version of head. Linux will work with the first one.

To append lines to the end of the same file, use:

echo 'first line to add' >>file
echo 'second line to add' >>file
echo 'third line to add' >>file

or:

echo 'first line to add
second line to add
third line to add' >>file

to do it in one hit.

So, tying these two ideas together, if you wanted to get the first 10 lines of the input.txt file to output.txt and append a line with five "=" characters, you could use something like:

( head -10 input.txt ; echo '=====' ) > output.txt

In this case, we do both operations in a sub-shell so as to consolidate the output streams into one, which is then used to create or overwrite the output file.

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

.col-xs-$   Extra Small     Phones Less than 768px 
.col-sm-$   Small Devices   Tablets 768px and Up 
.col-md-$   Medium Devices  Desktops 992px and Up 
.col-lg-$   Large Devices   Large Desktops 1200px and Up 

Centering floating divs within another div

In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

Then add all of your element's totaled widths together.

Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24

In this example the width for the "outer" div would be 112.

_x000D_
_x000D_
.outer {_x000D_
  /* floats + margins + borders = 270 */_x000D_
  max-width: 270px;_x000D_
  margin: auto;_x000D_
  height: 80px;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
    /* 3 floats x 50px = 150px */_x000D_
    width: 50px;_x000D_
    /* 6 margins x 10px = 60 */_x000D_
    margin: 10px;_x000D_
    /* 6 borders x 10px = 60 */_x000D_
    border: 10px solid #6B6B6B;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="myFloat">Float 1</div>_x000D_
  <div class="myFloat">Float 2</div>_x000D_
  <div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

I was able to get mine working using the following Client Credentials:

Authorized JavaScript origins

http://localhost

Authorized redirect URIs

http://localhost:8090/oauth2callback

Note: I used port 8090 instead of 8080, but that doesn't matter as long as your python script uses the same port as your client_secret.json file.

Reference: Python Quickstart

fatal error: mpi.h: No such file or directory #include <mpi.h>

You can execute:

$ mpicc -showme 

result :

gcc -I/Users/<USER_NAME>/openmpi-2.0.1/include -L/Users/<USER_NAME>/openmpi-2.0.1/lib -lmp

This command shows you the necessary libraries to compile mpicc

Example:

$ mpicc -g  -I/Users/<USER_NAME>/openmpi-2.0.1/include -o [nameExec] [objetcs.o...] [program.c] -lm


$ mpicc -g  -I/Users/<USER_NAME>/openmpi-2.0.1/include -o example file_object.o my_program.c otherlib.o -lm

this command generates executable with your program in example, you can execute :

$ ./example

Deploying website: 500 - Internal server error

For me, the following code in the web.config was the culprit. When I removed it, the web site worked fine.

  <staticContent>
    <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
  </staticContent>

How to pass arguments to a Button command in Tkinter?

Lambdas are all well and good, but you can also try this (which works in a for loop btw):

root = Tk()

dct = {"1": [*args], "2": [*args]}
def keypress(event):
    *args = dct[event.char]
    for arg in args:
        pass
for i in range(10):
    root.bind(str(i), keypress)

This works because when the binding is set, a key press passes the event as an argument. You can then call attributes off the event like event.char to get "1" or "UP" ect. If you need an argument or multiple arguments other than the event attributes. just create a dictionary to store them.

jQuery - setting the selected value of a select control via its text description

Very fiddly and nothing else seemed to work

$('select[name$="dropdown"]').children().text("Mr").prop("selected", true);

worked for me.

Link to "pin it" on pinterest without generating a button

The standard Pinterest button code (which you can generate here), is an <a> tag wrapping an <img> of the Pinterest button.

If you don't include the pinit.js script on your page, this <a> tag will work "as-is". You could improve the experience by registering your own click handler on these tags that opens a new window with appropriate dimensions, or at least adding target="_blank" to the tag to make it open clicks in a new window.

The tag syntax would look like:

<a href="http://pinterest.com/pin/create/button/?url={URI-encoded URL of the page to pin}&media={URI-encoded URL of the image to pin}&description={optional URI-encoded description}" class="pin-it-button" count-layout="horizontal">
    <img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" />
</a>

If using the JavaScript versions of sharing buttons are ruining your page load times, you can improve your site by using asynchronous loading methods. For an example of doing this with the Pinterest button, check out my GitHub Pinterest button project with an improved HTML5 syntax.

import error: 'No module named' *does* exist

I set the PYTHONPATH to '.' and that solved it for me.

export PYTHONPATH='.'

For a one-liner you could as easily do:

PYTHONPATH='.' your_python_script

These commands are expected to be run in a terminal

How do I get the entity that represents the current user in Symfony2?

The thread is a bit old but i think this could probably save someone's time ...

I ran into the same problem as the original question, that the type is showed as Symfony\Component\Security\Core\User\User

It eventually turned out that i was logged in using an in memory user

my security.yml looks something like this

security:
    providers:
        chain_provider:
            chain:
                providers: [in_memory, fos_userbundle]
        fos_userbundle:
            id: fos_user.user_manager
        in_memory:
            memory:
                users:
                    user:  { password: userpass, roles: [ 'ROLE_USER' ] }
                    admin: { password: adminpass, roles: [ 'ROLE_ADMIN', 'ROLE_SONATA_ADMIN' ] }

the in_memory user type is always Symfony\Component\Security\Core\User\User if you want to use your own entity, log in using that provider's user.

Thanks, hj

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

this helped me

git checkout -b newbranch
git checkout master
git merge newbranch
git branch -d newbranch

Read an Excel file directly from a R script

Given the proliferation of different ways to read an Excel file in R and the plethora of answers here, I thought I'd try to shed some light on which of the options mentioned here perform the best (in a few simple situations).

I myself have been using xlsx since I started using R, for inertia if nothing else, and I recently noticed there doesn't seem to be any objective information about which package works better.

Any benchmarking exercise is fraught with difficulties as some packages are sure to handle certain situations better than others, and a waterfall of other caveats.

That said, I'm using a (reproducible) data set that I think is in a pretty common format (8 string fields, 3 numeric, 1 integer, 3 dates):

set.seed(51423)
data.frame(
  str1 = sample(sprintf("%010d", 1:NN)), #ID field 1
  str2 = sample(sprintf("%09d", 1:NN)),  #ID field 2
  #varying length string field--think names/addresses, etc.
  str3 = 
    replicate(NN, paste0(sample(LETTERS, sample(10:30, 1L), TRUE),
                         collapse = "")),
  #factor-like string field with 50 "levels"
  str4 = sprintf("%05d", sample(sample(1e5, 50L), NN, TRUE)),
  #factor-like string field with 17 levels, varying length
  str5 = 
    sample(replicate(17L, paste0(sample(LETTERS, sample(15:25, 1L), TRUE),
                                 collapse = "")), NN, TRUE),
  #lognormally distributed numeric
  num1 = round(exp(rnorm(NN, mean = 6.5, sd = 1.5)), 2L),
  #3 binary strings
  str6 = sample(c("Y","N"), NN, TRUE),
  str7 = sample(c("M","F"), NN, TRUE),
  str8 = sample(c("B","W"), NN, TRUE),
  #right-skewed integer
  int1 = ceiling(rexp(NN)),
  #dates by month
  dat1 = 
    sample(seq(from = as.Date("2005-12-31"), 
               to = as.Date("2015-12-31"), by = "month"),
           NN, TRUE),
  dat2 = 
    sample(seq(from = as.Date("2005-12-31"), 
               to = as.Date("2015-12-31"), by = "month"),
           NN, TRUE),
  num2 = round(exp(rnorm(NN, mean = 6, sd = 1.5)), 2L),
  #date by day
  dat3 = 
    sample(seq(from = as.Date("2015-06-01"), 
               to = as.Date("2015-07-15"), by = "day"),
           NN, TRUE),
  #lognormal numeric that can be positive or negative
  num3 = 
    (-1) ^ sample(2, NN, TRUE) * round(exp(rnorm(NN, mean = 6, sd = 1.5)), 2L)
)

I then wrote this to csv and opened in LibreOffice and saved it as an .xlsx file, then benchmarked 4 of the packages mentioned in this thread: xlsx, openxlsx, readxl, and gdata, using the default options (I also tried a version of whether or not I specify column types, but this didn't change the rankings).

I'm excluding RODBC because I'm on Linux; XLConnect because it seems its primary purpose is not reading in single Excel sheets but importing entire Excel workbooks, so to put its horse in the race on only its reading capabilities seems unfair; and xlsReadWrite because it is no longer compatible with my version of R (seems to have been phased out).

I then ran benchmarks with NN=1000L and NN=25000L (resetting the seed before each declaration of the data.frame above) to allow for differences with respect to Excel file size. gc is primarily for xlsx, which I've found at times can create memory clogs. Without further ado, here are the results I found:

1,000-Row Excel File

benchmark1k <-
  microbenchmark(times = 100L,
                 xlsx = {xlsx::read.xlsx2(fl, sheetIndex=1); invisible(gc())},
                 openxlsx = {openxlsx::read.xlsx(fl); invisible(gc())},
                 readxl = {readxl::read_excel(fl); invisible(gc())},
                 gdata = {gdata::read.xls(fl); invisible(gc())})

# Unit: milliseconds
#      expr       min        lq      mean    median        uq       max neval
#      xlsx  194.1958  199.2662  214.1512  201.9063  212.7563  354.0327   100
#  openxlsx  142.2074  142.9028  151.9127  143.7239  148.0940  255.0124   100
#    readxl  122.0238  122.8448  132.4021  123.6964  130.2881  214.5138   100
#     gdata 2004.4745 2042.0732 2087.8724 2062.5259 2116.7795 2425.6345   100

So readxl is the winner, with openxlsx competitive and gdata a clear loser. Taking each measure relative to the column minimum:

#       expr   min    lq  mean median    uq   max
# 1     xlsx  1.59  1.62  1.62   1.63  1.63  1.65
# 2 openxlsx  1.17  1.16  1.15   1.16  1.14  1.19
# 3   readxl  1.00  1.00  1.00   1.00  1.00  1.00
# 4    gdata 16.43 16.62 15.77  16.67 16.25 11.31

We see my own favorite, xlsx is 60% slower than readxl.

25,000-Row Excel File

Due to the amount of time it takes, I only did 20 repetitions on the larger file, otherwise the commands were identical. Here's the raw data:

# Unit: milliseconds
#      expr        min         lq       mean     median         uq        max neval
#      xlsx  4451.9553  4539.4599  4738.6366  4762.1768  4941.2331  5091.0057    20
#  openxlsx   962.1579   981.0613   988.5006   986.1091   992.6017  1040.4158    20
#    readxl   341.0006   344.8904   347.0779   346.4518   348.9273   360.1808    20
#     gdata 43860.4013 44375.6340 44848.7797 44991.2208 45251.4441 45652.0826    20

Here's the relative data:

#       expr    min     lq   mean median     uq    max
# 1     xlsx  13.06  13.16  13.65  13.75  14.16  14.13
# 2 openxlsx   2.82   2.84   2.85   2.85   2.84   2.89
# 3   readxl   1.00   1.00   1.00   1.00   1.00   1.00
# 4    gdata 128.62 128.67 129.22 129.86 129.69 126.75

So readxl is the clear winner when it comes to speed. gdata better have something else going for it, as it's painfully slow in reading Excel files, and this problem is only exacerbated for larger tables.

Two draws of openxlsx are 1) its extensive other methods (readxl is designed to do only one thing, which is probably part of why it's so fast), especially its write.xlsx function, and 2) (more of a drawback for readxl) the col_types argument in readxl only (as of this writing) accepts some nonstandard R: "text" instead of "character" and "date" instead of "Date".

What is the string concatenation operator in Oracle?

It is ||, for example:

select 'Mr ' || ename from emp;

The only "interesting" feature I can think of is that 'x' || null returns 'x', not null as you might perhaps expect.

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

As of R2017b, this is not officially possible. The relevant documentation states that:

Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.

However, workarounds suggested in other answers can achieve something similar.

Recommended way to embed PDF in HTML?

To stream the file to the browser, see Stack Overflow question How to stream a PDF file as binary to the browser using .NET 2.0 - note that, with minor variations, this should work whether you're serving up a file from the file system or dynamically generated.

With that said, the referenced MSDN article takes a rather simplistic view of the world, so you may want to read Successfully Stream a PDF to browser through HTTPS as well for some of the headers you may need to supply.

Using that approach, an iframe is probably the best way to go. Have one webform that streams the file, and then put the iframe on another page with its src attribute set to the first form.

How to control size of list-style-type disc in CSS?

In modern browsers you can use the ::marker CSS pseudo-element like this:

.farParentDiv ul li::marker {
  font-size: 0.8em;
}

For browser support, please refer to: Can I Use ::marker pseudo-element

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

What's the best way to cancel event propagation between nested ng-click calls?

If you don't want to have to add the stop propagation to all links this works as well. A bit more scalable.

$scope.hideOverlay( $event ){

   // only hide the overlay if we click on the actual div
   if( $event.target.className.indexOf('overlay') ) 
      // hide overlay logic

}

jQuery: count number of rows in a table

Here's my take on it:

//Helper function that gets a count of all the rows <TR> in a table body <TBODY>
$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

USAGE:

var rowCount = $('#productTypesTable').rowCount();

java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. spark Eclipse on windows 7

Follow this:

  1. Create a bin folder in any directory(to be used in step 3).

  2. Download winutils.exe and place it in the bin directory.

  3. Now add System.setProperty("hadoop.home.dir", "PATH/TO/THE/DIR"); in your code.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

You could use both LTRIM and RTRIM.

select rtrim(ltrim('abcdab','ab'),'ab') from dual;

If you want to trim CHR(13) only when it comes with a CHR(10) it gets more complicated. Firstly, translated the combined string to a single character. Then LTRIM/RTRIM that character, then replace the single character back to the combined string.

select replace(rtrim(ltrim(replace('abccccabcccaab','ab','#'),'#'),'#'),'#','ab') from dual;

Changing column names of a data frame

If you need to rename not all but multiple column at once when you only know the old column names you can use colnames function and %in% operator. Example:

df = data.frame(bad=1:3, worse=rnorm(3), worst=LETTERS[1:3])

   bad      worse    worst
1   1 -0.77915455       A
2   2  0.06717385       B
3   3 -0.02827242       C

Now you want to change "bad" and "worst" to "good" and "best". You can use

colnames(df)[which(colnames(df) %in% c("bad","worst") )] <- c("good","best")

This results in

  good      worse  best
1    1 -0.6010363    A
2    2  0.7336155    B
3    3  0.9435469    C

Using a cursor with dynamic SQL in a stored procedure

First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:

There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction

Row-By-Row Processing Without Cursor

That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.

But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

If anyone got an error while signing in to Google and this message appear:

Couldn't Sign In
can't establish a reliable connection to the server...

then try to sign in from the browser - in YouTube, Gmail, Google sites, etc.

This helped me. After signing in in the browser I was able to sign in the Google Play app...

difference between primary key and unique key

A primary key must be unique.

A unique key does not have to be the primary key - see candidate key.

That is, there may be more than one combination of columns on a table that can uniquely identify a row - only one of these can be selected as the primary key. The others, though unique are candidate keys.

Fixing slow initial load for IIS

A good option to ping the site on a schedule is to use Microsoft Flow, which is free for up to 750 "runs" per month. It is very easy to create a Flow that hits your site every hour to keep it warm. You can even work around their limit of 750 by creating a single flow with delays separating multiple hits of your site.

https://flow.microsoft.com

Spring JUnit: How to Mock autowired component in autowired component

Another approach in integration testing is to define a new Configuration class and provide it as your @ContextConfiguration. Into the configuration you will be able to mock your beans and also you must define all types of beans which you are using in test/s flow. To provide an example :

@RunWith(SpringRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class MockTest{
 @Configuration
 static class ContextConfiguration{
 // ... you beans here used in test flow
 @Bean
    public MockMvc mockMvc() {
        return MockMvcBuilders.standaloneSetup(/*you can declare your controller beans defines on top*/)
                .addFilters(/*optionally filters*/).build();
    }
 //Defined a mocked bean
 @Bean
    public MyService myMockedService() {
        return Mockito.mock(MyService.class);
    }
 }

 @Autowired
 private MockMvc mockMvc;

 @Autowired
 MyService myMockedService;

 @Before
 public void setup(){
  //mock your methods from MyService bean 
  when(myMockedService.myMethod(/*params*/)).thenReturn(/*my answer*/);
 }

 @Test
 public void test(){
  //test your controller which trigger the method from MyService
  MvcResult result = mockMvc.perform(get(CONTROLLER_URL)).andReturn();
  // do your asserts to verify
 }
}

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

My work around for this problem has always been to use the principle that single hash temp tables are in scope to any called procs. So, I have an option switch in the proc parameters (default set to off). If this is switched on, the called proc will insert the results into the temp table created in the calling proc. I think in the past I have taken it a step further and put some code in the called proc to check if the single hash table exists in scope, if it does then insert the code, otherwise return the result set. Seems to work well - best way of passing large data sets between procs.

jquery: how to get the value of id attribute?

You can also try this way

<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>

jquery

$('.select_continent').click(function () {
alert($(this).data('value'));
});

Good luck !!!!

how to avoid a new line with p tag?

The <p> paragraph tag is meant for specifying paragraphs of text. If you don't want the text to start on a new line, I would suggest you're using the <p> tag incorrectly. Perhaps the <span> tag more closely fits what you want to achieve...?

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I solved the problem by changing the StartupType of the ssh-agent to Manual via Set-Service ssh-agent -StartupType Manual.

Then I was able to start the service via Start-Service ssh-agent or just ssh-agent.exe.

How to disable Django's CSRF validation?

If you want disable it in Global, you can write a custom middleware, like this

from django.utils.deprecation import MiddlewareMixin

class DisableCsrfCheck(MiddlewareMixin):

    def process_request(self, req):
        attr = '_dont_enforce_csrf_checks'
        if not getattr(req, attr, False):
            setattr(req, attr, True)

then add this class youappname.middlewarefilename.DisableCsrfCheck to MIDDLEWARE_CLASSES lists, before django.middleware.csrf.CsrfViewMiddleware

Difference between app.use and app.get in express.js

In addition to the above explanations, what I experience:

app.use('/book', handler);  

will match all requests beginning with '/book' as URL. so it also matches '/book/1' or '/book/2'

app.get('/book')  

matches only GET request with exact match. It will not handle URLs like '/book/1' or '/book/2'

So, if you want a global handler that handles all of your routes, then app.use('/') is the option. app.get('/') will handle only the root URL.

How to listen for 'props' changes

Not sure if you have resolved it (and if I understand correctly), but here's my idea:

If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).

Try this:

new Vue({
  el: '#app',
  data: {
    text: 'Hello'
  },
  components: {
    'parent': {
      props: ['myProp'],
      computed: {
        myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
      }
    },
    'child': {
      props: ['myProp'],
      watch: {
        myProp(val, oldval) { now val will differ from oldval }
      }
    }
  }
}

and in html:

<child :my-prop="myInnerProp"></child>

actually you have to be very careful when working on complex collections in such situations (passing down few times)

How to align td elements in center

margin:auto; text-align, if this won't work - try adding display:block; and set there width:200px; (in case your TD is too small).

Determine if JavaScript value is an "integer"?

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

Iterator Loop vs index loop

its a matter of speed. using the iterator accesses the elements faster. a similar question was answered here:

What's faster, iterating an STL vector with vector::iterator or with at()?

Edit: speed of access varies with each cpu and compiler

Create a new TextView programmatically then display it below another TextView

If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.

Complete code:

String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);        
for( int i = 0; i < textArray.length; i++ )
{
    TextView textView = new TextView(this);
    textView.setText(textArray[i]);
    linearLayout.addView(textView);
}

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.

export default function Component(props) {

function clickEvent (event, variable){
    console.log(variable);
}

return (
    <div>
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)} 
        >
    </div>
)
}

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want to list to exclude duplicates on one column only, inner join to a sub-select

select u.* [whatever joined values]
from users u
inner join
(select name from users group by name having count(*)=1) uniquenames
on uniquenames.name = u.name

Getting value of select (dropdown) before change

Use following code,I have tested it and its working

var prev_val;
$('.dropdown').focus(function() {
    prev_val = $(this).val();
}).change(function(){
            $(this).unbind('focus');
            var conf = confirm('Are you sure want to change status ?');

            if(conf == true){
                //your code
            }
            else{
                $(this).val(prev_val);
                $(this).bind('focus');
                return false;
            }
});

REST HTTP status codes for failed validation or invalid duplicate

406 - Not Acceptable

Which means this response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.

How are parameters sent in an HTTP POST request?

You cannot type it directly on the browser URL bar.

You can see how POST data is sent on the Internet with Live HTTP Headers for example. Result will be something like that

http://127.0.0.1/pass.php
POST /pass.php HTTP/1.1

Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1/pass.php
Cookie: passx=87e8af376bc9d9bfec2c7c0193e6af70; PHPSESSID=l9hk7mfh0ppqecg8gialak6gt5
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 30
username=zurfyx&pass=password

Where it says

Content-Length: 30
    username=zurfyx&pass=password

will be the post values.

Adding multiple class using ng-class

An incredibly powerful alternative to other answers here:

ng-class="[  { key: resulting-class-expression }[ key-matching-expression ], ..  ]"

Some examples:

1. Simply adds 'class1 class2 class3' to the div:

<div ng-class="[{true: 'class1'}[true], {true: 'class2 class3'}[true]]"></div>

2. Adds 'odd' or 'even' classes to div, depending on the $index:

<div ng-class="[{0:'even', 1:'odd'}[ $index % 2]]"></div>

3. Dynamically creates a class for each div based on $index

<div ng-class="[{true:'index'+$index}[true]]"></div>

If $index=5 this will result in:

<div class="index5"></div>

Here's a code sample you can run:

_x000D_
_x000D_
var app = angular.module('app', []); _x000D_
app.controller('MyCtrl', function($scope){_x000D_
  $scope.items = 'abcdefg'.split('');_x000D_
}); 
_x000D_
.odd  { background-color: #eee; }_x000D_
.even { background-color: #fff; }_x000D_
.index5 {background-color: #0095ff; color: white; font-weight: bold; }_x000D_
* { font-family: "Courier New", Courier, monospace; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="app" ng-controller="MyCtrl">_x000D_
  <div ng-repeat="item in items"_x000D_
    ng-class="[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]]">_x000D_
    index {{$index}} = "{{item}}" ng-class="{{[{true:'index'+$index}[true], {0:'even', 1:'odd'}[ $index % 2 ]].join(' ')}}"_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jQuery form validation on button click

$(document).ready(function() {
    $("#form1").validate({
        rules: {
            field1: "required"
        },
        messages: {
            field1: "Please specify your name"
        }
    })
});

<form id="form1" name="form1">
     Field 1: <input id="field1" type="text" class="required">
    <input id="btn" type="submit" value="Validate">
</form>

You are also you using type="button". And I'm not sure why you ought to separate the submit button, place it within the form. It's more proper to do it that way. This should work.

Redirecting to a page after submitting form in HTML

You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.

Example:

 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      window.location.href = 'https://website.com/my-account';
    }
  };
  xhttp.open("POST", "demo_post.asp", true);
  xhttp.send();

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

How to bind a List to a ComboBox?

If you are using a ToolStripComboBox there is no DataSource exposed (.NET 4.0):

List<string> someList = new List<string>();
someList.Add("value");
someList.Add("value");
someList.Add("value");

toolStripComboBox1.Items.AddRange(someList.ToArray());

Print specific part of webpage

You can use simple JavaScript to print a specific div from a page.

var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

destination path already exists and is not an empty directory

An engineered way to solve this if you already have files you need to push to Github/Server:

  1. In Github/Server where your repo will live:

    • Create empty Git Repo (Save <YourPathAndRepoName>)
    • $git init --bare
  2. Local Computer (Just put in any folder):

    • $touch .gitignore
    • (Add files you want to ignore in text editor to .gitignore)
    • $git clone <YourPathAndRepoName>

    • (This will create an empty folder with your Repo Name from Github/Server)

    • (Legitimately copy and paste all your files from wherever and paste them into this empty Repo)

    • $git add . && git commit -m "First Commit"

    • $git push origin master

What is C# analog of C++ std::pair?

Depending on what you want to accomplish, you might want to try out KeyValuePair.

The fact that you cannot change the key of an entry can of course be rectified by simply replacing the entire entry by a new instance of KeyValuePair.

How to iterate through LinkedHashMap with lists as values

for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
    String key = entry.getKey();
    ArrayList<String> value = entry.getValue();
    // now work with key and value...
}

By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.

Using strtok with a std::string

I suppose the language is C, or C++...

strtok, IIRC, replace separators with \0. That's what it cannot use a const string. To workaround that "quickly", if the string isn't huge, you can just strdup() it. Which is wise if you need to keep the string unaltered (what the const suggest...).

On the other hand, you might want to use another tokenizer, perhaps hand rolled, less violent on the given argument.

How to create a dotted <hr/> tag?

You can do:

<hr style="border-bottom: dotted 1px #000" />

Get commit list between tags in git

FYI:

git log tagA...tagB

provides standard log output in a range.

What is a singleton in C#?

Whilst the there can only ever be one instance of a singleton, it is not the same as a static class. A static class can only contain static methods and can never be instantiated, whereas the instance of a singleton may be used in the same way as any other object.

Javascript Get Element by Id and set the value

For each element type, you can use specific attribute to set value. E.g.:

<div id="theValue1"></div>
window.document.getElementById("theValue1").innerText = "value div";

<input id="theValue2"></input>
window.document.getElementById("theValue2").value = "value input";

You can try example here!

System.out.println() shortcut on Intellij IDEA

Open up Settings (By default is Alt + Ctrl + S) and search for Live Templates. In the upper part there's an option that says "By default expand with TAB" (TAB is the default), choose "Custom" and then hit "change" and add the keymap "ctrl+spacebar" to the option "Expand Live Template/Emmet Abbreviation".

Now you can hit ctrl + spacebar and expand the live templates. Now, to change it to "syso" instead of "sout", in the Live Templates option, theres a list of tons of options checked, go to "other" and expand it, there you wil find "sout", just rename it to "syso" and hit aply.

Hope this can help you.

Simple Java Client/Server Program

It's probably a firewall issue. Make sure you port forward the port you want to connect to on the server side. localhost maps directly to an ip and also moves through your network stack. You're changing some text in your code but the way your program is working is fundamentally the same.

Timeout for python requests.get entire response

I came up with a more direct solution that is admittedly ugly but fixes the real problem. It goes a bit like this:

resp = requests.get(some_url, stream=True)
resp.raw._fp.fp._sock.settimeout(read_timeout)
# This will load the entire response even though stream is set
content = resp.content

You can read the full explanation here

String array initialization in Java

First up, this has got nothing to do with String, it is about arrays.. and that too specifically about declarative initialization of arrays.

As discussed by everyone in almost every answer here, you can, while declaring a variable, use:

String names[] = {"x","y","z"};

However, post declaration, if you want to assign an instance of an Array:

names = new String[] {"a","b","c"};

AFAIK, the declaration syntax is just a syntactic sugar and it is not applicable anymore when assigning values to variables because when values are assigned you need to create an instance properly.

However, if you ask us why it is so? Well... good luck getting an answer to that. Unless someone from the Java committee answers that or there is explicit documentation citing the said syntactic sugar.

Force Intellij IDEA to reread all maven dependencies

In the latest IntelliJ IDEA version (2020.1.3 Ultimate Edition), You need to to click this little guy that appears on the top right of the editor window after you make a change to the pom.xml

This little guy is too small and in an unnoticeable position. I liked the previous versions where an alert shows up in the bottom right. Still can't find the option to enable auto import in this version.

enter image description here

Batch: Remove file extension

In case the file your variable holds doesn't actually exist the FOR approach won't work. One trick you could use, if you know the length of the extension, is taking a substring:

%var:~0,-4%

the -4 means that the last 4 digits (presumably .ext) will be truncated.

How to add elements to an empty array in PHP?

You can use array_push. It adds the elements to the end of the array, like in a stack.

You could have also done it like this:

$cart = array(13, "foo", $obj);

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

SQL Server loop - how do I loop through a set of records

I think this is the easy way example to iterate item.

declare @cateid int
select CateID into [#TempTable] from Category where GroupID = 'STOCKLIST'

while (select count(*) from #TempTable) > 0
begin
    select top 1 @cateid = CateID from #TempTable
    print(@cateid)

    --DO SOMETHING HERE

    delete #TempTable where CateID = @cateid
end

drop table #TempTable

how to print an exception using logger?

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

You should simply apply the following transformation to your input data array.

input_data = input_data.reshape((-1, image_side1, image_side2, channels))

How to log as much information as possible for a Java Exception?

The java.util.logging package is standard in Java SE. Its Logger includes an overloaded log method that accepts Throwable objects. It will log stacktraces of exceptions and their cause for you.

For example:

import java.util.logging.Level;
import java.util.logging.Logger;

[...]

Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "an exception was thrown", e2);

Will log:

SEVERE: an exception was thrown
java.lang.Exception: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:21)
Caused by: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:20)

Internally, this does exactly what @philipp-wendler suggests, by the way. See the source code for SimpleFormatter.java. This is just a higher level interface.

Destroy or remove a view in Backbone.js

According to current Backbone documentation....

view.remove()

Removes a view and its el from the DOM, and calls stopListening to remove any bound events that the view has listenTo'd.

Microsoft.ACE.OLEDB.12.0 is not registered

Summarized: INSTALL 32 bit version of Microsoft Access Database Engine 2010 Redistributable. Uninstall 64 bit version if previously installed. http://www.microsoft.com/en-us/download/details.aspx?id=13255

The Excel connection manager is trying to use the ACE OLE DB provider in order to access the Excel file when the version is above 2007 (xlsx). Although your box is 64-bit, you’re using SQL Server Data Tools, which is a 32-bit application. There is no 64-bit version for SSDT. When you design your package within SSDT, you’re using a 32-bit process, which can only use 32-bit providers. When you try to choose the table in the Excel file, the connection manager needs to access the 32-bit version of the ACE OLE DB provider, but this provider is not registered on your machine, only the 64-bit version is installed.

You should download the 32-bit version of the “Microsoft Access Database Engine 2010 Redistributable”. When you try to install it, you might get an error message. You should first uninstall only the 64-bit version of the “Microsoft Access Database Engine 2010 Redistributable”, which you probably installed previously. The 64-bit version and the 32-bit version can’t live together on the same host, so you’ll have to uninstall (through “Program and Features”) and install the other one if you wish to switch between them.

Once you finish uninstalling the 64-bit version and installing the 32-bit version of the provider, the problem is solved, and you can finally choose the table within the Excel file. The Excel connection manager is now able to use the ACE OLE DB provider (32-bit version) in order to access the Excel file.

Uncaught Typeerror: cannot read property 'innerHTML' of null

//Run with this HTML structure
<!DOCTYPE html>
<head>
    <title>OOJS</title>

</head>
<body>
    <div id="status">
    </div>
    <script type="text/javascript" src="scriptfile.js"></script>
</body>
</html>

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

EF Migrations: Rollback last applied migration?

In case there is a possibility for dataloss EF does not complete the update-database command since AutomaticMigrationDataLossAllowed = false by default, and roolbacks the action unless you run it with the -force parameter.

Update-Database –TargetMigration:"Your migration name" -force

or

Update-Database –TargetMigration:Your_Migration_Index -force

Count of "Defined" Array Elements

No, the only way to know how many elements are not undefined is to loop through and count them. That doesn't mean you have to write the loop, though, just that something, somewhere has to do it. (See #3 below for why I added that caveat.)

How you loop through and count them is up to you. There are lots of ways:

  1. A standard for loop from 0 to arr.length - 1 (inclusive).
  2. A for..in loop provided you take correct safeguards.
  3. Any of several of the new array features from ECMAScript5 (provided you're using a JavaScript engine that supports them, or you've included an ES5 shim, as they're all shim-able), like some, filter, or reduce, passing in an appropriate function. This is handy not only because you don't have to explicitly write the loop, but because using these features gives the JavaScript engine the opportunity to optimize the loop it does internally in various ways. (Whether it actually does will vary on the engine.)

...but it all amounts to looping, either explicitly or (in the case of the new array features) implicitly.

how to implement a long click listener on a listview

In xml add

<ListView android:longClickable="true">

In java file

lv.setLongClickable(true) 

try this setOnItemLongClickListener()

lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long l) {
                //final String category = "Position at : "+pos;
                final String category = ((TextView) view.findViewById(R.id.textView)).getText().toString();
                Toast.makeText(getActivity(),""+category,Toast.LENGTH_LONG).show();
                args = new Bundle();
                args.putString("category", category);
                return false;
            }
        });

dotnet ef not found in .NET Core 3

if your using snap package dotnet-sdk on linux this can resolve by updating your ~.bashrc / etc. as follows:

#!/bin/bash
export DOTNET_ROOT=/snap/dotnet-sdk/current
export MSBuildSDKsPath=$DOTNET_ROOT/sdk/$(${DOTNET_ROOT}/dotnet --version)/Sdks
export PATH="${PATH}:${DOTNET_ROOT}"
export PATH="$PATH:$HOME/.dotnet/tools"

What is stability in sorting algorithms and why is it important?

Sorting stability means that records with the same key retain their relative order before and after the sort.

So stability matters if, and only if, the problem you're solving requires retention of that relative order.

If you don't need stability, you can use a fast, memory-sipping algorithm from a library, like heapsort or quicksort, and forget about it.

If you need stability, it's more complicated. Stable algorithms have higher big-O CPU and/or memory usage than unstable algorithms. So when you have a large data set, you have to pick between beating up the CPU or the memory. If you're constrained on both CPU and memory, you have a problem. A good compromise stable algorithm is a binary tree sort; the Wikipedia article has a pathetically easy C++ implementation based on the STL.

You can make an unstable algorithm into a stable one by adding the original record number as the last-place key for each record.

How do I store and retrieve a blob from sqlite?

You need to use sqlite's prepared statements interface. Basically, the idea is that you prepare a statement with a placeholder for your blob, then use one of the bind calls to "bind" your data...

SQLite Prepared Statements

jQuery selector for id starts with specific text

Add a common class to all the div. For example add foo to all the divs.

$('.foo').each(function () {
   $(this).dialog({
    autoOpen: false,
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "explode",
      duration: 1000
    }
  });
});

NULL value for int in Update statement

If this is nullable int field then yes.

update TableName
set FiledName = null
where Id = SomeId

TypeError: ObjectId('') is not JSON serializable

If you will not be needing the _id of the records I will recommend unsetting it when querying the DB which will enable you to print the returned records directly e.g

To unset the _id when querying and then print data in a loop you write something like this

records = mycollection.find(query, {'_id': 0}) #second argument {'_id':0} unsets the id from the query
for record in records:
    print(record)

How to download image using requests

I have the same need for downloading images using requests. I first tried the answer of Martijn Pieters, and it works well. But when I did a profile on this simple function, I found that it uses so many function calls compared to urllib and urllib2.

I then tried the way recommended by the author of requests module:

import requests
from PIL import Image
# python2.x, use this instead  
# from StringIO import StringIO
# for python3.x,
from io import StringIO

r = requests.get('https://example.com/image.jpg')
i = Image.open(StringIO(r.content))

This much more reduced the number of function calls, thus speeded up my application. Here is the code of my profiler and the result.

#!/usr/bin/python
import requests
from StringIO import StringIO
from PIL import Image
import profile

def testRequest():
    image_name = 'test1.jpg'
    url = 'http://example.com/image.jpg'

    r = requests.get(url, stream=True)
    with open(image_name, 'wb') as f:
        for chunk in r.iter_content():
            f.write(chunk)

def testRequest2():
    image_name = 'test2.jpg'
    url = 'http://example.com/image.jpg'

    r = requests.get(url)

    i = Image.open(StringIO(r.content))
    i.save(image_name)

if __name__ == '__main__':
    profile.run('testUrllib()')
    profile.run('testUrllib2()')
    profile.run('testRequest()')

The result for testRequest:

343080 function calls (343068 primitive calls) in 2.580 seconds

And the result for testRequest2:

3129 function calls (3105 primitive calls) in 0.024 seconds

Dynamically load a function from a DLL

This is not exactly a hot topic, but I have a factory class that allows a dll to create an instance and return it as a DLL. It is what I came looking for but couldn't find exactly.

It is called like,

IHTTP_Server *server = SN::SN_Factory<IHTTP_Server>::CreateObject();
IHTTP_Server *server2 =
      SN::SN_Factory<IHTTP_Server>::CreateObject(IHTTP_Server_special_entry);

where IHTTP_Server is the pure virtual interface for a class created either in another DLL, or the same one.

DEFINE_INTERFACE is used to give a class id an interface. Place inside interface;

An interface class looks like,

class IMyInterface
{
    DEFINE_INTERFACE(IMyInterface);

public:
    virtual ~IMyInterface() {};

    virtual void MyMethod1() = 0;
    ...
};

The header file is like this

#if !defined(SN_FACTORY_H_INCLUDED)
#define SN_FACTORY_H_INCLUDED

#pragma once

The libraries are listed in this macro definition. One line per library/executable. It would be cool if we could call into another executable.

#define SN_APPLY_LIBRARIES(L, A)                          \
    L(A, sn, "sn.dll")                                    \
    L(A, http_server_lib, "http_server_lib.dll")          \
    L(A, http_server, "")

Then for each dll/exe you define a macro and list its implementations. Def means that it is the default implementation for the interface. If it is not the default, you give a name for the interface used to identify it. Ie, special, and the name will be IHTTP_Server_special_entry.

#define SN_APPLY_ENTRYPOINTS_sn(M)                                     \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, def)                   \
    M(IHTTP_Handler, SNI::SNI_HTTP_Handler, sn, special)

#define SN_APPLY_ENTRYPOINTS_http_server_lib(M)                        \
    M(IHTTP_Server, HTTP::server::server, http_server_lib, def)

#define SN_APPLY_ENTRYPOINTS_http_server(M)

With the libraries all setup, the header file uses the macro definitions to define the needful.

#define APPLY_ENTRY(A, N, L) \
    SN_APPLY_ENTRYPOINTS_##N(A)

#define DEFINE_INTERFACE(I) \
    public: \
        static const long Id = SN::I##_def_entry; \
    private:

namespace SN
{
    #define DEFINE_LIBRARY_ENUM(A, N, L) \
        N##_library,

This creates an enum for the libraries.

    enum LibraryValues
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_ENUM, "")
        LastLibrary
    };

    #define DEFINE_ENTRY_ENUM(I, C, L, D) \
        I##_##D##_entry,

This creates an enum for interface implementations.

    enum EntryValues
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_ENUM)
        LastEntry
    };

    long CallEntryPoint(long id, long interfaceId);

This defines the factory class. Not much to it here.

    template <class I>
    class SN_Factory
    {
    public:
        SN_Factory()
        {
        }

        static I *CreateObject(long id = I::Id )
        {
            return (I *)CallEntryPoint(id, I::Id);
        }
    };
}

#endif //SN_FACTORY_H_INCLUDED

Then the CPP is,

#include "sn_factory.h"

#include <windows.h>

Create the external entry point. You can check that it exists using depends.exe.

extern "C"
{
    __declspec(dllexport) long entrypoint(long id)
    {
        #define CREATE_OBJECT(I, C, L, D) \
            case SN::I##_##D##_entry: return (int) new C();

        switch (id)
        {
            SN_APPLY_CURRENT_LIBRARY(APPLY_ENTRY, CREATE_OBJECT)
        case -1:
        default:
            return 0;
        }
    }
}

The macros set up all the data needed.

namespace SN
{
    bool loaded = false;

    char * libraryPathArray[SN::LastLibrary];
    #define DEFINE_LIBRARY_PATH(A, N, L) \
        libraryPathArray[N##_library] = L;

    static void LoadLibraryPaths()
    {
        SN_APPLY_LIBRARIES(DEFINE_LIBRARY_PATH, "")
    }

    typedef long(*f_entrypoint)(long id);

    f_entrypoint libraryFunctionArray[LastLibrary - 1];
    void InitlibraryFunctionArray()
    {
        for (long j = 0; j < LastLibrary; j++)
        {
            libraryFunctionArray[j] = 0;
        }

        #define DEFAULT_LIBRARY_ENTRY(A, N, L) \
            libraryFunctionArray[N##_library] = &entrypoint;

        SN_APPLY_CURRENT_LIBRARY(DEFAULT_LIBRARY_ENTRY, "")
    }

    enum SN::LibraryValues libraryForEntryPointArray[SN::LastEntry];
    #define DEFINE_ENTRY_POINT_LIBRARY(I, C, L, D) \
            libraryForEntryPointArray[I##_##D##_entry] = L##_library;
    void LoadLibraryForEntryPointArray()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_POINT_LIBRARY)
    }

    enum SN::EntryValues defaultEntryArray[SN::LastEntry];
        #define DEFINE_ENTRY_DEFAULT(I, C, L, D) \
            defaultEntryArray[I##_##D##_entry] = I##_def_entry;

    void LoadDefaultEntries()
    {
        SN_APPLY_LIBRARIES(APPLY_ENTRY, DEFINE_ENTRY_DEFAULT)
    }

    void Initialize()
    {
        if (!loaded)
        {
            loaded = true;
            LoadLibraryPaths();
            InitlibraryFunctionArray();
            LoadLibraryForEntryPointArray();
            LoadDefaultEntries();
        }
    }

    long CallEntryPoint(long id, long interfaceId)
    {
        Initialize();

        // assert(defaultEntryArray[id] == interfaceId, "Request to create an object for the wrong interface.")
        enum SN::LibraryValues l = libraryForEntryPointArray[id];

        f_entrypoint f = libraryFunctionArray[l];
        if (!f)
        {
            HINSTANCE hGetProcIDDLL = LoadLibraryA(libraryPathArray[l]);

            if (!hGetProcIDDLL) {
                return NULL;
            }

            // resolve function address here
            f = (f_entrypoint)GetProcAddress(hGetProcIDDLL, "entrypoint");
            if (!f) {
                return NULL;
            }
            libraryFunctionArray[l] = f;
        }
        return f(id);
    }
}

Each library includes this "cpp" with a stub cpp for each library/executable. Any specific compiled header stuff.

#include "sn_pch.h"

Setup this library.

#define SN_APPLY_CURRENT_LIBRARY(L, A) \
    L(A, sn, "sn.dll")

An include for the main cpp. I guess this cpp could be a .h. But there are different ways you could do this. This approach worked for me.

#include "../inc/sn_factory.cpp"

How can I find the current OS in Python?

https://docs.python.org/library/os.html

To complement Greg's post, if you're on a posix system, which includes MacOS, Linux, Unix, etc. you can use os.uname() to get a better feel for what kind of system it is.

How to restart adb from root to user mode?

For quick steps just check summary. If interested to know details, go on to read below.

adb is a daemon. Doing ps adb we can see its process.

shell@grouper:/ $ ps adb
USER     PID   PPID  VSIZE  RSS     WCHAN    PC        NAME
shell     133   1     4636   212   ffffffff 00000000 S /sbin/adbd

I just checked what additional property variables it is using when adb is running as root and user.

adb user mode :

shell@grouper:/ $ getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

adb root mode :

shell@grouper:/ # getprop | grep adb                                         
[init.svc.adbd]: [running]
[persist.sys.usb.config]: [mtp,adb]
[ro.adb.secure]: [1]
[service.adb.root]: [1]
[sys.usb.config]: [mtp,adb]
[sys.usb.state]: [mtp,adb]

We can see that service.adb.root is a new prop variable that came up when we did adb root.

So, to change back adb to user from root, I went ahead and made this 0

setprop service.adb.root 0

But this did not change anything.

Then I went ahead and killed the process (with an intention to restart the process). The pid of adbd process in my device is 133

kill -9 133

I exited from shell automatically after I had killed the process.

I did adb shell again it was in user mode.

SUMMARY :

So, we have 3 very simple steps.

  1. Enter adb shell as a root.
  2. setprop service.adb.root 0
  3. kill -9 (pid of adbd)

After these steps just re-enter the shell with adb shell and you are back on your device as a user.

Take multiple lists into dataframe

Adding one more scalable solution.

lists = [lst1, lst2, lst3, lst4]
df = pd.concat([pd.Series(x) for x in lists], axis=1)

How to use (install) dblink in PostgreSQL?

Installing modules usually requires you to run an sql script that is included with the database installation.

Assuming linux-like OS

find / -name dblink.sql

Verify the location and run it

How to select bottom most rows?

SELECT
    columns
FROM
(
     SELECT TOP 200
          columns
     FROM
          My_Table
     ORDER BY
          a_column DESC
) SQ
ORDER BY
     a_column ASC

List of special characters for SQL LIKE clause

Sybase :

%              : Matches any string of zero or more characters.
_              : Matches a single character.
[specifier]    : Brackets enclose ranges or sets, such as [a-f] 
                 or [abcdef].Specifier  can take two forms:

                 rangespec1-rangespec2: 
                   rangespec1 indicates the start of a range of characters.
                   - is a special character, indicating a range.
                   rangespec2 indicates the end of a range of characters.

                 set: 
                  can be composed of any discrete set of values, in any 
                  order, such as [a2bR].The range [a-f], and the 
                  sets [abcdef] and [fcbdae] return the same 
                  set of values.

                 Specifiers are case-sensitive.

[^specifier]    : A caret (^) preceding a specifier indicates 
                  non-inclusion. [^a-f] means "not in the range 
                  a-f"; [^a2bR] means "not a, 2, b, or R."

How to find and replace all occurrences of a string recursively in a directory tree?

Try this:

grep -rl 'SearchString' ./ | xargs sed -i 's/REPLACESTRING/WITHTHIS/g'

grep -rl will recursively search for the SEARCHSTRING in the directories ./ and will replace the strings using sed.

Ex:

Replacing a name TOM with JERRY using search string as SWATKATS in directory CARTOONNETWORK

grep -rl 'SWATKATS' CARTOONNETWORK/ | xargs sed -i 's/TOM/JERRY/g'

This will replace TOM with JERRY in all the files and subdirectories under CARTOONNETWORK wherever it finds the string SWATKATS.

Can a background image be larger than the div itself?

Not really - the background image is bounded by the element it's applied to, and the overflow properties only apply to the content (i.e. markup) within an element.

You can add another div into your footer div and apply the background image to that, though, and have that overflow instead.

Definition of "downstream" and "upstream"

That's a bit of informal terminology.

As far as Git is concerned, every other repository is just a remote.

Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.

The terms are not restricted to Git repositories.

For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.

Calling a rest api with username and password - how to

If the API says to use HTTP Basic authentication, then you need to add an Authorization header to your request. I'd alter your code to look like this:

    WebRequest req = WebRequest.Create(@"https://sub.domain.com/api/operations?param=value&param2=value");
    req.Method = "GET";
    req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("username:password"));
    //req.Credentials = new NetworkCredential("username", "password");
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

Replacing "username" and "password" with the correct values, of course.

Add 2 hours to current time in MySQL?

SELECT * FROM courses WHERE (NOW() + INTERVAL 2 HOUR) > start_time

Connecting PostgreSQL 9.2.1 with Hibernate

This is the hibernate.cfg.xml file to connect postgresql 9.5 and this is help to you basic configuration.

 <?xml version='1.0' encoding='utf-8'?>

<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-configuration SYSTEM
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration
>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://localhost:5433/hibernatedb</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">password</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>
        <mapping class="com.waseem.UserDetails"/>
    </session-factory>
</hibernate-configuration>

Make sure File Location should be under src/main/resources/hibernate.cfg.xml

How do I change the font-size of an <option> element within <select>?

One solution could be to wrap the options inside optgroup:

_x000D_
_x000D_
optgroup { font-size:40px; }
_x000D_
<select>
  <optgroup>
    <option selected="selected" class="service-small">Service area?</option>
    <option class="service-small">Volunteering</option>
    <option class="service-small">Partnership &amp; Support</option>
    <option class="service-small">Business Services</option>
  </optgroup>
</select>
_x000D_
_x000D_
_x000D_

How to convert an array to a string in PHP?

Using implode(), you can turn the array into a string.

$str = implode(',', $array); // 33160,33280,33180,...

Encrypt and Decrypt in Java

KeyGenerator is used to generate keys

You may want to check KeySpec, SecretKey and SecretKeyFactory classes

http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/package-summary.html

javascript createElement(), style problem

Others have given you the answer about appendChild.

Calling document.write() on a page that is not open (e.g. has finished loading) first calls document.open() which clears the entire content of the document (including the script calling document.write), so it's rarely a good idea to do that.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

How to use classes from .jar files?

As workmad3 says, you need the jar file to be in your classpath. If you're compiling from the commandline, that will mean using the -classpath flag. (Avoid the CLASSPATH environment variable; it's a pain in the neck IMO.)

If you're using an IDE, please let us know which one and we can help you with the steps specific to that IDE.

Git commit in terminal opens VIM, but can't get back to terminal

To save your work and exit press Esc and then :wq (w for write and q for quit).

Alternatively, you could both save and exit by pressing Esc and then :x

To set another editor run export EDITOR=myFavoriteEdioron your terminal, where myFavoriteEdior can be vi, gedit, subl(for sublime) etc.

How to check if cursor exists (open status)

This happened to me when a stored procedure running in SSMS encountered an error during the loop, while the cursor was in use to iterate over records and before the it was closed. To fix it I added extra code in the CATCH block to close the cursor if it is still open (using CURSOR_STATUS as other answers here suggest).

Embed a PowerPoint presentation into HTML

Another option is to use Apple Keynote on a Mac (Libre Office couldn't event open a pptx I had) to save the presentation to HTML5. It does a pretty good job to produce exactly what it displays in keynote, e.g. it includes animations and video. Compatibility of keynote to powerpoint has it's limits though (independent of the export).

What is the quickest way to HTTP GET in Python?

theller's solution for wget is really useful, however, i found it does not print out the progress throughout the downloading process. It's perfect if you add one line after the print statement in reporthook.

import sys, urllib

def reporthook(a, b, c):
    print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
    sys.stdout.flush()
for url in sys.argv[1:]:
    i = url.rfind("/")
    file = url[i+1:]
    print url, "->", file
    urllib.urlretrieve(url, file, reporthook)
print

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

How to select a CRAN mirror in R

Repository selection screen cannot be shown on your system (OS X), since OS X no longer includes X11. R tries to show you the prompt through X11. Install X11 from http://xquartz.macosforge.org/landing/. Then run the install command. The repo selection prompt will be shown.

Query Mongodb on month, day, year... of a datetime

Use the $expr operator which allows the use of aggregation expressions within the query language. This will give you the power to use the Date Aggregation Operators in your query as follows:

month = 11
db.mydatabase.mycollection.find({ 
    "$expr": { 
        "$eq": [ { "$month": "$date" }, month ] 
    } 
})

or

day = 17
db.mydatabase.mycollection.find({ 
    "$expr": { 
        "$eq": [ { "$dayOfMonth": "$date" }, day ] 
    } 
})

You could also run an aggregate operation with the aggregate() function that takes in a $redact pipeline:

month = 11
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [ { "$month": "$date" }, month ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

For the other request

day = 17
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { "$eq": [ { "$dayOfMonth": "$date" }, day ] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

Using OR

month = 11
day = 17
db.mydatabase.mycollection.aggregate([
    {
        "$redact": {
            "$cond": [
                { 
                    "$or": [ 
                        { "$eq": [ { "$month": "$date" }, month ] },
                        { "$eq": [ { "$dayOfMonth": "$date" }, day ] }
                    ] 
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

Using AND

var month = 11,
    day = 17;
db.collection.aggregate([
    {
        "$redact": {
            "$cond": [
                { 
                    "$and": [ 
                        { "$eq": [ { "$month": "$createdAt" }, month ] },
                        { "$eq": [ { "$dayOfMonth": "$createdAt" }, day ] }
                    ] 
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    }
])

The $redact operator incorporates the functionality of $project and $match pipeline and will return all documents match the condition using $$KEEP and discard from the pipeline those that don't match using the $$PRUNE variable.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

HAS RELATION TYPE:


Don't try to instantiate the collection when it's declared in hasMany, just add and remove objects.

class Parent {
    static hasMany = [childs:Child]
}

USE RELATION TYPE:


But the collection could be null only when is declared as a property (use relation) and is not initialized in declaration.

class Parent {
    List<Child> childs = []
}

Write string to text file and ensure it always overwrites the existing content.

Generally, FileMode.Create is what you're looking for.

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

What is the difference between signed and unsigned int

Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

Should MySQL have its timezone set to UTC?

It seems that it does not matter what timezone is on the server as long as you have the time set right for the current timezone, know the timezone of the datetime columns that you store, and are aware of the issues with daylight savings time.

On the other hand if you have control of the timezones of the servers you work with then you can have everything set to UTC internally and never worry about timezones and DST.

Here are some notes I collected of how to work with timezones as a form of cheatsheet for myself and others which might influence what timezone the person will choose for his/her server and how he/she will store date and time.

MySQL Timezone Cheatsheet

Notes:

  1. Changing the timezone will not change the stored datetime or timestamp, but it will select a different datetime from timestamp columns
  2. Warning! UTC has leap seconds, these look like '2012-06-30 23:59:60' and can be added randomly, with 6 months prior notice, due to the slowing of the earths rotation
  3. GMT confuses seconds, which is why UTC was invented.

  4. Warning! different regional timezones might produce the same datetime value due to daylight savings time

  5. The timestamp column only supports dates 1970-01-01 00:00:01 to 2038-01-19 03:14:07 UTC, due to a limitation.
  6. Internally a MySQL timestamp column is stored as UTC but when selecting a date MySQL will automatically convert it to the current session timezone.

    When storing a date in a timestamp, MySQL will assume that the date is in the current session timezone and convert it to UTC for storage.

  7. MySQL can store partial dates in datetime columns, these look like "2013-00-00 04:00:00"
  8. MySQL stores "0000-00-00 00:00:00" if you set a datetime column as NULL, unless you specifically set the column to allow null when you create it.
  9. Read this

To select a timestamp column in UTC format

no matter what timezone the current MySQL session is in:

SELECT 
CONVERT_TZ(`timestamp_field`, @@session.time_zone, '+00:00') AS `utc_datetime` 
FROM `table_name`

You can also set the sever or global or current session timezone to UTC and then select the timestamp like so:

SELECT `timestamp_field` FROM `table_name`

To select the current datetime in UTC:

SELECT UTC_TIMESTAMP();
SELECT UTC_TIMESTAMP;
SELECT CONVERT_TZ(NOW(), @@session.time_zone, '+00:00');

Example result: 2015-03-24 17:02:41

To select the current datetime in the session timezone

SELECT NOW();
SELECT CURRENT_TIMESTAMP;
SELECT CURRENT_TIMESTAMP();

To select the timezone that was set when the server launched

SELECT @@system_time_zone;

Returns "MSK" or "+04:00" for Moscow time for example, there is (or was) a MySQL bug where if set to a numerical offset it would not adjust the Daylight savings time

To get the current timezone

SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);

It will return 02:00:00 if your timezone is +2:00.

To get the current UNIX timestamp (in seconds):

SELECT UNIX_TIMESTAMP(NOW());
SELECT UNIX_TIMESTAMP();

To get the timestamp column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(`timestamp`) FROM `table_name`

To get a UTC datetime column as a UNIX timestamp

SELECT UNIX_TIMESTAMP(CONVERT_TZ(`utc_datetime`, '+00:00', @@session.time_zone)) FROM `table_name`

Get a current timezone datetime from a positive UNIX timestamp integer

SELECT FROM_UNIXTIME(`unix_timestamp_int`) FROM `table_name`

Get a UTC datetime from a UNIX timestamp

SELECT CONVERT_TZ(FROM_UNIXTIME(`unix_timestamp_int`), @@session.time_zone, '+00:00') 
FROM `table_name`

Get a current timezone datetime from a negative UNIX timestamp integer

SELECT DATE_ADD('1970-01-01 00:00:00',INTERVAL -957632400 SECOND) 

There are 3 places where the timezone might be set in MySQL:

Note: A timezone can be set in 2 formats:

  1. an offset from UTC: '+00:00', '+10:00' or '-6:00'
  2. as a named time zone: 'Europe/Helsinki', 'US/Eastern', or 'MET'

Named time zones can be used only if the time zone information tables in the mysql database have been created and populated.

in the file "my.cnf"

default_time_zone='+00:00'

or

timezone='UTC'

@@global.time_zone variable

To see what value they are set to

SELECT @@global.time_zone;

To set a value for it use either one:

SET GLOBAL time_zone = '+8:00';
SET GLOBAL time_zone = 'Europe/Helsinki';
SET @@global.time_zone='+00:00';

@@session.time_zone variable

SELECT @@session.time_zone;

To set it use either one:

SET time_zone = 'Europe/Helsinki';
SET time_zone = "+00:00";
SET @@session.time_zone = "+00:00";

both "@@global.time_zone variable" and "@@session.time_zone variable" might return "SYSTEM" which means that they use the timezone set in "my.cnf".

For timezone names to work (even for default-time-zone) you must setup your timezone information tables need to be populated: http://dev.mysql.com/doc/refman/5.1/en/time-zone-support.html

Note: you can not do this as it will return NULL:

SELECT 
CONVERT_TZ(`timestamp_field`, TIMEDIFF(NOW(), UTC_TIMESTAMP), '+00:00') AS `utc_datetime` 
FROM `table_name`

Setup mysql timezone tables

For CONVERT_TZ to work, you need the timezone tables to be populated

SELECT * FROM mysql.`time_zone` ;
SELECT * FROM mysql.`time_zone_leap_second` ;
SELECT * FROM mysql.`time_zone_name` ;
SELECT * FROM mysql.`time_zone_transition` ;
SELECT * FROM mysql.`time_zone_transition_type` ;

If they are empty, then fill them up by running this command

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

if this command gives you the error "data too long for column 'abbreviation' at row 1", then it might be caused by a NULL character being appended at the end of the timezone abbreviation

the fix being to run this

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql
(if the above gives error "data too long for column 'abbreviation' at row 1")
mysql_tzinfo_to_sql /usr/share/zoneinfo > /tmp/zut.sql

echo "SET SESSION SQL_MODE = '';" > /tmp/mysql_tzinfo_to.sql
cat /tmp/zut.sql >> /tmp/mysql_tzinfo_to.sql

mysql --defaults-file=/etc/mysql/my.cnf --user=verifiedscratch -p mysql < /tmp/mysql_tzinfo_to.sql

(make sure your servers dst rules are up to date zdump -v Europe/Moscow | grep 2011 https://chrisjean.com/updating-daylight-saving-time-on-linux/)

See the full DST (Daylight Saving Time) transition history for every timezone

SELECT 
tzn.Name AS tz_name,
tztt.Abbreviation AS tz_abbr,
tztt.Is_DST AS is_dst,
tztt.`Offset` AS `offset`,
DATE_ADD('1970-01-01 00:00:00',INTERVAL tzt.Transition_time SECOND)  AS transition_date
FROM mysql.`time_zone_transition` tzt
INNER JOIN mysql.`time_zone_transition_type` tztt USING(Time_zone_id, Transition_type_id)
INNER JOIN mysql.`time_zone_name` tzn USING(Time_zone_id)
-- WHERE tzn.Name LIKE 'Europe/Moscow' -- Moscow has weird DST changes
ORDER BY tzt.Transition_time ASC

CONVERT_TZ also applies any necessary DST changes based on the rules in the above tables and the date that you use.

Note:
According to the docs, the value you set for time_zone does not change, if you set it as "+01:00" for example, then the time_zone will be set as an offset from UTC, which does not follow DST, so it will stay the same all year round.

Only the named timezones will change time during daylight savings time.

Abbreviations like CET will always be a winter time and CEST will be summer time while +01:00 will always be UTC time + 1 hour and both won't change with DST.

The system timezone will be the timezone of the host machine where mysql is installed (unless mysql fails to determine it)

You can read more about working with DST here

related questions:

Sources:

Salt and hash a password in Python

As of Python 3.4, the hashlib module in the standard library contains key derivation functions which are "designed for secure password hashing".

So use one of those, like hashlib.pbkdf2_hmac, with a salt generated using os.urandom:

from typing import Tuple
import os
import hashlib
import hmac

def hash_new_password(password: str) -> Tuple[bytes, bytes]:
    """
    Hash the provided password with a randomly-generated salt and return the
    salt and hash to store in the database.
    """
    salt = os.urandom(16)
    pw_hash = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
    return salt, pw_hash

def is_correct_password(salt: bytes, pw_hash: bytes, password: str) -> bool:
    """
    Given a previously-stored salt and hash, and a password provided by a user
    trying to log in, check whether the password is correct.
    """
    return hmac.compare_digest(
        pw_hash,
        hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
    )

# Example usage:
salt, pw_hash = hash_new_password('correct horse battery staple')
assert is_correct_password(salt, pw_hash, 'correct horse battery staple')
assert not is_correct_password(salt, pw_hash, 'Tr0ub4dor&3')
assert not is_correct_password(salt, pw_hash, 'rosebud')

Note that:

  • The use of a 16-byte salt and 100000 iterations of PBKDF2 match the minimum numbers recommended in the Python docs. Further increasing the number of iterations will make your hashes slower to compute, and therefore more secure.
  • os.urandom always uses a cryptographically secure source of randomness
  • hmac.compare_digest, used in is_correct_password, is basically just the == operator for strings but without the ability to short-circuit, which makes it immune to timing attacks. That probably doesn't really provide any extra security value, but it doesn't hurt, either, so I've gone ahead and used it.

For theory on what makes a good password hash and a list of other functions appropriate for hashing passwords with, see https://security.stackexchange.com/q/211/29805.

Mongodb service won't start

After running the repair I was able to start the mongod proccessor but as root, which meant that service mongod start would not work. To repair this issue, I needed to make sure that all the files inside the database folder were owned and grouped to mongod. I did this by the following:

  1. Check the file permissions inside your database folder
    1. note you need to be in your dbpath folder mine was /var/lib/mongo I went to cd /var/lib
    2. I ran ls -l mongo
  2. This showed me that databases were owned by root, which is wrong. I ran the following to fix this: chown -R mongod:mongod mongo. This changed the owner and group of every file in the folder to mongod. (If using the mongodb package, chown -R mongodb:mongodb mongodb)

I hope this helps someone else in the future.

Listen to changes within a DIV and act accordingly

If possible you can change the div to an textarea and use .change().

Another solution could be use a hidden textarea and update the textarea same time as you update the div. Then use .change() on the hidden textarea.

You can also use http://www.jacklmoore.com/autosize/ to make the text area act more like a div.

<style>
.hidden{
display:none
}
</style>

<textarea class="hidden" rows="4" cols="50">

</textarea>


$("#hiddentextarea").change(function() {

alert('Textarea changed');

})

Update: It seems like textarea has to be defocused after updated, for more info: How do I set up a listener in jQuery/javascript to monitor a if a value in the textbox has changed?

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

Getting XML Node text value with Java DOM

If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...

import com.ximpleware.*;
public class queryText {
    public static void main(String[] s) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", true))
            return;
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        // first manually navigate
        if(vn.toElement(VTDNav.FC,"tag")){
            int i= vn.getText();
            if (i!=-1){
                System.out.println("text ===>"+vn.toString(i));
            }
            if (vn.toElement(VTDNav.NS,"tag")){
                i=vn.getText();
                System.out.println("text ===>"+vn.toString(i));
            }
        }

        // second version use XPath
        ap.selectXPath("/add/tag/text()");
        int i=0;
        while((i=ap.evalXPath())!= -1){
            System.out.println("text node ====>"+vn.toString(i));
        }
    }
}

Adding and removing style attribute from div with jquery

To completely remove the style attribute of the voltaic_holder span, do this:

$("#voltaic_holder").removeAttr("style");

To add an attribute, do this:

$("#voltaic_holder").attr("attribute you want to add", "value you want to assign to attribute");

To remove only the top style, do this:

$("#voltaic_holder").css("top", "");

How do I parse an ISO 8601-formatted date?

I'm the author of iso8601 utils. It can be found on GitHub or on PyPI. Here's how you can parse your example:

>>> from iso8601utils import parsers
>>> parsers.datetime('2008-09-03T20:56:35.450686Z')
datetime.datetime(2008, 9, 3, 20, 56, 35, 450686)

Notepad++ cached files location

I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.

Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.

Returning boolean if set is empty

"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()

Path of currently executing powershell script

From Get-ScriptDirectory to the Rescue blog entry ...

function Get-ScriptDirectory
{
  $Invocation = (Get-Variable MyInvocation -Scope 1).Value
  Split-Path $Invocation.MyCommand.Path
}

bash, extract string before a colon

Another pure BASH way:

> s='/some/random/file.csv:some string'
> echo "${s%%:*}"
/some/random/file.csv

How to pick element inside iframe using document.getElementById

You need to make sure the frame is fully loaded the best way to do it is to use onload:

<iframe id="nesgt" src="" onload="custom()"></iframe>

function custom(){
    document.getElementById("nesgt").contentWindow.document;
    }

this function will run automatically when the iframe is fully loaded.

it could be done with setTimeout but we can't get the exact time of the frame load.

hope this helps someone.

How to convert text to binary code in JavaScript?

Provided you're working in node or a browser with BigInt support, this version cuts costs by saving the expensive string construction for the very end:

const zero = 0n
const shift = 8n

function asciiToBinary (str) {
  const len = str.length
  let n = zero
  for (let i = 0; i < len; i++) {
    n = (n << shift) + BigInt(str.charCodeAt(i))
  }
  return n.toString(2).padStart(len * 8, 0)
}

It's about twice as fast as the other solutions mentioned here including this simple es6+ implementation:

const toBinary = s => [...s]
  .map(x => x
    .codePointAt()
    .toString(2)
    .padStart(8,0)
  )
  .join('')

If you need to handle unicode characters, here's this guy:

const zero = 0n
const shift = 8n
const bigShift = 16n
const byte = 255n

function unicodeToBinary (str) {
  const len = str.length
  let n = zero
  for (let i = 0; i < len; i++) {
    const bits = BigInt(str.codePointAt(i))
    n = (n << (bits > byte ? bigShift : shift)) + bits
  }
  const bin = n.toString(2)
  return bin.padStart(8 * Math.ceil(bin.length / 8), 0)
}

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

Python time measure function

Timeit has two big flaws: it doesn't return the return value of the function, and it uses eval, which requires passing in extra setup code for imports. This solves both problems simply and elegantly:

def timed(f):
  start = time.time()
  ret = f()
  elapsed = time.time() - start
  return ret, elapsed

timed(lambda: database.foo.execute('select count(*) from source.apachelog'))
(<sqlalchemy.engine.result.ResultProxy object at 0x7fd6c20fc690>, 4.07547402381897)

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

Take note of what is printed for x. You are trying to convert an array (basically just a list) into an int. length-1 would be an array of a single number, which I assume numpy just treats as a float. You could do this, but it's not a purely-numpy solution.

EDIT: I was involved in a post a couple of weeks back where numpy was slower an operation than I had expected and I realised I had fallen into a default mindset that numpy was always the way to go for speed. Since my answer was not as clean as ayhan's, I thought I'd use this space to show that this is another such instance to illustrate that vectorize is around 10% slower than building a list in Python. I don't know enough about numpy to explain why this is the case but perhaps someone else does?

import numpy as np
import matplotlib.pyplot as plt
import datetime

time_start = datetime.datetime.now()

# My original answer
def f(x):
    rebuilt_to_plot = []
    for num in x:
        rebuilt_to_plot.append(np.int(num))
    return rebuilt_to_plot

for t in range(10000):
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f(x))

time_end = datetime.datetime.now()

# Answer by ayhan
def f_1(x):
    return np.int(x)

for t in range(10000):
    f2 = np.vectorize(f_1)
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f2(x))

time_end_2 = datetime.datetime.now()

print time_end - time_start
print time_end_2 - time_end

mysql query result in php variable

There are a couple of mysql functions you need to look into.

  • mysql_query("query string here") : returns a resource
  • mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:

    while ($row = mysql_fetch_array($query)){
        print_r $row;
    }

    Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.

Links:

In your case,

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
    die("BAD!");
}
if (mysql_num_rows($result)==1){
    $row = mysql_fetch_array($result);
    echo "user Id: " . $row['userid'];
}
else{
    echo "not found!";
}

Twitter Bootstrap modal: How to remove Slide down effect

If you like to have the modal fade in rather than slide in (why is it called .fade anyway?) you can overwrite the class in your CSS file or directly in bootstrap.css with this:

.modal.fade{
    -webkit-transition: opacity .2s linear, none;
    -moz-transition: opacity .2s linear, none;
    -ms-transition: opacity .2s linear, none;
    -o-transition: opacity .2s linear, none;
    transition: opacity .2s linear, none;
    top: 50%;
}

If you don't want any effect just remove the fade class from the modal classes.

Gradient borders

Try this, works fine on web-kit

_x000D_
_x000D_
.border { _x000D_
    width: 400px;_x000D_
    padding: 20px;_x000D_
    border-top: 10px solid #FFFF00;_x000D_
    border-bottom:10px solid #FF0000;_x000D_
    background-image: _x000D_
        linear-gradient(#FFFF00, #FF0000),_x000D_
        linear-gradient(#FFFF00, #FF0000)_x000D_
    ;_x000D_
    background-size:10px 100%;_x000D_
    background-position:0 0, 100% 0;_x000D_
    background-repeat:no-repeat;_x000D_
}
_x000D_
<div class="border">Hello!</div>
_x000D_
_x000D_
_x000D_

How to write a multidimensional array to a text file?

Use JSON module for multidimensional arrays, e.g.

import json
with open(filename, 'w') as f:
   json.dump(myndarray.tolist(), f)

What is the difference between ELF files and bin files?

A bin file is just the bits and bytes that go into the rom or a particular address from which you will run the program. You can take this data and load it directly as is, you need to know what the base address is though as that is normally not in there.

An elf file contains the bin information but it is surrounded by lots of other information, possible debug info, symbols, can distinguish code from data within the binary. Allows for more than one chunk of binary data (when you dump one of these to a bin you get one big bin file with fill data to pad it to the next block). Tells you how much binary you have and how much bss data is there that wants to be initialised to zeros (gnu tools have problems creating bin files correctly).

The elf file format is a standard, arm publishes its enhancements/variations on the standard. I recommend everyone writes an elf parsing program to understand what is in there, dont bother with a library, it is quite simple to just use the information and structures in the spec. Helps to overcome gnu problems in general creating .bin files as well as debugging linker scripts and other things that can help to mess up your bin or elf output.

Giving a border to an HTML table row, <tr>

After fighting with this for a long time I have concluded that the spectacularly simple answer is to just fill the table with empty cells to pad out every row of the table to the same number of cells (taking colspan into account, obviously). With computer-generated HTML this is very simple to arrange, and avoids fighting with complex workarounds. Illustration follows:

<h3>Table borders belong to cells, and aren't present if there is no cell</h3>
<table style="border:1px solid red; width:100%; border-collapse:collapse;">
    <tr style="border-top:1px solid darkblue;">
        <th>Col 1<th>Col 2<th>Col 3
    <tr style="border-top:1px solid darkblue;">
        <td>Col 1 only
    <tr style="border-top:1px solid darkblue;">
        <td colspan=2>Col 1 2 only
    <tr style="border-top:1px solid darkblue;">
        <td>1<td>2<td>3

</table>


<h3>Simple solution, artificially insert empty cells</h3>

<table style="border:1px solid red; width:100%; border-collapse:collapse;">
    <tr style="border-top:1px solid darkblue;">
        <th>Col 1<th>Col 2<th>Col 3
    <tr style="border-top:1px solid darkblue;">
        <td>Col 1 only<td><td>
    <tr style="border-top:1px solid darkblue;">
        <td colspan=2>Col 1 2 only<td>
    <tr style="border-top:1px solid darkblue;">
        <td>1<td>2<td>3

</table>

Setting Authorization Header of HttpClient

As it is a good practice to reuse the HttpClient instance, for performance and port exhaustion problems, and because none of the answers give this solution (and even leading you toward bad practices :( ), I put here a link towards the answer I made on a similar question :

https://stackoverflow.com/a/40707446/717372

Some sources on how to use HttpClient the right way:

How do I fetch only one branch of a remote Git repository?

If you want to change the default for "git pull" and "git fetch" to only fetch specific branches then you can edit .git/config so that the remote config looks like:

[remote "origin"]
  fetch = +refs/heads/master:refs/remotes/origin/master

This will only fetch master from origin by default. See for more info: https://git-scm.com/book/en/v2/Git-Internals-The-Refspec

EDIT: Just realized this is the same thing that the -t option does for git remote add. At least this is a nice way to do it after the remote is added if you don't want ot delete the remote and add it again using -t.

CORS: credentials mode is 'include'

If you're using .NET Core, you will have to .AllowCredentials() when configuring CORS in Startup.CS.

Inside of ConfigureServices

services.AddCors(o => {
    o.AddPolicy("AllowSetOrigins", options =>
    {
        options.WithOrigins("https://localhost:xxxx");
        options.AllowAnyHeader();
        options.AllowAnyMethod();
        options.AllowCredentials();
    });
});

services.AddMvc();

Then inside of Configure:

app.UseCors("AllowSetOrigins");
app.UseMvc(routes =>
    {
        // Routing code here
    });

For me, it was specifically just missing options.AllowCredentials() that caused the error you mentioned. As a side note in general for others having CORS issues as well, the order matters and AddCors() must be registered before AddMVC() inside of your Startup class.

What is the `data-target` attribute in Bootstrap 3?

The toggle tells Bootstrap what to do and the target tells Bootstrap which element is going to open. So whenever a link like that is clicked, a modal with an id of “basicModal” will appear.

Last Key in Python Dictionary

yes there is : len(data)-1.

For the first element it´s : 0