Programs & Examples On #Em getline

How to open adb and use it to send commands

You should find it in :

C:\Users\User Name\AppData\Local\Android\sdk\platform-tools

Add that to path, or change directory to there. The command sqlite3 is also there.

In the terminal you can type commands like

adb logcat //for logs
adb shell // for android shell

How do I connect to a specific Wi-Fi network in Android programmatically?

This is an activity you can subclass to force the connecting to a specific wifi: https://github.com/zoltanersek/android-wifi-activity/blob/master/app/src/main/java/com/zoltanersek/androidwifiactivity/WifiActivity.java

You will need to subclass this activity and implement its methods:

public class SampleActivity extends WifiBaseActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  }

  @Override
  protected int getSecondsTimeout() {
      return 10;
  }

  @Override
  protected String getWifiSSID() {
      return "WifiNetwork";
  }

  @Override
  protected String getWifiPass() {
      return "123456";
  }
}

refresh both the External data source and pivot tables together within a time schedule

I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.

Sub Refresh()

    Dim conn As Variant

    For Each conn In ActiveWorkbook.Connections
        conn.ODBCConnection.BackgroundQuery = False
    Next conn

    ActiveWorkbook.RefreshAll
End Sub

What does the ELIFECYCLE Node.js error mean?

While working on a WordPress theme, I got the same ELIFECYCLE error with slightly different output:

npm ERR! Darwin 14.5.0
npm ERR! argv "/usr/local/Cellar/node/7.6.0/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v7.6.0
npm ERR! npm  v3.7.3
npm ERR! code ELIFECYCLE
npm ERR! [email protected] postinstall: `bower install && gulp build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] postinstall script 'bower install && gulp build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the foundationsix package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     bower install && gulp build

After trying npm install one more time with the same result, I tried bower install. When that was successful I tried gulp build and that also worked.

Everything is working just fine now. No idea why running each command separately worked when && failed but maybe someone else will find this answer useful.

What is the difference between encode/decode?

To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding).

Example:

    >>> u'æøå'.encode('utf8')
    '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
    >>> u'æøå'.encode('latin1')
    '\xc3\xa6\xc3\xb8\xc3\xa5'
    >>> u'æøå'.encode('ascii')
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: 
    ordinal not in range(128)

You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.

To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding) or '...'.decode(encoding).

Example:

   >>> u'æøå'
   u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
   >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'
   >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'

You typically decode a string of bytes whenever you receive string data from the network or from a disk file.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:

Underscore prefix for property and method names in JavaScript

import/export is now doing the job with ES6. I still tend to prefix not exported functions with _ if most of my functions are exported.

If you export only a class (like in angular projects), it's not needed at all.

export class MyOpenClass{

    open(){
         doStuff()
         this._privateStuff()
         return close();
    }

    _privateStuff() { /* _ only as a convention */} 

}

function close(){ /*... this is really private... */ }

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

Delete rows with blank values in one particular column

 df[!(is.na(df$start_pc) | df$start_pc==""), ]

Get Locale Short Date Format using javascript

I don't know of a way to do that (you can get the language and try to deduct the locale from that).

I tried to cook a little something to try and do that (only tested on Firefox with one locale). should work as long as the short date string includes the date as digits, so it might fail for, say, arabic. It might have other bugs too, i don't know all the different locales peculiarities, this is just a concept...

function getShortDateFormat() {
    var d = new Date(1992, 0, 7);
    var s = d.toLocaleDateString();

    function formatReplacer(str) {
        var num = parseInt(str);
        switch (num % 100) {
            case 92:
                return str.replace(/.{1}/g, "Y");
            case 1:
                return str.length == 1 ? "mM" : "MM"
            case 7:
                return str.length == 1 ? "dD" : "DD"
        }
    }

    shortDateFormat = s.replace(/\d+/g, formatReplacer);
    return shortDateFormat;
}

getShortDateFormat();

The outputted format will be:

  • Y: the number of digits to represent years
  • dD = short day (i.e. use only one digit when possible)
  • DD = long day format (i.e. two digits always)
  • mM/MM - same for months

So in my browser, the shortDateformat you get is "MM/DD/YYYY".

How to make an authenticated web request in Powershell?

The PowerShell is almost exactly the same.

$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings

Since PHP 5.5, there is a separate php.ini file for CLI interface. If You use symfony console from command line, then this specific php.ini is used.

In Ubuntu 13.10 check file:

/etc/php5/cli/php.ini

Stopping fixed position scrolling at a certain point?

In a project, I actually have some heading fixed to the bottom of the screen on page load (it's a drawing app so the heading is at the bottom to give maximum space to the canvas element on wide viewport).

I needed the heading to become 'absolute' when it reaches the footer on scroll, since I don't want the heading over the footer (heading colour is same as footer background colour).

I took the oldest response on here (edited by Gearge Millo) and that code snippet worked for my use-case. With some playing around I got this working. Now the fixed heading sits beautifully above the footer once it reaches the footer.

Just thought I'd share my use-case and how it worked, and say thank you! The app: http://joefalconer.com/web_projects/drawingapp/index.html

    /* CSS */
    @media screen and (min-width: 1100px) {
        #heading {
            height: 80px;
            width: 100%;
            position: absolute;  /* heading is 'absolute' on page load. DOESN'T WORK if I have this on 'fixed' */
            bottom: 0;
        }
    }

    // jQuery
    // Stop the fixed heading from scrolling over the footer
    $.fn.followTo = function (pos) {
      var $this = this,
      $window = $(window);

      $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
          $this.css( { position: 'absolute', bottom: '-180px' } );
        } else {
          $this.css( { position: 'fixed', bottom: '0' } );
        }
      });
    };
    // This behaviour is only needed for wide view ports
    if ( $('#heading').css("position") === "absolute" ) {
      $('#heading').followTo(180);
    }

Disable mouse scroll wheel zoom on embedded Google Maps

This is my approach. I find it easy to implement on various websites and use it all the time

CSS and JavaScript:

<style type="text/css">
.scrolloff iframe   {
    pointer-events: none ;
}
</style>

<script type="text/javascript">
function scrollOn() {
    $('#map').removeClass('scrolloff'); // set the pointer events true on click

}

function scrollOff() {
    $('#map').addClass('scrolloff'); 

}
</script>

In the HTML, you will want to wrap the iframe in a div. <div id="map" class="scrolloff" onclick="scrollOn()" onmouseleave="scrollOff()" >

_x000D_
_x000D_
function scrollOn() {_x000D_
    $('#map').removeClass('scrolloff'); // set the pointer events true on click_x000D_
   _x000D_
}_x000D_
_x000D_
function scrollOff() {_x000D_
    $('#map').addClass('scrolloff'); // set the pointer events true on click_x000D_
    _x000D_
}
_x000D_
.scrolloff iframe   {_x000D_
        pointer-events: none ;_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="map" class="scrolloff" onclick="scrollOn()" onmouseleave="scrollOff()" ><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d23845.03946309692!2d-70.0451736316453!3d41.66373705082399!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x89fb159980380d21%3A0x78c040f807017e30!2sChatham+Tides!5e0!3m2!1sen!2sus!4v1452964723177" width="100%" height="450" frameborder="0" style="border:0" allowfullscreen></iframe></div>
_x000D_
_x000D_
_x000D_

Hope this helps anyone looking for a simple solution.

How to use Python to execute a cURL command?

Just use this website. It'll convert any curl command into Python, Node.js, PHP, R, or Go.

Example:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

Becomes this in Python,

import requests

headers = {
    'Content-type': 'application/json',
}

data = '{"text":"Hello, World!"}'

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)

Getting HTTP code in PHP using curl

curl_getinfo — Get information regarding a specific transfer

Check curl_getinfo

<?php
// Create a curl handle
$ch = curl_init('http://www.yahoo.com/');

// Execute
curl_exec($ch);

// Check if any error occurred
if(!curl_errno($ch))
{
 $info = curl_getinfo($ch);

 echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url'];
}

// Close handle
curl_close($ch);

Strip out HTML and Special Characters

Strip out tags, leave only alphanumeric characters and space:

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($des));

Edit: all credit to DaveRandom for the perfect solution...

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags(html_entity_decode($des)));

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Why is sed not recognizing \t as a tab?

sed doesn't support \t, nor other escape sequences like \n for that matter. The only way I've found to do it was to actually insert the tab character in the script using sed.

That said, you may want to consider using Perl or Python. Here's a short Python script I wrote that I use for all stream regex'ing:

#!/usr/bin/env python
import sys
import re

def main(args):
  if len(args) < 2:
    print >> sys.stderr, 'Usage: <search-pattern> <replace-expr>'
    raise SystemExit

  p = re.compile(args[0], re.MULTILINE | re.DOTALL)
  s = sys.stdin.read()
  print p.sub(args[1], s),

if __name__ == '__main__':
  main(sys.argv[1:])

How to call a SOAP web service on Android

For me the easiest way is to use good tool to generate all required classes. Personally I use this site:

http://easywsdl.com/

It supports quite complex web services and uses ksoap2.

How to search contents of multiple pdf files?

If You want to see file names with pdftotext use following command:

find . -name '*.pdf' -exec echo {} \; -exec pdftotext {} - \; | grep "pattern\|pdf" 

How can I connect to MySQL in Python 3 on Windows?

PyMySQL gives MySQLDb like interface as well. You could try in your initialization:

import pymysql
pymysql.install_as_MySQLdb()

Also there is a port of mysql-python on github for python3.

https://github.com/davispuh/MySQL-for-Python-3

Disable Pinch Zoom on Mobile Web

Found here you can use user-scalable=no:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

sudo: npm: command not found

Appended npm binary path to sudo path using visudo and editing "secure_path"

Now "sudo npm" works

How do I check whether a checkbox is checked in jQuery?

Use jQuery's is() function:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked

Creating a file name as a timestamp in a batch job

For big zip files for deployment, I use quarter hours. No one else on this page had mentioned it before, so I'll put my small script here:

set /a "quarter_hours=%time:~0,2%*4 + %time:~3,2% / 15"
set "zip_file=release_%DATE:~-4%.%DATE:~4,2%.%DATE:~7,2%.%quarter_hours%.zip"

It doesn't zero pad quarter hours from midnight to 5am yet, but it still makes it so you can have a stamped release multiple times a day with few collisions.

Hope that helps.

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

CSS :: child set to change color on parent hover, but changes also when hovered itself

Update

The below made sense for 2013. However, now, I would use the :not() selector as described below.


CSS can be overwritten.

DEMO: http://jsfiddle.net/persianturtle/J4SUb/

Use this:

_x000D_
_x000D_
.parent {
  padding: 50px;
  border: 1px solid black;
}

.parent span {
  position: absolute;
  top: 200px;
  padding: 30px;
  border: 10px solid green;
}

.parent:hover span {
  border: 10px solid red;
}

.parent span:hover {
  border: 10px solid green;
}
_x000D_
<a class="parent">
    Parent text
    <span>Child text</span>    
</a>
_x000D_
_x000D_
_x000D_

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; 

How should I log while using multiprocessing in Python?

Below is another solution with a focus on simplicity for anyone else (like me) who get here from Google. Logging should be easy! Only for 3.2 or higher.

import multiprocessing
import logging
from logging.handlers import QueueHandler, QueueListener
import time
import random


def f(i):
    time.sleep(random.uniform(.01, .05))
    logging.info('function called with {} in worker thread.'.format(i))
    time.sleep(random.uniform(.01, .05))
    return i


def worker_init(q):
    # all records from worker processes go to qh and then into q
    qh = QueueHandler(q)
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    logger.addHandler(qh)


def logger_init():
    q = multiprocessing.Queue()
    # this is the handler for all log records
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter("%(levelname)s: %(asctime)s - %(process)s - %(message)s"))

    # ql gets records from the queue and sends them to the handler
    ql = QueueListener(q, handler)
    ql.start()

    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)
    # add the handler to the logger so records from this process are handled
    logger.addHandler(handler)

    return ql, q


def main():
    q_listener, q = logger_init()

    logging.info('hello from main thread')
    pool = multiprocessing.Pool(4, worker_init, [q])
    for result in pool.map(f, range(10)):
        pass
    pool.close()
    pool.join()
    q_listener.stop()

if __name__ == '__main__':
    main()

Batch script: how to check for admin rights

alternative solution:

@echo off
pushd %SystemRoot%
openfiles.exe 1>nul 2>&1
if not %errorlevel% equ 0 (
    Echo here you are not administrator!
) else (
    Echo here you are administrator!
)
popd
Pause

Is there any way to specify a suggested filename when using data: URI?

The following Javascript snippet works in Chrome by using the new 'download' attribute of links and simulating a click.

function downloadWithName(uri, name) {
  var link = document.createElement("a");
  link.download = name;
  link.href = uri;
  link.click();
}

And the following example shows it's use:

downloadWithName("data:,Hello%2C%20World!", "helloWorld.txt")

How can I check if a Perl module is installed on my system from the command line?

Bravo for @user80168's solution (I'm still counting \'s !) but to avoid all the escaping involved with aliases and shells:

%~/ cat ~/bin/perlmod
perl -le'eval qq{require $ARGV[0]; } 
    ? print ( "Found $ARGV[0] Version: ", eval "$ARGV[0]->VERSION" ) 
    : print "Not installed" ' $1

works reasonably well.

Here might be the simplest and most "modern" approach, using Module::Runtime:

perl -MModule::Runtime=use_module -E '
     say "$ARGV[0] ", use_module($ARGV[0])->VERSION' DBI

This will give a useful error if the module is not installed.

Using -MModule::Runtime requires it to be installed (it is not a core module).

How to convert datetime format to date format in crystal report using C#?

if it is just a format issue use ToShortDateString()

Detecting TCP Client Disconnect

select (with the read mask set) will return with the handle signalled, but when you use ioctl* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.

This is a great discussion on the various methods of checking that the client has disconnected: Stephen Cleary, Detection of Half-Open (Dropped) Connections.

* for Windows use ioctlsocket.

Delete empty rows

DELETE FROM table WHERE edit_user IS NULL;

How can I make sticky headers in RecyclerView? (Without external lib)

Another solution, based on scroll listener. Initial conditions are the same as in Sevastyan answer

RecyclerView recyclerView;
TextView tvTitle; //sticky header view

//... onCreate, initialize, etc...

public void bindList(List<Item> items) { //All data in adapter. Item - just interface for different item types
    adapter = new YourAdapter(items);
    recyclerView.setAdapter(adapter);
    StickyHeaderViewManager<HeaderItem> stickyHeaderViewManager = new StickyHeaderViewManager<>(
            tvTitle,
            recyclerView,
            HeaderItem.class, //HeaderItem - subclass of Item, used to detect headers in list
            data -> { // bind function for sticky header view
                tvTitle.setText(data.getTitle());
            });
    stickyHeaderViewManager.attach(items);
}

Layout for ViewHolder and sticky header.

item_header.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

Layout for RecyclerView

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <!--it can be any view, but order important, draw over recyclerView-->
    <include
        layout="@layout/item_header"/>

</FrameLayout>

Class for HeaderItem.

public class HeaderItem implements Item {

    private String title;

    public HeaderItem(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

}

It's all use. The implementation of the adapter, ViewHolder and other things, is not interesting for us.

public class StickyHeaderViewManager<T> {

    @Nonnull
    private View headerView;

    @Nonnull
    private RecyclerView recyclerView;

    @Nonnull
    private StickyHeaderViewWrapper<T> viewWrapper;

    @Nonnull
    private Class<T> headerDataClass;

    private List<?> items;

    public StickyHeaderViewManager(@Nonnull View headerView,
                                   @Nonnull RecyclerView recyclerView,
                                   @Nonnull Class<T> headerDataClass,
                                   @Nonnull StickyHeaderViewWrapper<T> viewWrapper) {
        this.headerView = headerView;
        this.viewWrapper = viewWrapper;
        this.recyclerView = recyclerView;
        this.headerDataClass = headerDataClass;
    }

    public void attach(@Nonnull List<?> items) {
        this.items = items;
        if (ViewCompat.isLaidOut(headerView)) {
            bindHeader(recyclerView);
        } else {
            headerView.post(() -> bindHeader(recyclerView));
        }

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                bindHeader(recyclerView);
            }
        });
    }

    private void bindHeader(RecyclerView recyclerView) {
        if (items.isEmpty()) {
            headerView.setVisibility(View.GONE);
            return;
        } else {
            headerView.setVisibility(View.VISIBLE);
        }

        View topView = recyclerView.getChildAt(0);
        if (topView == null) {
            return;
        }
        int topPosition = recyclerView.getChildAdapterPosition(topView);
        if (!isValidPosition(topPosition)) {
            return;
        }
        if (topPosition == 0 && topView.getTop() == recyclerView.getTop()) {
            headerView.setVisibility(View.GONE);
            return;
        } else {
            headerView.setVisibility(View.VISIBLE);
        }

        T stickyItem;
        Object firstItem = items.get(topPosition);
        if (headerDataClass.isInstance(firstItem)) {
            stickyItem = headerDataClass.cast(firstItem);
            headerView.setTranslationY(0);
        } else {
            stickyItem = findNearestHeader(topPosition);
            int secondPosition = topPosition + 1;
            if (isValidPosition(secondPosition)) {
                Object secondItem = items.get(secondPosition);
                if (headerDataClass.isInstance(secondItem)) {
                    View secondView = recyclerView.getChildAt(1);
                    if (secondView != null) {
                        moveViewFor(secondView);
                    }
                } else {
                    headerView.setTranslationY(0);
                }
            }
        }

        if (stickyItem != null) {
            viewWrapper.bindView(stickyItem);
        }
    }

    private void moveViewFor(View secondView) {
        if (secondView.getTop() <= headerView.getBottom()) {
            headerView.setTranslationY(secondView.getTop() - headerView.getHeight());
        } else {
            headerView.setTranslationY(0);
        }
    }

    private T findNearestHeader(int position) {
        for (int i = position; position >= 0; i--) {
            Object item = items.get(i);
            if (headerDataClass.isInstance(item)) {
                return headerDataClass.cast(item);
            }
        }
        return null;
    }

    private boolean isValidPosition(int position) {
        return !(position == RecyclerView.NO_POSITION || position >= items.size());
    }
}

Interface for bind header view.

public interface StickyHeaderViewWrapper<T> {

    void bindView(T data);
}

Can Android do peer-to-peer ad-hoc networking?

you can connect your android device to a known ad-hoc network.

edit /system/etc/wifi/tiwlan.ini

WiFiAdhoc = 1
dot11DesiredSSID = <your_network_ssid>
dot11DesiredBSSType = 0 

edit /data/misc/wifi/wpa_supplicant.conf

ctrl_interface=tiwlan0
update_config=1
eapol_version=1
ap_scan=2

if that is too simplistic, see these instructions.

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

JQuery Validate input file type

Simply use the .rules('add') method immediately after creating the element...

var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile

    // create the new input element
    $('<li><input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> <a href="#" class="RemoveFileUpload">Remove</a></li>').prependTo("#FileUploader");

    // declare the rule on this newly created input field        
    $('#FileUpload' + filenumber).rules('add', {
        required: true,  // <- with this you would not need 'required' attribute on input
        accept: "image/jpeg, image/pjpeg"
    });

    filenumber++; // increment counter for next time

    return false;
});
  • You'll still need to use .validate() to initialize the plugin within a DOM ready handler.

  • You'll still need to declare rules for your static elements using .validate(). Whatever input elements that are part of the form when the page loads... declare their rules within .validate().

  • You don't need to use .each(), when you're only targeting ONE element with the jQuery selector attached to .rules().

  • You don't need the required attribute on your input element when you're declaring the required rule using .validate() or .rules('add'). For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required".

Working DEMO: http://jsfiddle.net/8dAU8/5/

Escaping quotes and double quotes

In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:

C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"

How to read all files in a folder from Java?

Java 8 Files.walk(..) is good when you are soore it will not throw Avoid Java 8 Files.walk(..) termination cause of ( java.nio.file.AccessDeniedException ) .

Here is a safe solution , not though so elegant as Java 8Files.walk(..) :

int[] count = {0};
try {
    Files.walkFileTree(Paths.get(dir.getPath()), new HashSet<FileVisitOption>(Arrays.asList(FileVisitOption.FOLLOW_LINKS)),
            Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file , BasicFileAttributes attrs) throws IOException {
                    System.out.printf("Visiting file %s\n", file);
                    ++count[0];

                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file , IOException e) throws IOException {
                    System.err.printf("Visiting failed for %s\n", file);

                    return FileVisitResult.SKIP_SUBTREE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir , BasicFileAttributes attrs) throws IOException {
                     System.out.printf("About to visit directory %s\n", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

How to store a list in a column of a database table

I'd just store it as CSV, if it's simple values then it should be all you need (XML is very verbose and serializing to/from it would probably be overkill but that would be an option as well).

Here's a good answer for how to pull out CSVs with LINQ.

How to retrieve raw post data from HttpServletRequest in java

We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.

So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.

    String input = null;

    // we have to store the string, which can only be read one time, because when the
    // servlet awakens an AsyncContext, it reposts the request and returns here empty handed
    if ((input = (String) request.getAttribute("com.xp.input")) == null) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while((line = reader.readLine()) != null){
            buffer.append(line);
        }
        // reqBytes = buffer.toString().getBytes();

        input = buffer.toString();
        request.setAttribute("com.xp.input", input);
    }

    if (input == null) {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
    }       

Passing $_POST values with cURL

Another simple PHP example of using cURL:

<?php
    $ch = curl_init();                    // Initiate cURL
    $url = "http://www.somesite.com/curl_example.php"; // Where you want to post data
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_POST, true);  // Tell cURL you want to post something
    curl_setopt($ch, CURLOPT_POSTFIELDS, "var1=value1&var2=value2&var_n=value_n"); // Define what you want to post
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the output in string format
    $output = curl_exec ($ch); // Execute

    curl_close ($ch); // Close cURL handle

    var_dump($output); // Show output
?>

Example found here: http://devzone.co.in/post-data-using-curl-in-php-a-simple-example/

Instead of using curl_setopt you can use curl_setopt_array.

http://php.net/manual/en/function.curl-setopt-array.php

how to use the Box-Cox power transformation in R

If I want tranfer only the response variable y instead of a linear model with x specified, eg I wanna transfer/normalize a list of data, I can take 1 for x, then the object becomes a linear model:

library(MASS)
y = rf(500,30,30)
hist(y,breaks = 12)
result = boxcox(y~1, lambda = seq(-5,5,0.5))
mylambda = result$x[which.max(result$y)]
mylambda
y2 = (y^mylambda-1)/mylambda
hist(y2)

Display date in dd/mm/yyyy format in vb.net

First, uppercase MM are months and lowercase mm are minutes.

You have to pass CultureInfo.InvariantCulture to ToString to ensure that / as date separator is used since it would normally be replaced with the current culture's date separator:

MsgBox(dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture))

Another option is to escape that custom format specifier by embedding the / within ':

dt.ToString("dd'/'MM'/'yyyy")

MSDN: The "/" Custom Format Specifier:

The "/" custom format specifier represents the date separator, which is used to differentiate years, months, and days. The appropriate localized date separator is retrieved from the DateTimeFormatInfo.DateSeparator property of the current or specified culture.

Java 8 lambda get and remove element from list

Although the thread is quite old, still thought to provide solution - using Java8.

Make the use of removeIf function. Time complexity is O(n)

producersProcedureActive.removeIf(producer -> producer.getPod().equals(pod));

API reference: removeIf docs

Assumption: producersProcedureActive is a List

NOTE: With this approach you won't be able to get the hold of the deleted item.

Android WebView Cookie Problem

Thanks justingrammens! That worked for me, I managed to share the cookie within my DefaultHttpClient requests and WebView activity:

//------- Native request activity
private DefaultHttpClient httpClient;
public static Cookie cookie = null;

//After Login
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
    cookie = cookies.get(i);
}

//------- Web Browser activity
Cookie sessionCookie = myapp.cookie;
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
    cookieManager.removeSessionCookie();
    String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
    cookieManager.setCookie(myapp.domain, cookieString);
    CookieSyncManager.getInstance().sync();
}   

How to call a .NET Webservice from Android using KSOAP2?

If more than one result is expected, then the getResponse() method will return a Vector containing the various responses.

In which case the offending code becomes:

Object result = envelope.getResponse();

// treat result as a vector
String resultText = null;
if (result instanceof Vector)
{
    SoapPrimitive element0 = (SoapPrimitive)((Vector) result).elementAt(0);
    resultText = element0.toString();
}

tv.setText(resultText);

Answer based on the ksoap2-android (mosabua fork)

define() vs. const

define I use for global constants.

const I use for class constants.

You cannot define into class scope, and with const you can. Needless to say, you cannot use const outside class scope.

Also, with const, it actually becomes a member of the class, and with define, it will be pushed to global scope.

How display only years in input Bootstrap Datepicker?

Try this

_x000D_
_x000D_
$("#datepicker").datepicker({_x000D_
    format: "yyyy",_x000D_
    viewMode: "years", _x000D_
    minViewMode: "years"_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<input type="text" id="datepicker" />
_x000D_
_x000D_
_x000D_

$("#datepicker").datepicker( {
    format: " yyyy", // Notice the Extra space at the beginning
    viewMode: "years", 
    minViewMode: "years"
});

Find stored procedure by name

Very neat trick I stumble upon trying some SQL injection, in object explorer in the search box just use your percentage characters, and this will search EVERYTHING stored procedures, functions, views, tables, schema, indexes...I tired of thinking of more :)

Search Pattern

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

query to find sql that opened.

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
and S.USERNAME='XXXX'
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

Using prepared statements with JDBCTemplate

I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):

private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
    if (updateSales == null) {
        updateSales = con.prepareStatement(
            "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    }
    updateSales.setInt(1, sales);
    updateSales.setString(2, cof_name);
    updateSales.executeUpdate();
}

At that point, it is then just a matter of calling:

updateSales(75, "Colombian");

Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...

Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.

Caesar Cipher Function in Python

I have a hard time remember the char to int conversions so this could be optimized

def decryptCaesar(encrypted, shift):
    minRange = ord('a')
    decrypted = ""
    for char in encrypted:
        decrypted += chr(((ord(char) - minRange + shift) % 26) + minRange)

    return decrypted

Printing *s as triangles in Java?

1) Normal triangle

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=n-i;j++)
         {

             System.out.print(" ");
         }

         for(int k=0;k<=2*i;k++)
         {
         System.out.print("*");
         }

         System.out.println("\n");

     }

     }

2) right angle triangle

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=n-i;j++)
         {

             System.out.print(" ");
         }

         for(int k=0;k<=i;k++)
         {
         System.out.print("*");
         }

         System.out.println("\n");

     }

     }


}

     }

3) Left angle triangle

package test1;


 class Test1 {

     public static void main(String args[])
     {
         int n=5;
     for(int i=0;i<n;i++)
     {

         for(int j=0;j<=i;j++)
         {

             System.out.print("*");
         }

         System.out.println("\n");

     }

     }


}

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

[Original answer]: You can still use launchctl setenv variablename value to set a variable so that is picked up by all applications (graphical applications started via the Dock or Spotlight, in addition to those started via the terminal).

Obviously you will not want to do this every time you login.

[Edit]: To avoid this, launch AppleScript Editor, enter a command like this:

do shell script "launchctl setenv variablename value"

(Use multiple lines if you want to set multiple variables)

Now save (?+s) as File format: Application. Finally open System Settings ? Users & Groups ? Login Items and add your new application.

[Original answer]: To work around this place all the variables you wish to define in a short shell script, then have a look at this previous answer about how to run a script on MacOS login. That way the the script will be invoked when the user logs in.

[Edit]: Neither solution is perfect as the variables will only be set for that specific user but I am hoping/guessing that may be all you require.

If you do have multiple users you could either manually set a Login Item for each of them or place a copy of com.user.loginscript.plist in each of their local Library/LaunchAgents directories, pointing at the same shell script.

Granted, neither of these workarounds is as convenient as /etc/launchd.conf.

[Further Edit]: A user below mentions that this did not work for him. However I have tested on multiple Yosemite machines and it does work for me. If you are having a problem, remember that you will need to restart applications for this to take effect. Additionally if you set variables in the terminal via ~/.profile or ~/.bash_profile, they will override things set via launchctl setenv for applications started from the shell.

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

How to format DateTime columns in DataGridView?

You can set the format you want:

dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn

How to split a string in Java

I just wanted to write an algorithm instead of using Java built-in functions:

public static List<String> split(String str, char c){
    List<String> list = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++){
        if(str.charAt(i) != c){
            sb.append(str.charAt(i));
        }
        else{
            if(sb.length() > 0){
                list.add(sb.toString());
                sb = new StringBuilder();
            }
        }
    }

    if(sb.length() >0){
        list.add(sb.toString());
    }
    return list;
}

How do I remove packages installed with Python's easy_install?

Official(?) instructions: http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages

If you have replaced a package with another version, then you can just delete the package(s) you don't need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).

If you want to delete the currently installed version of a package (or all versions of a package), you should first run:

easy_install -mxN PackageName

This will ensure that Python doesn't continue to search for a package you're planning to remove. After you've done this, you can safely delete the .egg files or directories, along with any scripts you wish to remove.

How to view method information in Android Studio?

The easiest and the most straightforward way:

To activate: File > Settings > Editor > General

For Mac OS X, Android Studio > Preferences > Editor > General and check Show quick documentation on mouse move:

Settings dialog with checked option

Other ways:

  • You can go into your IntelliJ's bin folder and search for idea.properties. Add this line to the document:

    auto.show.quick.doc=true

    Now you'll have the same floating docs window like in Eclipse.

  • You have to press CTRL+Q to see the Javadoc.

    You can pin the window and make the documentation appear every time you select a method with your mouse though.

Android Studio 1.0: You have to hold CTRL if you want to get hold of documentation window for e.g. scrolling documentation otherwise as you move your mouse away from method documentation window will disappear.

Get real path from URI, Android KitKat new storage access framework

I had the exact same problem. I need the filename so to be able to upload it to a website.

It worked for me, if I changed the intent to PICK. This was tested in AVD for Android 4.4 and in AVD for Android 2.1.

Add permission READ_EXTERNAL_STORAGE :

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Change the Intent :

Intent i = new Intent(
  Intent.ACTION_PICK,
  android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
  );
startActivityForResult(i, 66453666);

/* OLD CODE
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
  Intent.createChooser( intent, "Select Image" ),
  66453666
  );
*/

I did not have to change my code the get the actual path:

// Convert the image URI to the direct file system path of the image file
 public String mf_szGetRealPathFromURI(final Context context, final Uri ac_Uri )
 {
     String result = "";
     boolean isok = false;

     Cursor cursor = null;
      try { 
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(ac_Uri,  proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
        isok = true;
      } finally {
        if (cursor != null) {
          cursor.close();
        }
      }

      return isok ? result : "";
 }

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

npm not working - "read ECONNRESET"

You may also encounter this error if you have a saved bearer token that is now invalid. I've encountered this when using a private repo where the accounts were wiped and reset, invalidating the tokens. Although your repo may not require authentication, if you have a token from a previous login it will be passed and if it's invalid your connection will be closed.

You can resolve this by either logging in again with the new user name and password, or presumably by simply logging out via npm.

jQuery find element by data attribute value

Use Attribute Equals Selector

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

.find()

it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

How to add message box with 'OK' button?

I think there may be problem that you haven't added click listener for ok positive button.

dlgAlert.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          //dismiss the dialog  
        }
    });

Eclipse: The declared package does not match the expected package

  1. Right click on the external folder which is having package
src.prefix1.prefix.packagename1 
src.prefix1.prefix.packagename2
  1. Click Build path --> Remove from build path.

  2. Now go the folder prefix1 in the folder section of your project.

  3. Right click on it --> Build path --> Use as source folder.

  4. Done. The package folder wont show any error now. If it still shows, just restart the project.

How do I write good/correct package __init__.py files

__all__ is very good - it helps guide import statements without automatically importing modules http://docs.python.org/tutorial/modules.html#importing-from-a-package

using __all__ and import * is redundant, only __all__ is needed

I think one of the most powerful reasons to use import * in an __init__.py to import packages is to be able to refactor a script that has grown into multiple scripts without breaking an existing application. But if you're designing a package from the start. I think it's best to leave __init__.py files empty.

for example:

foo.py - contains classes related to foo such as fooFactory, tallFoo, shortFoo

then the app grows and now it's a whole folder

foo/
    __init__.py
    foofactories.py
    tallFoos.py
    shortfoos.py
    mediumfoos.py
    santaslittlehelperfoo.py
    superawsomefoo.py
    anotherfoo.py

then the init script can say

__all__ = ['foofactories', 'tallFoos', 'shortfoos', 'medumfoos',
           'santaslittlehelperfoo', 'superawsomefoo', 'anotherfoo']
# deprecated to keep older scripts who import this from breaking
from foo.foofactories import fooFactory
from foo.tallfoos import tallFoo
from foo.shortfoos import shortFoo

so that a script written to do the following does not break during the change:

from foo import fooFactory, tallFoo, shortFoo

How do you assert that a certain exception is thrown in JUnit 4 tests?

You can also do this:

@Test
public void testFooThrowsIndexOutOfBoundsException() {
    try {
        foo.doStuff();
        assert false;
    } catch (IndexOutOfBoundsException e) {
        assert true;
    }
}

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

in my case i made a custom view i added to custom view constructor

new RoomView(getAplicationContext());

the correct context is activity so changed it to:

new RoomView(getActivity());

or

new RoomView(this);

NVIDIA NVML Driver/library version mismatch

This also happened to me on Ubuntu 16.04 using the nvidia-348 package (latest nvidia version on Ubuntu 16.04).

However I could resolve the problem by installing nvidia-390 through the Proprietary GPU Drivers PPA.

So a solution to the described problem on Ubuntu 16.04 is doing this:

  • sudo add-apt-repository ppa:graphics-drivers/ppa
  • sudo apt-get update
  • sudo apt-get install nvidia-390

Note: This guide assumes a clean Ubuntu install. If you have previous drivers installed a reboot migh be needed to reload all the kernel modules.

How to insert data into elasticsearch

Let me explain clearly.. If you are familiar With rdbms.. Index is database.. And index type is table.. It mean index is collection of index types., like collection of tables as database (DB).

in NOSQL.. Index is database and index type is collections. Group of collection as database..

To execute those queries... U need to install CURL for Windows.

Curl is nothing but a command line rest tool.. If you want a graphical tool.. Try

Sense plugin for chrome...

Hope it helps..

Xcode Objective-C | iOS: delay function / NSTimer help?

Try

NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];

Transparent color of Bootstrap-3 Navbar

  1. Go to http://px64.net/
  2. mess around with opacity, add your image or choose color.
  3. copy either html or css(css is easier) the site spits out.
  4. Select your element aka the navbar.

  5. .navbar{ background-image:url(link that the site provides); background-repeat:repeat;

  6. Enjoy.

Python locale error: unsupported locale setting

For those deploying a docker image and using a locale that isn't shown in the locale -a command, add this line to your Dockerfile
RUN apt-get install -y locales

This should add all locales to your image, I used de_DE which is not part of AWS default Ubuntu server.

Could not load file or assembly '***.dll' or one of its dependencies

Had the same issue and got it resolved by making sure projects in the solution have the same configuration and platform (in my case it was Debug x64). Somehow the VIsual Studio was missing x64 for part of the projects and I edited the .sln file manually (copied the configurations and platforms from correctly built projects to the projects that were missing the settings I needed). This is what it looks like for one of the projects:

{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.ActiveCfg = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Debug|x64.Build.0 = Debug|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|Any CPU.Build.0 = Release|Any CPU
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.ActiveCfg = Release|x64
{1BA29980-EE5D-4476-AFFC-0F177B6C9865}.Release|x64.Build.0 = Release|x64

But then the same error occurred for a project that had a Java file (*.jar) in the dependencies. I had to edit Environment Variables manually to create a record with this value

C:\Program Files\Java\jre1.8.0_171\bin\server

for Java's path, and put it on top of the Path items.

This fixed the issue until I updated Java on my machine. I had to edit the version number in Environment Variables to match the updated folder name.

C:\Program Files\Java\jre1.8.0_181\bin\server

How do I calculate the percentage of a number?

$percentage = 50;
$totalWidth = 350;

$new_width = ($percentage / 100) * $totalWidth;

Gerrit error when Change-Id in commit messages are missing

You need to follow below 2 steps instructions:

[Issue] remote: Hint: To automatically insert Change-Id, install the hook:

1) gitdir=$(git rev-parse --git-dir);

2) scp -p -P 29418 <username>@gerrit.xyz.se:hooks/commit-msg ${gitdir}/hooks/

normally $gitdir = ".git". You need to update the username and the Gerrit link.

Refresh DataGridView when updating data source

Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List); 
dataGridView1.DataSource = itemStates;

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

Define global constants

If you're using Webpack, which I recommend, you can set-up constants for different environments. This is especially valuable when you have different constant values on a per environment basis.

You'll likely have multiple webpack files under your /config directory (e.g., webpack.dev.js, webpack.prod.js, etc.). Then you'll have a custom-typings.d.ts you'll add them there. Here's the general pattern to follow in each file and a sample usage in a Component.

webpack.{env}.js

const API_URL = process.env.API_URL = 'http://localhost:3000/';
const JWT_TOKEN_NAME = "id_token";
...
    plugins: [
      // NOTE: when adding more properties, make sure you include them in custom-typings.d.ts
      new DefinePlugin({
        'API_URL': JSON.stringify(API_URL),
        'JWT_TOKEN_NAME': JSON.stringify(JWT_TOKEN_NAME)
      }),

custom-typings.d.ts

declare var API_URL: string;
declare var JWT_TOKEN_NAME: string;
interface GlobalEnvironment {
  API_URL: string;
  JWT_TOKEN_NAME: string;
}

Component

export class HomeComponent implements OnInit {
  api_url:string = API_URL;
  authToken: string = "Bearer " + localStorage.getItem(JWT_TOKEN_NAME)});
}

How to submit a form when the return key is pressed?

Using the "autofocus" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the "autofocus" does that for you in case the user never clicked on any other control within the form.

So, the "autofocus" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.

But even then, there are still 2 conditions to be met for this to work without JS:

a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php

b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden. What I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.

<form action="hello.php" method="get">
  Name: <input type="text" name="name"/><br/>
  Pwd: <input type="password" name="password"/><br/>
  <div class="yourCustomDiv"/>
  <input autofocus type="submit" style="position:relative; left:-200px; height:0px;" />
</form>

How do I get the XML root node with C#?

Try this

XElement root = XDocument.Load(fStream).Root;

How to cancel a Task in await?

Read up on Cancellation (which was introduced in .NET 4.0 and is largely unchanged since then) and the Task-Based Asynchronous Pattern, which provides guidelines on how to use CancellationToken with async methods.

To summarize, you pass a CancellationToken into each method that supports cancellation, and that method must check it periodically.

private async Task TryTask()
{
  CancellationTokenSource source = new CancellationTokenSource();
  source.CancelAfter(TimeSpan.FromSeconds(1));
  Task<int> task = Task.Run(() => slowFunc(1, 2, source.Token), source.Token);

  // (A canceled task will raise an exception when awaited).
  await task;
}

private int slowFunc(int a, int b, CancellationToken cancellationToken)
{
  string someString = string.Empty;
  for (int i = 0; i < 200000; i++)
  {
    someString += "a";
    if (i % 1000 == 0)
      cancellationToken.ThrowIfCancellationRequested();
  }

  return a + b;
}

How do I read input character-by-character in Java?

Wrap your reader in a BufferedReader, which maintains a buffer allowing for much faster reads overall. You can then use read() to read a single character (which you'll need to cast). You can also use readLine() to fetch an entire line and then break that into individual characters. The BufferedReader also supports marking and returning, so if you need to, you can read a line multiple times.

Generally speaking, you want to use a BufferedReader or BufferedInputStream on top of whatever stream you are actually using since the buffer they maintain will make multiple reads much faster.

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Another option is where you have tables like 'type' or 'status', for example, OrderStatus, where you always want to control the Id value, create the Id (Primary Key) column without it being an Identity column is the first place.

UTL_FILE.FOPEN() procedure not accepting path for directory?

You need to register the directory with Oracle. fopen takes the name of a directory object, not the path. For example:

(you may need to login as SYS to execute these)

CREATE DIRECTORY MY_DIR AS 'C:\';

GRANT READ ON DIRECTORY MY_DIR TO SCOTT;

Then, you can refer to it in the call to fopen:

execute sal_status('MY_DIR','vin1.txt');

How to close the command line window after running a batch file?

%Started Program or Command% | taskkill /F /IM cmd.exe

Example:

notepad.exe | taskkill /F /IM cmd.exe

compare two list and return not matching items using linq

As an extension method

public static IEnumerable<TSource> AreNotEqual<TSource, TKey, TTarget>(this IEnumerable<TSource> source, Func<TSource, TKey> sourceKeySelector, IEnumerable<TTarget> target, Func<TTarget, TKey> targetKeySelector) 
{
    var targetValues = new HashSet<TKey>(target.Select(targetKeySelector));

    return source.Where(sourceValue => targetValues.Contains(sourceKeySelector(sourceValue)) == false);
}

eg.

public class Customer
{
    public int CustomerId { get; set; }
}

public class OtherCustomer
{
    public int Id { get; set; }
}


var customers = new List<Customer>()
{
    new Customer() { CustomerId = 1 },
    new Customer() { CustomerId = 2 }
};

var others = new List<OtherCustomer>()
{
    new OtherCustomer() { Id = 2 },
    new OtherCustomer() { Id = 3 }
};

var result = customers.AreNotEqual(customer => customer.CustomerId, others, other => other.Id).ToList();

Debug.Assert(result.Count == 1);
Debug.Assert(result[0].CustomerId == 1);

Check whether user has a Chrome extension installed

Another method is to expose a web-accessible resource, though this will allow any website to test if your extension is installed.

Suppose your extension's ID is aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, and you add a file (say, a transparent pixel image) as test.png in your extension's files.

Then, you expose this file to the web pages with web_accessible_resources manifest key:

  "web_accessible_resources": [
    "test.png"
  ],

In your web page, you can try to load this file by its full URL (in an <img> tag, via XHR, or in any other way):

chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/test.png

If the file loads, then the extension is installed. If there's an error while loading this file, then the extension is not installed.

// Code from https://groups.google.com/a/chromium.org/d/msg/chromium-extensions/8ArcsWMBaM4/2GKwVOZm1qMJ
function detectExtension(extensionId, callback) { 
  var img; 
  img = new Image(); 
  img.src = "chrome-extension://" + extensionId + "/test.png"; 
  img.onload = function() { 
    callback(true); 
  }; 
  img.onerror = function() { 
    callback(false); 
  };
}

Of note: if there is an error while loading this file, said network stack error will appear in the console with no possibility to silence it. When Chromecast used this method, it caused quite a bit of controversy because of this; with the eventual very ugly solution of simply blacklisting very specific errors from Dev Tools altogether by the Chrome team.


Important note: this method will not work in Firefox WebExtensions. Web-accessible resources inherently expose the extension to fingerprinting, since the URL is predictable by knowing the ID. Firefox decided to close that hole by assigning an instance-specific random URL to web accessible resources:

The files will then be available using a URL like:

moz-extension://<random-UUID>/<path/to/resource>

This UUID is randomly generated for every browser instance and is not your extension's ID. This prevents websites from fingerprinting the extensions a user has installed.

However, while the extension can use runtime.getURL() to obtain this address, you can't hard-code it in your website.

Content Security Policy "data" not working for base64 Images in Chrome 28

Try this

data to load:

<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 4 5'><path fill='#343a40' d='M2 0L0 2h4zm0 5L0 3h4z'/></svg>

get a utf8 to base64 convertor and convert the "svg" string to:

PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

and the CSP is

img-src data: image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCA0IDUn
PjxwYXRoIGZpbGw9JyMzNDNhNDAnIGQ9J00yIDBMMCAyaDR6bTAgNUwwIDNoNHonLz48L3N2Zz4=

Javascript get Object property Name

Like the other answers you can do theTypeIs = Object.keys(myVar)[0]; to get the first key. If you are expecting more keys, you can use

Object.keys(myVar).forEach(function(k) {
    if(k === "typeA") {
        // do stuff
    }
    else if (k === "typeB") {
        // do more stuff
    }
    else {
        // do something
    }
});

Android: Changing Background-Color of the Activity (Main View)

First Method

 View someView = findViewById(R.id.randomViewInMainLayout);// get Any child View

  // Find the root view
  View root = someView.getRootView()

  // Set the color
  root.setBackgroundColor(getResources().getColor(android.R.color.red));

Second Method

Add this single line after setContentView(...);

getWindow().getDecorView().setBackgroundColor(Color.WHITE);

Third Method

set background color to the rootView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF"
android:id="@+id/rootView"
</LinearLayout>

Important Thing

rootView.setBackgroundColor(0xFF00FF00); //after 0x the other four pairs are alpha,red,green,blue color. 

How can I escape latex code received through user input?

When you read the string from the GUI control, it is already a "raw" string. If you print out the string you might see the backslashes doubled up, but that's an artifact of how Python displays strings; internally there's still only a single backslash.

>>> a='\nu + \lambda + \theta'
>>> a
'\nu + \\lambda + \theta'
>>> len(a)
20
>>> b=r'\nu + \lambda + \theta'
>>> b
'\\nu + \\lambda + \\theta'
>>> len(b)
22
>>> b[0]
'\\'
>>> print b
\nu + \lambda + \theta

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

Get Cell Value from a DataTable in C#

You can iterate DataTable like this:

private void button1_Click(object sender, EventArgs e)
{
    for(int i = 0; i< dt.Rows.Count;i++)
        for (int j = 0; j <dt.Columns.Count ; j++)
        {
            object o = dt.Rows[i].ItemArray[j];
            //if you want to get the string
            //string s = o = dt.Rows[i].ItemArray[j].ToString();
        }
}

Depending on the type of the data in the DataTable cell, you can cast the object to whatever you want.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

Try rerunning the pod and running

 kubectl get pods --watch

to watch the status of the pod as it progresses.

In my case, I would only see the end result, 'CrashLoopBackOff,' but the docker container ran fine locally. So I watched the pods using the above command, and I saw the container briefly progress into an OOMKilled state, which meant to me that it required more memory.

Postgres FOR LOOP

I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.

import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
                                  , password="***"
                                  , port="5432"
                                  , database="myDB"
                                  , host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()

myList = [...]
for item in myList:
  cursor_psql.execute('''
    -- The query goes here
  ''')

connection_psql.commit()
cursor_psql.close()

Using a PHP variable in a text input value = statement

You need, for example:

<input type="text" name="idtest" value="<?php echo $idtest; ?>" />

The echo function is what actually outputs the value of the variable.

Transform DateTime into simple Date in Ruby on Rails

In Ruby 1.9.2 and above they added a .to_date function to DateTime:

http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date

This instance method doesn't appear to be present in earlier versions like 1.8.7.

Android canvas draw rectangle

The code is fine just setStyle of paint as STROKE

paint.setStyle(Paint.Style.STROKE);

How do I find out which process is locking a file using .NET?

It is very complex to invoke Win32 from C#.

You should use the tool Handle.exe.

After that your C# code have to be the following:

string fileName = @"c:\aaa.doc";//Path to locked file

Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();           
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
    Process.GetProcessById(int.Parse(match.Value)).Kill();
}

Excel VBA If cell.Value =... then

I think it would make more sense to use "Find" function in Excel instead of For Each loop. It works much much faster and it's designed for such actions. Try this:

 Sub FindSomeCells(strSearchQuery As String)   

    Set SearchRange = Worksheets("Sheet1").Range("A1:A100")
    FindWhat = strSearchQuery
    Set FoundCells = FindAll(SearchRange:=SearchRange, _
                            FindWhat:=FindWhat, _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByColumns, _
                            MatchCase:=False, _
                            BeginsWith:=vbNullString, _
                            EndsWith:=vbNullString, _
                            BeginEndCompare:=vbTextCompare)
    If FoundCells Is Nothing Then
        Debug.Print "Value Not Found"
    Else
        For Each FoundCell In FoundCells
            FoundCell.Interior.Color = XlRgbColor.rgbLightGreen
        Next FoundCell
    End If

End Sub

That subroutine searches for some string and returns a collections of cells fullfilling your search criteria. Then you can do whatever you want with the cells in that collection. Forgot to add the FindAll function definition:

Function FindAll(SearchRange As Range, _
                FindWhat As Variant, _
               Optional LookIn As XlFindLookIn = xlValues, _
                Optional LookAt As XlLookAt = xlWhole, _
                Optional SearchOrder As XlSearchOrder = xlByRows, _
                Optional MatchCase As Boolean = False, _
                Optional BeginsWith As String = vbNullString, _
                Optional EndsWith As String = vbNullString, _
                Optional BeginEndCompare As VbCompareMethod = vbTextCompare) As Range
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' FindAll
' This searches the range specified by SearchRange and returns a Range object
' that contains all the cells in which FindWhat was found. The search parameters to
' this function have the same meaning and effect as they do with the
' Range.Find method. If the value was not found, the function return Nothing. If
' BeginsWith is not an empty string, only those cells that begin with BeginWith
' are included in the result. If EndsWith is not an empty string, only those cells
' that end with EndsWith are included in the result. Note that if a cell contains
' a single word that matches either BeginsWith or EndsWith, it is included in the
' result.  If BeginsWith or EndsWith is not an empty string, the LookAt parameter
' is automatically changed to xlPart. The tests for BeginsWith and EndsWith may be
' case-sensitive by setting BeginEndCompare to vbBinaryCompare. For case-insensitive
' comparisons, set BeginEndCompare to vbTextCompare. If this parameter is omitted,
' it defaults to vbTextCompare. The comparisons for BeginsWith and EndsWith are
' in an OR relationship. That is, if both BeginsWith and EndsWith are provided,
' a match if found if the text begins with BeginsWith OR the text ends with EndsWith.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Dim FoundCell As Range
Dim FirstFound As Range
Dim LastCell As Range
Dim ResultRange As Range
Dim XLookAt As XlLookAt
Dim Include As Boolean
Dim CompMode As VbCompareMethod
Dim Area As Range
Dim MaxRow As Long
Dim MaxCol As Long
Dim BeginB As Boolean
Dim EndB As Boolean
CompMode = BeginEndCompare
If BeginsWith <> vbNullString Or EndsWith <> vbNullString Then
    XLookAt = xlPart
Else
    XLookAt = LookAt
End If
' this loop in Areas is to find the last cell
' of all the areas. That is, the cell whose row
' and column are greater than or equal to any cell
' in any Area.

For Each Area In SearchRange.Areas
    With Area
        If .Cells(.Cells.Count).Row > MaxRow Then
            MaxRow = .Cells(.Cells.Count).Row
        End If
        If .Cells(.Cells.Count).Column > MaxCol Then
            MaxCol = .Cells(.Cells.Count).Column
        End If
    End With
Next Area
Set LastCell = SearchRange.Worksheet.Cells(MaxRow, MaxCol)
On Error GoTo 0
Set FoundCell = SearchRange.Find(what:=FindWhat, _
        after:=LastCell, _
        LookIn:=LookIn, _
        LookAt:=XLookAt, _
        SearchOrder:=SearchOrder, _
        MatchCase:=MatchCase)
If Not FoundCell Is Nothing Then
    Set FirstFound = FoundCell
    Do Until False ' Loop forever. We'll "Exit Do" when necessary.
        Include = False
        If BeginsWith = vbNullString And EndsWith = vbNullString Then
            Include = True
        Else
            If BeginsWith <> vbNullString Then
                If StrComp(Left(FoundCell.Text, Len(BeginsWith)), BeginsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
            If EndsWith <> vbNullString Then
                If StrComp(Right(FoundCell.Text, Len(EndsWith)), EndsWith, BeginEndCompare) = 0 Then
                    Include = True
                End If
            End If
        End If
        If Include = True Then
            If ResultRange Is Nothing Then
                Set ResultRange = FoundCell
            Else
                Set ResultRange = Application.Union(ResultRange, FoundCell)
            End If
        End If
        Set FoundCell = SearchRange.FindNext(after:=FoundCell)
        If (FoundCell Is Nothing) Then
            Exit Do
        End If
        If (FoundCell.Address = FirstFound.Address) Then
            Exit Do
        End If
    Loop
End If
Set FindAll = ResultRange
End Function

How do I convert a file path to a URL in ASP.NET

The problem with all these answers is that they do not take virtual directories into account.

Consider:

Site named "tempuri.com/" rooted at c:\domains\site
virtual directory "~/files" at c:\data\files
virtual directory "~/files/vip" at c:\data\VIPcust\files

So:

Server.MapPath("~/files/vip/readme.txt") 
  = "c:\data\VIPcust\files\readme.txt"

But there is no way to do this:

MagicResolve("c:\data\VIPcust\files\readme.txt") 
   = "http://tempuri.com/files/vip/readme.txt"

because there is no way to get a complete list of virtual directories.

Dynamically load JS inside JS

The jQuery.getScript() method is a shorthand of the Ajax function (with the dataType attribute: $.ajax({ url: url,dataType: "script"}))

If you want the scripts to be cachable, either use RequireJS or follow jQuery's example on extending the jQuery.getScript method similar to the following.

jQuery.cachedScript = function( url, options ) {

  // Allow user to set any option except for dataType, cache, and url
  options = $.extend( options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
  console.log( textStatus );
});

Reference: jQuery.getScript() | jQuery API Documentation

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Getting Python error "from: can't read /var/mail/Bio"

for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.

Get class name using jQuery

Best way to get class name in javascript or jquery

attr() attribute function is used to get and set attribute.


Get Class

jQuery('your selector').attr('class');  // Return class

Check class exist or not

The hasClass() method checks if any of the selected elements have a specified class name.

 if(jQuery('selector').hasClass('abc-class')){
        // Yes Exist
    }else{
        // NOt exists
    }

Set Class

jQuery('your selector').attr('class','myclass');  // It will add class to your selector

Get Class on Click of button using jQuery

jQuery(document).on('click','button',function(){
     var myclass = jQuery('#selector').attr('class');
});

Add class if selector have no any class using jQuery

if ( $('#div-id' ).hasClass( 'classname' ) ) {
        // Add your code
    }

Get the second class into multiple classes using into a element

Change array position in place of [1] to get particular class.

var mysecondclass = $('#mydiv').attr('class').split(' ')[1];

Trying to use fetch and pass in mode: no-cors

The simple solution: Add the following to the very top of the php file you are requesting the data from.

header("Access-Control-Allow-Origin: *");

Can an AWS Lambda function call another

I was looking at cutting out SNS until I saw this in the Lambda client docs (Java version):

Client for accessing AWS Lambda. All service calls made using this client are blocking, and will not return until the service call completes.

So SNS has an obvious advantage: it's asynchronous. Your lambda won't wait for the subsequent lambda to complete.

UTF-8 problems while reading CSV file with fgetcsv

In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string...

So this solution helped me a lot:

/**
 * getting CSV array with UTF-8 encoding
 *
 * @param   resource    &$handle
 * @param   integer     $length
 * @param   string      $separator
 *
 * @return  array|false
 */
private function fgetcsvUTF8(&$handle, $length, $separator = ';')
{
    if (($buffer = fgets($handle, $length)) !== false)
    {
        $buffer = $this->autoUTF($buffer);
        return str_getcsv($buffer, $separator);
    }
    return false;
}

/**
 * automatic convertion windows-1250 and iso-8859-2 info utf-8 string
 *
 * @param   string  $s
 *
 * @return  string
 */
private function autoUTF($s)
{
    // detect UTF-8
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s))
        return $s;

    // detect WINDOWS-1250
    if (preg_match('#[\x7F-\x9F\xBC]#', $s))
        return iconv('WINDOWS-1250', 'UTF-8', $s);

    // assume ISO-8859-2
    return iconv('ISO-8859-2', 'UTF-8', $s);
}

Response to @manvel's answer - use str_getcsv instead of explode - because of cases like this:

some;nice;value;"and;here;comes;combinated;value";and;some;others

explode will explode string into parts:

some
nice
value
"and
here
comes
combinated
value"
and
some
others

but str_getcsv will explode string into parts:

some
nice
value
and;here;comes;combinated;value
and
some
others

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

This worked for me.

You need to run it twice once for globals followed by locals

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

for name in dir():
    if not name.startswith('_'):
        del locals()[name]

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

Just go to build.gradle(Module:App) and change the minSdkVersion to whatever you are using with emulator.

Example:

defaultConfig {
        applicationId "com.example.raghu.sample"
        // Change the version in following line
        minSdkVersion 10 // <-- Whatever you are using with Emulator
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }

How do I update a formula with Homebrew?

You will first need to update the local formulas by doing

brew update

and then upgrade the package by doing

brew upgrade formula-name

An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :

brew update && brew upgrade mongodb && brew cleanup mongodb

How to identify numpy types in python?

To get the type, use the builtin type function. With the in operator, you can test if the type is a numpy type by checking if it contains the string numpy;

In [1]: import numpy as np

In [2]: a = np.array([1, 2, 3])

In [3]: type(a)
Out[3]: <type 'numpy.ndarray'>

In [4]: 'numpy' in str(type(a))
Out[4]: True

(This example was run in IPython, by the way. Very handy for interactive use and quick tests.)

How to change the text on the action bar

You can define your title programatically using setTitle within your Activity, this method can accept either a String or an ID defined in your values/strings.xml file. Example:

public class YourActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        setTitle(R.string.your_title);
        setContentView(R.layout.main);

    }
}

C++ code file extension? .cc vs .cpp

GNU GCC recognises all of the following as C++ files, and will use C++ compilation regardless of whether you invoke it through gcc or g++: .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx.

Note the .C - case matters in GCC, .c is a C file whereas .C is a C++ file (if you let the compiler decide what it is compiling that is).

GCC also supports other suffixes to indicate special handling, for example a .ii file will be compiled as C++, but not pre-processed (intended for separately pre-processed code). All the recognised suffixes are detailed at gcc.gnu.org

How do I horizontally center an absolute positioned element inside a 100% width div?

Its easy, just wrap it in a relative box like so:

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

The relative box has a margin: 0 Auto; and, important, a width...

div background color, to change onhover

html code:

    <!DOCTYPE html>
    <html>
    <head><title>this is your web page</title></head>
    <body>
    <div class = "nicecolor"></div>
    </body>
    </html>

css code:

    .nicecolor {
      color:red;
      width:200px;
      height:200px;
     }

    .nicecolor:hover {
      color:blue;
     }

and thats how youll change your div from red to blue by hovering over it.

How do I create a list of random numbers without duplicates?

If you need to sample extremely large numbers, you cannot use range

random.sample(range(10000000000000000000000000000000), 10)

because it throws:

OverflowError: Python int too large to convert to C ssize_t

Also, if random.sample cannot produce the number of items you want due to the range being too small

 random.sample(range(2), 1000)

it throws:

 ValueError: Sample larger than population

This function resolves both problems:

import random

def random_sample(count, start, stop, step=1):
    def gen_random():
        while True:
            yield random.randrange(start, stop, step)

    def gen_n_unique(source, n):
        seen = set()
        seenadd = seen.add
        for i in (i for i in source() if i not in seen and not seenadd(i)):
            yield i
            if len(seen) == n:
                break

    return [i for i in gen_n_unique(gen_random,
                                    min(count, int(abs(stop - start) / abs(step))))]

Usage with extremely large numbers:

print('\n'.join(map(str, random_sample(10, 2, 10000000000000000000000000000000))))

Sample result:

7822019936001013053229712669368
6289033704329783896566642145909
2473484300603494430244265004275
5842266362922067540967510912174
6775107889200427514968714189847
9674137095837778645652621150351
9969632214348349234653730196586
1397846105816635294077965449171
3911263633583030536971422042360
9864578596169364050929858013943

Usage where the range is smaller than the number of requested items:

print(', '.join(map(str, random_sample(100000, 0, 3))))

Sample result:

2, 0, 1

It also works with with negative ranges and steps:

print(', '.join(map(str, random_sample(10, 10, -10, -2))))
print(', '.join(map(str, random_sample(10, 5, -5, -2))))

Sample results:

2, -8, 6, -2, -4, 0, 4, 10, -6, 8
-3, 1, 5, -1, 3

How to use jQuery to select a dropdown option?

I would do it this way

 $("#idElement").val('optionValue').trigger('change');

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

ADB not recognising Nexus 4 under Windows 7

Just to confirm a previous comment. I needed to switch my connection to Camera (PTP) mode in addition to enabling Developer options and then selecting USB Debugging from the newly appeared Developer Options.

What are CN, OU, DC in an LDAP search?

I want to add somethings different from definitions of words. Most of them will be visual.

Technically, LDAP is just a protocol that defines the method by which directory data is accessed.Necessarily, it also defines and describes how data is represented in the directory service

Data is represented in an LDAP system as a hierarchy of objects, each of which is called an entry. The resulting tree structure is called a Directory Information Tree (DIT). The top of the tree is commonly called the root (a.k.a base or the suffix).the Data (Information) Model

To navigate the DIT we can define a path (a DN) to the place where our data is (cn=DEV-India,ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com will take us to a unique entry) or we can define a path (a DN) to where we think our data is (say, ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com) then search for the attribute=value or multiple attribute=value pairs to find our target entry (or entries).

enter image description here

If you want to get more depth information, you visit here

how to make log4j to write to the console as well

Your root logger definition is a bit confused. See the log4j documentation.

This is a standard Java properties file, which means that lines are treated as key=value pairs. Your second log4j.rootLogger line is overwriting the first, which explains why you aren't seeing anything on the console appender.

You need to merge your two rootLogger definitions into one. It looks like you're trying to have DEBUG messages go to the console and INFO messages to the file. The root logger can only have one level, so you need to change your configuration so that the appenders have appropriate levels.

While I haven't verified that this is correct, I'd guess it'll look something like this:

log4j.rootLogger=DEBUG,console,file
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.file=org.apache.log4j.RollingFileAppender

Note that you also have an error in casing - you have console lowercase in one place and in CAPS in another.

Action Bar's onClick listener for the Home button

if anyone else need the solution

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();  return true;
    }

    return super.onOptionsItemSelected(item);
}

Android Canvas: drawing too large bitmap

Turns out the problem was the main image that we used on our app at the time. The actual size of the image was too large, so we compressed it. Then it worked like a charm, no loss in quality and the app ran fine on the emulator.

How to validate an Email in PHP?

User data is very important for a good developer, so don't ask again and again for same data, use some logic to correct some basic error in data.

Before validation of Email: First you have to remove all illegal characters from email.

//This will Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

after that validate your email address using this filter_var() function.

filter_var($email, FILTER_VALIDATE_EMAIL)) // To Validate the email

For e.g.

<?php
$email = "[email protected]";

// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate email
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo $email." is a valid email address";
} else {
    echo $email." is not a valid email address";
}
?>

Column/Vertical selection with Keyboard in SublimeText 3

In my case (Linux) is alt+shift up/down

 { "keys": ["alt+shift+up"], "command": "select_lines", "args": {"forward": false} },
 { "keys": ["alt+shift+down"], "command": "select_lines", "args": {"forward": true} },    

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

How to display HTML in TextView?

Whenever you write custom text view basic HTML set text feature will be get vanished form some of the devices.

So we need to do following addtional steps make is work

public class CustomTextView extends TextView {

    public CustomTextView(..) {
        // other instructions
        setText(Html.fromHtml(getText().toString()));
    }
}

How to read integer values from text file

Try this:-

File file = new File("contactids.txt");
Scanner scanner = new Scanner(file);
while(scanner.hasNextLong())
{
  // Read values here like long input = scanner.nextLong();
}

ValueError: Wrong number of items passed - Meaning and suggestions?

In general, the error ValueError: Wrong number of items passed 3, placement implies 1 suggests that you are attempting to put too many pigeons in too few pigeonholes. In this case, the value on the right of the equation

results['predictedY'] = predictedY

is trying to put 3 "things" into a container that allows only one. Because the left side is a dataframe column, and can accept multiple items on that (column) dimension, you should see that there are too many items on another dimension.

Here, it appears you are using sklearn for modeling, which is where gaussian_process.GaussianProcess() is coming from (I'm guessing, but correct me and revise the question if this is wrong).

Now, you generate predicted values for y here:

predictedY, MSE = gp.predict(testX, eval_MSE = True)

However, as we can see from the documentation for GaussianProcess, predict() returns two items. The first is y, which is array-like (emphasis mine). That means that it can have more than one dimension, or, to be concrete for thick headed people like me, it can have more than one column -- see that it can return (n_samples, n_targets) which, depending on testX, could be (1000, 3) (just to pick numbers). Thus, your predictedY might have 3 columns.

If so, when you try to put something with three "columns" into a single dataframe column, you are passing 3 items where only 1 would fit.

Change EditText hint color when using TextInputLayout

 <android.support.design.widget.TextInputLayout
        android:id="@+id/input_layout_passdword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColorHint="#d3d3d3">
        <EditText
            android:id="@+id/etaddrfess_ciwty"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            android:bottomLeftRadius="10dp"
            android:bottomRightRadius="50dp"
            android:fontFamily="@font/frutiger"
            android:gravity="start"
            android:hint="@string/address_city"
            android:padding="10dp"
            android:textColor="#000000"
            android:textColorHint="#000000"
            android:textSize="14sp"
            android:topLeftRadius="10dp"
            android:topRightRadius="10dp" />
    </android.support.design.widget.TextInputLayout>``

How to call a method function from another class?

You need to understand the difference between classes and objects. From the Java tutorial:

An object is a software bundle of related state and behavior

A class is a blueprint or prototype from which objects are created

You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new keyword.

new Date();

You will need to assign the object to a variable of the same type as the class the object was created from.

Date d = new Date();

Once you have a reference to the object you can interact with it

d.date("01", "12", "14");

The exception to this is static methods that belong to the class and are referenced through it

public class MyDate{
  public static date(){ ... }
}

...
MyDate.date();

In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.

loop through json array jquery

you could also change from the .get() method to the .getJSON() method, jQuery will then parse the string returned as data to a javascript object and/or array that you can then reference like any other javascript object/array.

using your code above, if you changed .get to .getJSON, you should get an alert of [object Object] for each element in the array. If you changed the alert to alert(item.name) you will get the names.

Python xml ElementTree from a string source?

io.StringIO is another option for getting XML into xml.etree.ElementTree:

import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()

Hovever, it does not affect the XML declaration one would assume to be in tree (although that's needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.

Update MySQL using HTML Form and PHP

Try it this way. Put the table name in quotes (``). beside put variable '".$xyz."'.

So your sql query will be like:

$sql = mysql_query("UPDATE `anstalld` SET mandag = "'.$mandag.'" WHERE namn =".$name)or die(mysql_error());

jQuery hyperlinks - href value?

You should really put a real link in there. I don't want to sound like a pedant, but that's a fairly bad habit to get into. JQuery and Ajax should always be the last thing you implement. If you have a link that goes no-where, you're not doing it right.

I'm not busting your balls, I mean that with all the best intention.

At least one JAR was scanned for TLDs yet contained no TLDs

If one wants to have the conf\logging.properties read one must (see also here) dump this file into the Servers\Tomcat v7.0 Server at localhost-config\ folder and then add the lines :

-Djava.util.logging.config.file="${workspace_loc}\Servers\Tomcat v7.0 Server at localhost-config\logging.properties" -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager

to the VM arguments of the launch configuration one is using.

This may have taken a restart or two (or not) but finally I saw in the console in bright red :

FINE: No TLD files were found in [file:/C:/Dropbox/eclipse_workspaces/javaEE/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ted2012/WEB-INF/lib/logback-classic-1.0.7.jar]. Consider adding the JAR to the tomcat.util.scan.DefaultJarScanner.jarsToSkip or org.apache.catalina.startup.TldConfig.jarsToSkip property in CATALINA_BASE/conf/catalina.properties file. //etc

I still don't know when exactly this FINE warning appears - does not appear immediately on tomcat launch EDIT: from the comment by @Stephan: "The FINE warning appears each time any change is done in the JSP file".


Bonus: To make the warning go away add in catalina.properties :

# Additional JARs (over and above the default JARs listed above) to skip when
# scanning for TLDs. The list must be a comma separated list of JAR file names.
org.apache.catalina.startup.TldConfig.jarsToSkip=logback-classic-1.0.7.jar,\
joda-time-2.1.jar,joda-time-2.1-javadoc.jar,mysql-connector-java-5.1.24-bin.jar,\
logback-core-1.0.7.jar,javax.servlet.jsp.jstl-api-1.2.1.jar

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

Python pandas: fill a dataframe row by row

df['y'] will set a column

since you want to set a row, use .loc

Note that .ix is equivalent here, yours failed because you tried to assign a dictionary to each element of the row y probably not what you want; converting to a Series tells pandas that you want to align the input (for example you then don't have to to specify all of the elements)

In [7]: df = pandas.DataFrame(columns=['a','b','c','d'], index=['x','y','z'])

In [8]: df.loc['y'] = pandas.Series({'a':1, 'b':5, 'c':2, 'd':3})

In [9]: df
Out[9]: 
     a    b    c    d
x  NaN  NaN  NaN  NaN
y    1    5    2    3
z  NaN  NaN  NaN  NaN

Get the year from specified date php

You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there

$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
     if(strlen($parts[$i]) == 4)
     {
          $year = $parts[$i];
          break;
      }
  }

Convert Unix timestamp into human readable date using MySQL

Why bother saving the field as readable? Just us AS

SELECT theTimeStamp, FROM_UNIXTIME(theTimeStamp) AS readableDate
               FROM theTable
               WHERE theTable.theField = theValue;

EDIT: Sorry, we store everything in milliseconds not seconds. Fixed it.

IO Error: The Network Adapter could not establish the connection

Either:

  1. The database isn't running
  2. You got the URL wrong
  3. There is a firewall in the way.

(This strange error message is produced by Oracle's JDBC driver when it can't connect to the database server. 'Network adapter' appears to refer to some component of their code, which isn't very useful. Real network adapters (NICs) don't establish connections at all: TCP protocol stacks do that. It would have been a lot more useful if they had just let the original ConnectException be thrown, or at least used its error message and let it appear in the stack trace.)

Function passed as template argument

Came here with the additional requirement, that also parameter/return types should vary. Following Ben Supnik this would be for some type T

typedef T(*binary_T_op)(T, T);

instead of

typedef int(*binary_int_op)(int, int);

The solution here is to put the function type definition and the function template into a surrounding struct template.

template <typename T> struct BinOp
{
    typedef T(*binary_T_op )(T, T); // signature for all valid template params
    template<binary_T_op op>
    T do_op(T a, T b)
    {
       return op(a,b);
    }
};


double mulDouble(double a, double b)
{
    return a * b;
}


BinOp<double> doubleBinOp;

double res = doubleBinOp.do_op<&mulDouble>(4, 5);

Alternatively BinOp could be a class with static method template do_op(...), then called as

double res = BinOp<double>::do_op<&mulDouble>(4, 5);

Target elements with multiple classes, within one rule

Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

The following:

.blue-border, .background {
    border: 1px solid #00f;
    background: #fff;
}

is for when you want to add styles to elements that have either the blue-border or background class, for example:

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

would all get a blue border and white background applied to them.

However, the accepted answer is different.

.blue-border.background {
    border: 1px solid #00f;
    background: #fff;
}

This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

Git asks for username every time I push

Add new SSH keys as described in this article on GitHub.

If Git still asks you for username & password, try changing https://github.com/ to [email protected]: in remote URL:

$ git config remote.origin.url 
https://github.com/dir/repo.git

$ git config remote.origin.url "[email protected]:dir/repo.git"

ValueError when checking if variable is None or numpy.array

To stick to == without consideration of the other type, the following is also possible.
type(a) == type(None)

How can I reset or revert a file to a specific revision?

I think I've found it....from http://www-cs-students.stanford.edu/~blynn/gitmagic/ch02.html

Sometimes you just want to go back and forget about every change past a certain point because they're all wrong.

Start with:

$ git log

which shows you a list of recent commits, and their SHA1 hashes.

Next, type:

$ git reset --hard SHA1_HASH

to restore the state to a given commit and erase all newer commits from the record permanently.

How to run multiple Python versions on Windows

Just call the correct executable

Width of input type=text element

The visible width of an element is width + padding + border + outline, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width on the input, or making your div wider.

jQuery & CSS - Remove/Add display:none

jQuery provides you with:

$(".news").hide();
$(".news").show();

You can then easily show and hide the element(s).

invalid operands of types int and double to binary 'operator%'

Because % is only defined for integer types. That's the modulus operator.

5.6.2 of the standard:

The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]

As Oli pointed out, you can use fmod(). Don't forget to include math.h.

C# Passing Function as Argument

There are a couple generic types in .Net (v2 and later) that make passing functions around as delegates very easy.

For functions with return types, there is Func<> and for functions without return types there is Action<>.

Both Func and Action can be declared to take from 0 to 4 parameters. For example, Func < double, int > takes one double as a parameter and returns an int. Action < double, double, double > takes three doubles as parameters and returns nothing (void).

So you can declare your Diff function to take a Func:

public double Diff(double x, Func<double, double> f) {
    double h = 0.0000001;

    return (f(x + h) - f(x)) / h;
}

And then you call it as so, simply giving it the name of the function that fits the signature of your Func or Action:

double result = Diff(myValue, Function);

You can even write the function in-line with lambda syntax:

double result = Diff(myValue, d => Math.Sqrt(d * 3.14));

How do I determine k when using k-means clustering?

My idea is to use Silhouette Coefficient to find the optimal cluster number(K). Details explanation is here.

Python IndentationError unindent does not match any outer indentation level

i have done proper indentation with spaces but syoll it was throwing error. Then I removed al the spaces and use Tab then it started working. thx

git pull error :error: remote ref is at but expected

Just delete the folders and files under \.git\refs\remotes\origin. Works, when u don't have unpushed changes.

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

In Java 8 you can use Files.write() method with two arguments: Path and List<String>, something like this:

List<String> clubNames = clubs.stream()
    .map(Club::getName)
    .collect(Collectors.toList())

try {
    Files.write(Paths.get(fileName), clubNames);
} catch (IOException e) {
    log.error("Unable to write out names", e);
}

Rails params explained?

On the Rails side, params is a method that returns an ActionController::Parameters object. See https://stackoverflow.com/a/44070358/5462485

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

> sudo nano /etc/mysql/my.cnf

Enter below

[mysqld]
sql_mode = ""

Ctrl + O => Y = Ctrl + X

> sudo service mysql restart

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

Hide header in stack navigator React navigation

If someone searching how to toggle header so in componentDidMount write something like:

  this.props.navigation.setParams({
      hideHeader: true,
  });

When

static navigationOptions = ({ navigation }) => {
    const {params = {}} = navigation.state;

    if (params.hideHeader) {
      return {
        header: null,
      }
    }

    return {
        headerLeft: <Text>Hi</Text>,
        headerRight: <Text>Hi</Text>,
        headerTitle: <Text>Hi</Text>
    };
};

And somewhere when event finish job:

this.props.navigation.setParams({
  hideHeader: false,
});

How can I sort an ArrayList of Strings in Java?

Take a look at the Collections.sort(List<T> list).

You can simply remove the first element, sort the list and then add it back again.

How can I create an array with key value pairs?

My PHP is a little rusty, but I believe you're looking for indexed assignment. Simply use:

$catList[$row["datasource_id"]] = $row["title"];

In PHP arrays are actually maps, where the keys can be either integers or strings. Check out PHP: Arrays - Manual for more information.

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

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

On Windows 10 I had to install ASP.NET 3.5 and ASP.NET 4.6 under Internet Information Services (the other boxes automatically check themselves):

enter image description here

ERROR 2006 (HY000): MySQL server has gone away

if none of this answers solves you the problem, I solved it by removing the tables and creating them again automatically in this way:

when creating the backup, first backup structure and be sure of add:
DROP TABLE / VIEW / PROCEDURE / FUNCTION / EVENT
CREATE PROCEDURE / FUNCTION / EVENT
IF NOT EXISTS
AUTO_INCREMENT

then just use this backup with your db and it will remove and recreate the tables you need.

Then you backup just data, and do the same, and it will work.

AngularJS 1.2 $injector:modulerr

A noob error can be forgetting to include the module js

<script src="app/modules/myModule.js"></script>

files in the index.html at all

Wrap text in <td> tag

Actually wrapping of text happens automatically in tables. The blunder people commit while testing is to hypothetically assume a long string like "ggggggggggggggggggggggggggggggggggggggggggggggg" and complain that it doesn't wrap. Practically there is no word in English that is this long and even if there is, there is a faint chance that it will be used within that <td>.

Try testing with sentences like "Counterposition is superstitious in predetermining circumstances".

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

I found the answer, and in spite of what I reported, it was NOT browser specific. The bug was in my function code, and would have occurred in any browser. It boils down to this. I had two lines in my code that were FireFox/FireBug specific. They used console.log. In IE, they threw an error, so I commented them out (or so I thought). I did a crappy job commenting them out, and broke the bracketing in my function.

Original Code (with console.log in it):

if (sxti.length <= 50) console.log('sxti=' + sxti);
if (sxph.length <= 50) console.log('sxph=' + sxph);

Broken Code (misplaced brackets inside comments):

if (sxti.length <= 50) { //console.log('sxti=' + sxti); }
if (sxph.length <= 50) { //console.log('sxph=' + sxph); }

Fixed Code (fixed brackets outside comments):

if (sxti.length <= 50) { }//console.log('sxti=' + sxti);
if (sxph.length <= 50) { }//console.log('sxph=' + sxph);

So, it was my own sloppy coding. The function really wasn't defined, because a syntax error kept it from being closed.

Oh well, live and learn. ;)

How to redraw DataTable with new data

The accepted answer calls the draw function twice. I can't see why that would be needed. In fact, if your new data has the same columns as the old data, you can accomplish this in one line:

datatable.clear().rows.add(newData).draw();

Get 2 Digit Number For The Month

SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')

Android ImageView Fixing Image Size

I had the same issue and this helped me.

<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitXY"
    />

How to set up devices for VS Code for a Flutter emulator

For those people using a Mac you can go to your terminal and type

$ open -a Simulator.app

and this command will open the simulator.

After that, just go to the Debug option and tap on "Start Debugging"

enter image description here

If you want to test with an Android Emulator:

What I did was to go first to Android Studio and open a virtual Device with AVD Manager. After that you'll see another devices in your Visual Studio Code

enter image description here

In the bottom right you'll see now that you have 2 devices connected. Now, you can test with any of this devices.

Android overlay a view ontop of everything?

Simply use RelativeLayout or FrameLayout. The last child view will overlay everything else.

Android supports a pattern which Cocoa Touch SDK doesn't: Layout management.
Layout for iPhone means to position everything absolute (besides some strech factors). Layout in android means that children will be placed in relation to eachother.

Example (second EditText will completely cover the first one):

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/root_view">

    <EditText
        android:layout_width="fill_parent"
        android:id="@+id/editText1"
        android:layout_height="fill_parent">
    </EditText>

    <EditText
        android:layout_width="fill_parent"
        android:id="@+id/editText2"
        android:layout_height="fill_parent">
        <requestFocus></requestFocus>
    </EditText>

</FrameLayout>

FrameLayout is some kind of view stack. Made for special cases.

RelativeLayout is pretty powerful. You can define rules like View A has to align parent layout bottom, View B has to align A bottom to top, etc

Update based on comment

Usually you set the content with setContentView(R.layout.your_layout) in onCreate (it will inflate the layout for you). You can do that manually and call setContentView(inflatedView), there's no difference.

The view itself might be a single view (like TextView) or a complex layout hierarchy (nested layouts, since all layouts are views themselves).

After calling setContentView your activity knows what its content looks like and you can use (FrameLayout) findViewById(R.id.root_view) to retrieve any view int this hierarchy (General pattern (ClassOfTheViewWithThisId) findViewById(R.id.declared_id_of_view)).

Datatables - Setting column width

you should use "bAutoWidth" property of datatable and give width to each td/column in %

 $(".table").dataTable({"bAutoWidth": false , 
aoColumns : [
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "15%"},
      { "sWidth": "10%"},
    ]
});

Hope this will help.

Android emulator doesn't take keyboard input - SDK tools rev 20

Here is some workaround that actually worked for me, it is the same solution as in the most popular answer - just add hw.keyboard=yes to config.ini but since this didn't work for me I additionally

  1. renamed config.ini (any name will do) to something like consssssfig.ini
  2. restarted emulator (obviously it didn't start)
  3. renamed config.ini back again
  4. (I am not sure if relevant) I added this new parameter (hw.keyboard=yes) at the beggining of config.ini file

Undefined symbols for architecture arm64

This error consumed my whole day so thought of writing what really worked for me

  1. delete .xworkspace
  2. delete podfile.lock
  3. delete the Pods folder/directory

"DO NOT DELETE PODFILE"

After all this, CLEAN(OPTION + SHIFT + CMD + K) --> BUILD(CMD + B) --> RUN(CMD + R)

I hope this really works for you :)

Select first empty cell in column F starting from row 1. (without using offset )

I think a Do Until-loop is cleaner, shorter and more appropriate here:

Public Sub SelectFirstBlankCell(col As String)
    Dim Column_Index as Integer
    Dim Row_Counter as 

    Column_Index = Range(col & 1).Column
    Row_Counter = 1

    Do Until IsEmpty(Cells(Row_Counter, 1))
        Row_Counter = Row_Counter + 1
    Loop

    Cells(Row_Counter, Column_Index).Select

HTML Agility pack - parsing tables

Line from above answer:

HtmlDocument doc = new HtmlDocument();

This doesn't work in VS 2015 C#. You cannot construct an HtmlDocument any more.

Another MS "feature" that makes things more difficult to use. Try HtmlAgilityPack.HtmlWeb and check out this link for some sample code.

PHP Change Array Keys

If you have an array of keys that you want to use then use array_combine

Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:

$list = array_combine($keys, array_values($list));

List will now be array('a' => 'blabla 1', ...) etc.

You have to use array_values to extract just the values from the array and not the old, numeric, keys.

That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:

foreach ($list as $k => $v) {
   unset ($list[$k]);

   $new_key =  *some logic here*

   $list[$new_key] = $v;
}

I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.

bootstrap multiselect get selected values

Shorter version:

$('#multiselect1').multiselect({
    ...
    onChange: function() {
        console.log($('#multiselect1').val());
    }
}); 

Install IPA with iTunes 11

For iTunes 11:

  1. open your iTunes "Side Bar" by going to View -> Show Side Bar
  2. drag the mobileprovision and ipa files to your iTunes "Apps" under LIBRARY
  3. open you device Apps from DEVICES and click install for the application and wait for iTunes to sync

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

Clearing my form inputs after submission

since you are using jquery library, i would advise you utilize the reset() method.

Firstly, add an id attribute to the form tag

<form id='myForm'>

Then on completion, clear your input fields as:

$('#myForm')[0].reset();

Adding backslashes without escaping [Python]

Python treats \ in literal string in a special way.
This is so you can type '\n' to mean newline or '\t' to mean tab
Since '\&' doesn't mean anything special to Python, instead of causing an error, the Python lexical analyser implicitly adds the extra \ for you.

Really it is better to use \\& or r'\&' instead of '\&'

The r here means raw string and means that \ isn't treated specially unless it is right before the quote character at the start of the string.

In the interactive console, Python uses repr to display the result, so that is why you see the double '\'. If you print your string or use len(string) you will see that it is really only the 2 characters

Some examples

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

To Clarify the point Peter makes in his comment see this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as “(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

strcpy() error in Visual studio 2012

For my problem, I removed the #include <glui.h> statement and it ran without a problem.

converting CSV/XLS to JSON?

You can try this tool I made:

Mr. Data Converter

It converts to JSON, XML and others.

It's all client side, too, so your data never leaves your computer.

Converting a Date object to a calendar object

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

How to get history on react-router v4?

You just need to have a module that exports a history object. Then you would import that object throughout your project.

// history.js
import { createBrowserHistory } from 'history'

export default createBrowserHistory({
  /* pass a configuration object here if needed */
})

Then, instead of using one of the built-in routers, you would use the <Router> component.

// index.js
import { Router } from 'react-router-dom'
import history from './history'
import App from './App'

ReactDOM.render((
  <Router history={history}>
    <App />
  </Router>
), holder)
// some-other-file.js
import history from './history'
history.push('/go-here')

Getting the first index of an object

You could do something like this:

var object = {
    foo:{a:'first'},
    bar:{},
    baz:{}
}


function getAttributeByIndex(obj, index){
  var i = 0;
  for (var attr in obj){
    if (index === i){
      return obj[attr];
    }
    i++;
  }
  return null;
}


var first = getAttributeByIndex(object, 0); // returns the value of the
                                            // first (0 index) attribute
                                            // of the object ( {a:'first'} )

How to get the first word in the string

Use this regex

^\w+

\w+ matches 1 to many characters.

\w is similar to [a-zA-Z0-9_]

^ depicts the start of a string


About Your Regex

Your regex (.*)?[ ] should be ^(.*?)[ ] or ^(.*?)(?=[ ]) if you don't want the space

Animate visibility modes, GONE and VISIBLE

Well there is a very easy way, but just setting android:animateLayoutChanges="true" will not work. You need to enableTransitionType in you activity. Check this link for more info: http://www.thecodecity.com/2018/03/android-animation-on-view-visibility.html