Programs & Examples On #Image preloader

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?

Answer update of 13-October-2018

To initiate a browsing context using Selenium driven ChromeDriver now you can just set the --headless property to true through an instance of Options() class as follows:

  • Effective code block:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.headless = True
    driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized")
    driver.quit()
    

Answer update of 23-April-2018

Invoking in mode programmatically have become much easier with the availability of the method set_headless(headless=True) as follows :

  • Documentation :

    set_headless(headless=True)
        Sets the headless argument
    
        Args:
            headless: boolean value indicating to set the headless option
    
  • Sample Code :

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.set_headless(headless=True)
    driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized")
    driver.quit()
    

Note : --disable-gpu argument is implemented internally.


Original Answer of Mar 30 '2018

While working with Selenium Client 3.11.x, ChromeDriver v2.38 and Google Chrome v65.0.3325.181 in Headless mode you have to consider the following points :

  • You need to add the argument --headless to invoke Chrome in headless mode.

  • For Windows OS systems you need to add the argument --disable-gpu

  • As per Headless: make --disable-gpu flag unnecessary --disable-gpu flag is not required on Linux Systems and MacOS.

  • As per SwiftShader fails an assert on Windows in headless mode --disable-gpu flag will become unnecessary on Windows Systems too.

  • Argument start-maximized is required for a maximized Viewport.

  • Here is the link to details about Viewport.

  • You may require to add the argument --no-sandbox to bypass the OS security model.

  • Effective code block :

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--headless") # Runs Chrome in headless mode.
    options.add_argument('--no-sandbox') # Bypass OS security model
    options.add_argument('--disable-gpu')  # applicable to windows os only
    options.add_argument('start-maximized') # 
    options.add_argument('disable-infobars')
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized on Windows OS")
    
  • Effective code block :

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("--headless") # Runs Chrome in headless mode.
    options.add_argument('--no-sandbox') # # Bypass OS security model
    options.add_argument('start-maximized')
    options.add_argument('disable-infobars')
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path='/path/to/chromedriver')
    driver.get("http://google.com/")
    print ("Headless Chrome Initialized on Linux OS")
    

Outro

How to make firefox headless programmatically in Selenium with python?


tl; dr

Here is the link to the Sandbox story.

What is the Python equivalent of static variables inside a function?

Here is a fully encapsulated version that doesn't require an external initialization call:

def fn():
    fn.counter=vars(fn).setdefault('counter',-1)
    fn.counter+=1
    print (fn.counter)

In Python, functions are objects and we can simply add, or monkey patch, member variables to them via the special attribute __dict__. The built-in vars() returns the special attribute __dict__.

EDIT: Note, unlike the alternative try:except AttributeError answer, with this approach the variable will always be ready for the code logic following initialization. I think the try:except AttributeError alternative to the following will be less DRY and/or have awkward flow:

def Fibonacci(n):
   if n<2: return n
   Fibonacci.memo=vars(Fibonacci).setdefault('memo',{}) # use static variable to hold a results cache
   return Fibonacci.memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2)) # lookup result in cache, if not available then calculate and store it

EDIT2: I only recommend the above approach when the function will be called from multiple locations. If instead the function is only called in one place, it's better to use nonlocal:

def TheOnlyPlaceStaticFunctionIsCalled():
    memo={}
    def Fibonacci(n):
       nonlocal memo  # required in Python3. Python2 can see memo
       if n<2: return n
       return memo.setdefault(n,Fibonacci(n-1)+Fibonacci(n-2))
    ...
    print (Fibonacci(200))
    ...

jQuery Button.click() event is triggered twice

in my case, i was using the change command like this way

$(document).on('change', '.select-brand', function () {...my codes...});

and then i changed the way to

$('.select-brand').on('change', function () {...my codes...});

and it solved my problem.

How to remove Left property when position: absolute?

left: initial

This will also set left back to the browser default.

But important to know property: initial is not supported in IE.

Editing in the Chrome debugger

  1. Place a breakpoint
  2. Right click on the breakpoint and select 'Edit breakpoint'
  3. Insert your code. Use SHIFT+ENTER to create a new line.

enter image description here

DTO pattern: Best way to copy properties between two objects

I suggest you should use one of the mappers' libraries: Mapstruct, ModelMapper, etc. With Mapstruct your mapper will look like:

@Mapper
public interface UserMapper {     
    UserMapper INSTANCE = Mappers.getMapper( UserMapper.class ); 

    UserDTO toDto(User user);
}

The real object with all getters and setters will be automatically generated from this interface. You can use it like:

UserDTO userDTO = UserMapper.INSTANCE.toDto(user);

You can also add some logic for your activeText filed using @AfterMapping annotation.

What is 'PermSize' in Java?

This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.

There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.

(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.

Change name of folder when cloning from GitHub?

In case you want to clone a specific branch only, then,

git clone -b <branch-name> <repo-url> <destination-folder-name>

for example,

git clone -b dev https://github.com/sferik/sign-in-with-twitter.git signin

How to refresh an IFrame using Javascript?

This should help:

document.getElementById('FrameID').contentWindow.location.reload(true);

EDIT: Fixed the object name as per @Joro's comment.

How to call a button click event from another method

You can call the button_click event by simply passing the arguments to it:

private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}

private void ChildNode_Click(object sender, RoutedEventArgs args)
{
   SubGraphButton_Click(sender, args);
}

Best practices for copying files with Maven

To summarize some of the fine answers above: Maven is designed to build modules and copy the results to a Maven repository. Any copying of modules to a deployment/installer-input directory must be done outside the context of Maven's core functionality, e.g. with the Ant/Maven copy command.

Python: Append item to list N times

I had to go another route for an assignment but this is what I ended up with.

my_array += ([x] * repeated_times)

Add and Remove Views in Android Dynamically?

This is my general way:

View namebar = view.findViewById(R.id.namebar);
ViewGroup parent = (ViewGroup) namebar.getParent();
if (parent != null) {
    parent.removeView(namebar);
}

Django Admin - change header 'Django administration' text

You can use these following lines in your main urls.py

you can add the text in the quotes to be displayed

To replace the text Django admin use admin.site.site_header = ""

To replace the text Site Administration use admin.site.site_title = ""

To replace the site name you can use admin.site.index_title = ""

To replace the url of the view site button you can use admin.site.site_url = ""

Prepend line to beginning of a file

In modes 'a' or 'a+', any writing is done at the end of the file, even if at the current moment when the write() function is triggered the file's pointer is not at the end of the file: the pointer is moved to the end of file before any writing. You can do what you want in two manners.

1st way, can be used if there are no issues to load the file into memory:

def line_prepender(filename, line):
    with open(filename, 'r+') as f:
        content = f.read()
        f.seek(0, 0)
        f.write(line.rstrip('\r\n') + '\n' + content)

2nd way:

def line_pre_adder(filename, line_to_prepend):
    f = fileinput.input(filename, inplace=1)
    for xline in f:
        if f.isfirstline():
            print line_to_prepend.rstrip('\r\n') + '\n' + xline,
        else:
            print xline,

I don't know how this method works under the hood and if it can be employed on big big file. The argument 1 passed to input is what allows to rewrite a line in place; the following lines must be moved forwards or backwards in order that the inplace operation takes place, but I don't know the mechanism

Unix command to find lines common in two files

While

grep -v -f 1.txt 2.txt > 3.txt

gives you the differences of two files (what is in 2.txt and not in 1.txt), you could easily do a

grep -f 1.txt 2.txt > 3.txt

to collect all common lines, which should provide an easy solution to your problem. If you have sorted files, you should take comm nonetheless. Regards!

Histogram Matplotlib

If you're willing to use pandas:

pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')

Received fatal alert: handshake_failure through SSLHandshakeException

This issue is occurring because of the java version. I was using 1.8.0.231 JDK and getting this error. I have degraded my java version from 1.8.0.231 to 1.8.0.171, Now It is working fine.

Best way to access a control on another form in Windows Forms?

@Lars, good call on the passing around of Form references, seen it as well myself. Nasty. Never seen them passed them down to the BLL layer though! That doesn't even make sense! That could have seriously impacted performance right? If somewhere in the BLL the reference was kept, the form would stay in memory right?

You have my sympathy! ;)


@Ed, RE your comment about making the Forms UserControls. Dylan has already pointed out that the root form instantiates many child forms, giving the impression of an MDI application (where I am assuming users may want to close various Forms). If I am correct in this assumption, I would think they would be best kept as forms. Certainly open to correction though :)

Creating pdf files at runtime in c#

Well, free and not-for-free, I use WebSuperGoo ABCpdf .NET component, that I just love it!

not-for-free because you need to pay for it.

for free because even if you have to pay, they have a trial version and you can request a free license if you do not mind that, in your site show "This site uses WebSuperGoo ABCpdf .NET component" with a link to their website.

I did that and I got a free license (version 5 in that time) so, I can say that it works (even if the website is no longer online) - I still have and use the component ~:)

A wonderful thing that I love with this is that you can do everything that you can thing off with this, create PDF forms and dynamically fill them and send to user by mail or have them to download it, create a pdf from scratch, convert HTML pages into PDF, etc etc etc, please read the documentation, it is a wonderful component.

Reverse order of foreach list items

Assuming you just need to reverse an indexed array (not associative or multidimensional) a simple for loop would suffice:

$fruits = ['bananas', 'apples', 'pears'];
for($i = count($fruits)-1; $i >= 0; $i--) {
    echo $fruits[$i] . '<br>';
} 

How to Sort Date in descending order From Arraylist Date in android?

Create Arraylist<Date> of Date class. And use Collections.sort() for ascending order.

See sort(List<T> list)

Sorts the specified list into ascending order, according to the natural ordering of its elements.

For Sort it in descending order See Collections.reverseOrder()

Collections.sort(yourList, Collections.reverseOrder());

$ is not a function - jQuery error

In my case I was using jquery on my typescript file:

import * as $ from "jquery";

But this line gives me back an Object $ and it does not allow to use as a function (I can not use $('my-selector')). It solves my problem this lines, I hope it could help anyone else:

import * as JQuery from "jquery";
const $ = JQuery.default;

Create an array of integers property in Objective-C

I found all the previous answers too much complicated. I had the need to store an array of some ints as a property, and found the ObjC requirement of using a NSArray an unneeded complication of my software.

So I used this:

typedef struct my10ints {
    int arr[10];
} my10ints;

@interface myClasss : NSObject

@property my10ints doubleDigits;

@end

This compiles cleanly using Xcode 6.2.

My intention was to use it like this:

myClass obj;
obj.doubleDigits.arr[0] = 4;

HOWEVER, this does not work. This is what it produces:

int i = 4;
myClass obj;
obj.doubleDigits.arr[0] = i;
i = obj.doubleDigits.arr[0];
// i is now 0 !!!

The only way to use this correctly is:

int i = 4;
myClass obj;
my10ints ints;
ints = obj.doubleDigits;
ints.arr[0] = i;
obj.doubleDigits = ints;
i = obj.doubleDigits.arr[0];
// i is now 4

and so, defeats completely my point (avoiding the complication of using a NSArray).

Log all requests from the python-requests module

Having a script or even a subsystem of an application for a network protocol debugging, it's desired to see what request-response pairs are exactly, including effective URLs, headers, payloads and the status. And it's typically impractical to instrument individual requests all over the place. At the same time there are performance considerations that suggest using single (or few specialised) requests.Session, so the following assumes that the suggestion is followed.

requests supports so called event hooks (as of 2.23 there's actually only response hook). It's basically an event listener, and the event is emitted before returning control from requests.request. At this moment both request and response are fully defined, hence can be logged.

import logging

import requests


logger = logging.getLogger('httplogger')

def logRoundtrip(response, *args, **kwargs):
    extra = {'req': response.request, 'res': response}
    logger.debug('HTTP roundtrip', extra=extra)

session = requests.Session()
session.hooks['response'].append(logRoundtrip)

That's basically how to log all HTTP round-trips of a session.

Formatting HTTP round-trip log records

For the logging above to be useful there can be specialised logging formatter that understands req and res extras on logging records. It can look like this:

import textwrap

class HttpFormatter(logging.Formatter):   

    def _formatHeaders(self, d):
        return '\n'.join(f'{k}: {v}' for k, v in d.items())

    def formatMessage(self, record):
        result = super().formatMessage(record)
        if record.name == 'httplogger':
            result += textwrap.dedent('''
                ---------------- request ----------------
                {req.method} {req.url}
                {reqhdrs}

                {req.body}
                ---------------- response ----------------
                {res.status_code} {res.reason} {res.url}
                {reshdrs}

                {res.text}
            ''').format(
                req=record.req,
                res=record.res,
                reqhdrs=self._formatHeaders(record.req.headers),
                reshdrs=self._formatHeaders(record.res.headers),
            )

        return result

formatter = HttpFormatter('{asctime} {levelname} {name} {message}', style='{')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logging.basicConfig(level=logging.DEBUG, handlers=[handler])

Now if you do some requests using the session, like:

session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')

The output to stderr will look as follows.

2020-05-14 22:10:13,224 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): httpbin.org:443
2020-05-14 22:10:13,695 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
2020-05-14 22:10:13,698 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/user-agent
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive

None
---------------- response ----------------
200 OK https://httpbin.org/user-agent
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: application/json
Content-Length: 45
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

{
  "user-agent": "python-requests/2.23.0"
}


2020-05-14 22:10:13,814 DEBUG urllib3.connectionpool https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
2020-05-14 22:10:13,818 DEBUG httplogger HTTP roundtrip
---------------- request ----------------
GET https://httpbin.org/status/200
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive

None
---------------- response ----------------
200 OK https://httpbin.org/status/200
Date: Thu, 14 May 2020 20:10:13 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

A GUI way

When you have a lot of queries, having a simple UI and a way to filter records comes at handy. I'll show to use Chronologer for that (which I'm the author of).

First, the hook has be rewritten to produce records that logging can serialise when sending over the wire. It can look like this:

def logRoundtrip(response, *args, **kwargs): 
    extra = {
        'req': {
            'method': response.request.method,
            'url': response.request.url,
            'headers': response.request.headers,
            'body': response.request.body,
        }, 
        'res': {
            'code': response.status_code,
            'reason': response.reason,
            'url': response.url,
            'headers': response.headers,
            'body': response.text
        },
    }
    logger.debug('HTTP roundtrip', extra=extra)

session = requests.Session()
session.hooks['response'].append(logRoundtrip)

Second, logging configuration has to be adapted to use logging.handlers.HTTPHandler (which Chronologer understands).

import logging.handlers

chrono = logging.handlers.HTTPHandler(
  'localhost:8080', '/api/v1/record', 'POST', credentials=('logger', ''))
handlers = [logging.StreamHandler(), chrono]
logging.basicConfig(level=logging.DEBUG, handlers=handlers)

Finally, run Chronologer instance. e.g. using Docker:

docker run --rm -it -p 8080:8080 -v /tmp/db \
    -e CHRONOLOGER_STORAGE_DSN=sqlite:////tmp/db/chrono.sqlite \
    -e CHRONOLOGER_SECRET=example \
    -e CHRONOLOGER_ROLES="basic-reader query-reader writer" \
    saaj/chronologer \
    python -m chronologer -e production serve -u www-data -g www-data -m

And run the requests again:

session.get('https://httpbin.org/user-agent')
session.get('https://httpbin.org/status/200')

The stream handler will produce:

DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): httpbin.org:443
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /user-agent HTTP/1.1" 200 45
DEBUG:httplogger:HTTP roundtrip
DEBUG:urllib3.connectionpool:https://httpbin.org:443 "GET /status/200 HTTP/1.1" 200 0
DEBUG:httplogger:HTTP roundtrip

Now if you open http://localhost:8080/ (use "logger" for username and empty password for the basic auth popup) and click "Open" button, you should see something like:

Screenshot of Chronologer

Create list or arrays in Windows Batch

Array type does not exist

There is no 'array' type in batch files, which is both an upside and a downside at times, but there are workarounds.

Here's a link that offers a few suggestions for creating a system for yourself similar to an array in a batch: http://hypftier.de/en/batch-tricks-arrays.

  • As for echoing to a file echo variable >> filepath works for echoing the contents of a variable to a file,
  • and echo. (the period is not a typo) works for echoing a newline character.

I think that these two together should work to accomplish what you need.

Further reading

The definitive guide to form-based website authentication

First, a strong caveat that this answer is not the best fit for this exact question. It should definitely not be the top answer!

I will go ahead and mention Mozilla’s proposed BrowserID (or perhaps more precisely, the Verified Email Protocol) in the spirit of finding an upgrade path to better approaches to authentication in the future.

I’ll summarize it this way:

  1. Mozilla is a nonprofit with values that align well with finding good solutions to this problem.
  2. The reality today is that most websites use form-based authentication
  3. Form-based authentication has a big drawback, which is an increased risk of phishing. Users are asked to enter sensitive information into an area controlled by a remote entity, rather than an area controlled by their User Agent (browser).
  4. Since browsers are implicitly trusted (the whole idea of a User Agent is to act on behalf of the User), they can help improve this situation.
  5. The primary force holding back progress here is deployment deadlock. Solutions must be decomposed into steps which provide some incremental benefit on their own.
  6. The simplest decentralized method for expressing an identity that is built into the internet infrastructure is the domain name.
  7. As a second level of expressing identity, each domain manages its own set of accounts.
  8. The form “account@domain” is concise and supported by a wide range of protocols and URI schemes. Such an identifier is, of course, most universally recognized as an email address.
  9. Email providers are already the de-facto primary identity providers online. Current password reset flows usually let you take control of an account if you can prove that you control that account’s associated email address.
  10. The Verified Email Protocol was proposed to provide a secure method, based on public key cryptography, for streamlining the process of proving to domain B that you have an account on domain A.
  11. For browsers that don’t support the Verified Email Protocol (currently all of them), Mozilla provides a shim which implements the protocol in client-side JavaScript code.
  12. For email services that don’t support the Verified Email Protocol, the protocol allows third parties to act as a trusted intermediary, asserting that they’ve verified a user’s ownership of an account. It is not desirable to have a large number of such third parties; this capability is intended only to allow an upgrade path, and it is much preferred that email services provide these assertions themselves.
  13. Mozilla offers their own service to act like such a trusted third party. Service Providers (that is, Relying Parties) implementing the Verified Email Protocol may choose to trust Mozilla's assertions or not. Mozilla’s service verifies users’ account ownership using the conventional means of sending an email with a confirmation link.
  14. Service Providers may, of course, offer this protocol as an option in addition to any other method(s) of authentication they might wish to offer.
  15. A big user interface benefit being sought here is the “identity selector”. When a user visits a site and chooses to authenticate, their browser shows them a selection of email addresses (“personal”, “work”, “political activism”, etc.) they may use to identify themselves to the site.
  16. Another big user interface benefit being sought as part of this effort is helping the browser know more about the user’s session – who they’re signed in as currently, primarily – so it may display that in the browser chrome.
  17. Because of the distributed nature of this system, it avoids lock-in to major sites like Facebook, Twitter, Google, etc. Any individual can own their own domain and therefore act as their own identity provider.

This is not strictly “form-based authentication for websites”. But it is an effort to transition from the current norm of form-based authentication to something more secure: browser-supported authentication.

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

Google Chrome default opening position and size

First, close all instances of Google Chrome. There should be no instances of chrome.exe running in the Windows Task Manager. Then

  • Go to %LOCALAPPDATA%\Google\Chrome\User Data\Default\.
  • Open the file "Preferences" in a text editor like Notepad.
  • First, resave the file to something like "Preference - Old" without any extension (i.e. no .txt). This will serve as a backup, should something go wrong.
  • Look for a section called "browser." Inside that section, you should find a subsection called window_placement. Under window_placement you will see things like "bottom", "left", "right", etc. with numbers after them.

You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.

How to calculate time elapsed in bash script?

With GNU units:

$ units
2411 units, 71 prefixes, 33 nonlinear units
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: s
    * 134
    / 0.0074626866
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: min
    * 2.2333333
    / 0.44776119

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

Is the order of elements in a JSON list preserved?

Yes, the order of elements in JSON arrays is preserved. From RFC 7159 -The JavaScript Object Notation (JSON) Data Interchange Format (emphasis mine):

An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.

An array is an ordered sequence of zero or more values.

The terms "object" and "array" come from the conventions of JavaScript.

Some implementations do also preserve the order of JSON objects as well, but this is not guaranteed.

How to get file creation & modification date/times in Python?

os.stat https://docs.python.org/2/library/stat.html#module-stat

edit: In newer code you should probably use os.path.getmtime() (thanks Christian Oudard)
but note that it returns a floating point value of time_t with fraction seconds (if your OS supports it)

How to give the background-image path in CSS?

The solution (http://expressjs.com/en/starter/static-files.html).

once done this the image folder no longer shalt put it. only be

background-image: url ( "/ image.png");

carpera that the image is already in the static files

GET parameters in the URL with CodeIgniter

Now it works ok from CodeIgniter 2.1.0

    //By default CodeIgniter enables access to the $_GET array.  If for some
    //reason you would like to disable it, set 'allow_get_array' to FALSE.

$config['allow_get_array']      = TRUE; 

What is the difference between Python and IPython?

Compared to Python, IPython (created by Fernando Perez in 2001) can do every thing what python can do. Ipython provides even extra features like tab-completion, testing, debugging, system calls and many other features. You can think IPython as a powerful interface to the Python language.

You can install Ipython using pip - pip install ipython

You can run Ipython by typing ipython in your terminal window.

Twitter Bootstrap scrollable table rows and fixed header

Interesting question, I tried doing this by just doing a fixed position row, but this way seems to be a much better one. Source at bottom.

css

thead { display:block; background: green; margin:0px; cell-spacing:0px; left:0px; }
tbody { display:block; overflow:auto; height:100px; }
th { height:50px; width:80px; }
td { height:50px; width:80px; background:blue; margin:0px; cell-spacing:0px;}

html

<table>
    <thead>
        <tr><th>hey</th><th>ho</th></tr>
    </thead>
    <tbody>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
        <tr><td>test</td><td>test</td></tr>
</tbody>

http://www.imaputz.com/cssStuff/bigFourVersion.html

What is default color for text in textview?

Actually the color TextView is:

android:textColor="@android:color/tab_indicator_text"

or

#808080

Styling the arrow on bootstrap tooltips

For styling each directional arrows(left, right,top and bottom), we have to select each arrow using CSS attribute selector and then style them individually.

Trick: Top arrow must have border color only on top side and transparent on other 3 sides. Other directional arrows also need to be styled this way.

click here for Working Jsfiddle Link

Here is the simple CSS,

.tooltip-inner { background-color:#8447cf;}

[data-placement="top"] + .tooltip > .tooltip-arrow { border-top-color: #8447cf;}

[data-placement="right"] + .tooltip > .tooltip-arrow { border-right-color: #8447cf;}

[data-placement="bottom"] + .tooltip > .tooltip-arrow {border-bottom-color: #8447cf;}

[data-placement="left"] + .tooltip > .tooltip-arrow {border-left-color: #8447cf; }

Shrink to fit content in flexbox, or flex-basis: content workaround?

I want columns One and Two to shrink/grow to fit rather than being fixed.

Have you tried: flex-basis: auto

or this:

flex: 1 1 auto, which is short for:

  • flex-grow: 1 (grow proportionally)
  • flex-shrink: 1 (shrink proportionally)
  • flex-basis: auto (initial size based on content size)

or this:

main > section:first-child {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:nth-child(2) {
    flex: 1 1 auto;
    overflow-y: auto;
}

main > section:last-child {
    flex: 20 1 auto;
    display: flex;
    flex-direction: column;  
}

revised demo

Related:

How to add an object to an array

  • JavaScript is case-sensitive. Calling new array() and new object() will throw a ReferenceError since they don't exist.
  • It's better to avoid new Array() due to its error-prone behavior.
    Instead, assign the new array with = [val1, val2, val_n]. For objects, use = {}.
  • There are many ways when it comes to extending an array (as shown in John's answer) but the safest way would be just to use concat instead of push. concat returns a new array, leaving the original array untouched. push mutates the calling array which should be avoided, especially if the array is globally defined.
  • It's also a good practice to freeze the object as well as the new array in order to avoid unintended mutations. A frozen object is neither mutable nor extensible (shallowly).

Applying those points and to answer your two questions, you could define a function like this:

function appendObjTo(thatArray, newObj) {
  const frozenObj = Object.freeze(newObj);
  return Object.freeze(thatArray.concat(frozenObj));
}

Usage:

// Given
const myArray = ["A", "B"];
// "save it to a variable"
const newArray = appendObjTo(myArray, {hello: "world!"});
// returns: ["A", "B", {hello: "world!"}]. myArray did not change.

Reset push notification settings for app

I agree with micmdk.. I had a development environment setup with Push Notifications and needed a way to reset my phone to look like an initial install… and only these precise steps worked for me… requires TWO reboots of Device:

From APPLE TECH DOC:

Resetting the Push Notifications Permissions Alert on iOS The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.

If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by following these steps:

  1. Delete your app from the device.

  2. Turn the device off completely and turn it back on.

  3. Go to Settings > General > Date & Time and set the date ahead a day or more.

  4. Turn the device off completely again and turn it back on.

How do I change the formatting of numbers on an axis with ggplot?

Another option is to format your axis tick labels with commas is by using the package scales, and add

 scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = comma)

to your ggplot statement.

If you don't want to load the package, use:

scale_y_continuous(name="Fluorescent intensity/arbitrary units", labels = scales::comma)

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

how to make jni.h be found?

Above answers give you a hardcoded path solution. This is bad on so many levels (java version change, OS change, etc).

Cleaner solution is to add:

JAVA_HOME = $(shell dirname $$(readlink -f $$(which java))|sed 's^jre/bin^^')

near the top of your makefile, then add:

-I$(JAVA_HOME)/include

To your include flags.

I am posting this because I ran into the same problem and spent too much time googling for wrong answers (I am building an app on multiple platforms so the build environment needs to be transportable).

Select random lines from a file

# Function to sample N lines randomly from a file
# Parameter $1: Name of the original file
# Parameter $2: N lines to be sampled 
rand_line_sampler() {
    N_t=$(awk '{print $1}' $1 | wc -l) # Number of total lines

    N_t_m_d=$(( $N_t - $2 - 1 )) # Number oftotal lines minus desired number of lines

    N_d_m_1=$(( $2 - 1)) # Number of desired lines minus 1

    # vector to have the 0 (fail) with size of N_t_m_d 
    echo '0' > vector_0.temp
    for i in $(seq 1 1 $N_t_m_d); do
            echo "0" >> vector_0.temp
    done

    # vector to have the 1 (success) with size of desired number of lines
    echo '1' > vector_1.temp
    for i in $(seq 1 1 $N_d_m_1); do
            echo "1" >> vector_1.temp
    done

    cat vector_1.temp vector_0.temp | shuf > rand_vector.temp

    paste -d" " rand_vector.temp $1 |
    awk '$1 != 0 {$1=""; print}' |
    sed 's/^ *//' > sampled_file.txt # file with the sampled lines

    rm vector_0.temp vector_1.temp rand_vector.temp
}

rand_line_sampler "parameter_1" "parameter_2"

How to add a .dll reference to a project in Visual Studio

For Visual Studio 2019 you may not find Project -> Add Reference option. Use Project -> Add Project Reference. Then in dialog window navigate to Browse tab and use Browse to find and attach your dll.

Deserialize a JSON array in C#

[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

and Remove a "{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

DeserializeObject..,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

Write lines of text to a file in R

Short ways to write lines of text to a file in R could be realised with cat or writeLines as already shown in many answers. Some of the shortest possibilities might be:

cat("Hello\nWorld", file="output.txt")
writeLines("Hello\nWorld", "output.txt")

In case you don't like the "\n" you could also use the following style:

cat("Hello
World", file="output.txt")

writeLines("Hello
World", "output.txt")

While writeLines adds a newline at the end of the file what is not the case for cat. This behaviour could be adjusted by:

writeLines("Hello\nWorld", "output.txt", sep="") #No newline at end of file
cat("Hello\nWorld\n", file="output.txt") #Newline at end of file
cat("Hello\nWorld", file="output.txt", sep="\n") #Newline at end of file

But main difference is that cat uses R objects and writeLines a character vector as argument. So writing out e.g. the numbers 1:10 needs to be casted for writeLines while it can be used as it is in cat:

cat(1:10)
writeLines(as.character(1:10))

and cat can take many objects but writeLines only one vector:

cat("Hello", "World", sep="\n")
writeLines(c("Hello", "World"))

Why do we need the "finally" clause in Python?

finally is for defining "clean up actions". The finally clause is executed in any event before leaving the try statement, whether an exception (even if you do not handle it) has occurred or not.

I second @Byers's example.

Javascript call() & apply() vs bind()?

Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

I do this a lot:

function MyObject(element) {
    this.elm = element;

    element.addEventListener('click', this.onClick.bind(this), false);
};

MyObject.prototype.onClick = function(e) {
     var t=this;  //do something with [t]...
    //without bind the context of this function wouldn't be a MyObject
    //instance as you would normally expect.
};

I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.

A simple, naive implementation of bind would be like:

Function.prototype.bind = function(ctx) {
    var fn = this;
    return function() {
        fn.apply(ctx, arguments);
    };
};

There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

Hope this helps.

'printf' vs. 'cout' in C++

And I quote:

In high level terms, the main differences are type safety (cstdio doesn't have it), performance (most iostreams implementations are slower than the cstdio ones) and extensibility (iostreams allows custom output targets and seamless output of user defined types).

Simple DatePicker-like Calendar

I'm particularly fond of this date picker built for Mootools: http://electricprism.com/aeron/calendar/

It's lovely right out of the box.

Initialize a byte array to a certain value, other than the default null?

Just to expand on my answer a neater way of doing this multiple times would probably be:

PopulateByteArray(UserCode, 0x20);

which calls:

public static void PopulateByteArray(byte[] byteArray, byte value)
{
    for (int i = 0; i < byteArray.Length; i++)
    {
        byteArray[i] = value;
    }
}

This has the advantage of a nice efficient for loop (mention to gwiazdorrr's answer) as well as a nice neat looking call if it is being used a lot. And a lot mroe at a glance readable than the enumeration one I personally think. :)

Finding duplicate values in MySQL

SELECT ColumnA, COUNT( * )
FROM Table
GROUP BY ColumnA
HAVING COUNT( * ) > 1

How to really read text file from classpath in Java

To read the contents of a file into a String from the classpath, you can use this:

private String resourceToString(String filePath) throws IOException, URISyntaxException
{
    try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(filePath))
    {
        return IOUtils.toString(inputStream);
    }
}

Note:
IOUtils is part of Commons IO.

Call it like this:

String fileContents = resourceToString("ImOnTheClasspath.txt");

How to scroll to the bottom of a UITableView on the iPhone before the view appears

Details

  • Xcode 8.3.2, swift 3.1
  • Xcode 10.2 (10E125), Swift 5

Code

import UIKit

extension UITableView {
    func scrollToBottom(animated: Bool) {
        let y = contentSize.height - frame.size.height
        if y < 0 { return }
        setContentOffset(CGPoint(x: 0, y: y), animated: animated)
    }
}

Usage

tableView.scrollToBottom(animated: true)

Full sample

Do not forget to paste solution code!

import UIKit

class ViewController: UIViewController {

    private weak var tableView: UITableView?
    private lazy var cellReuseIdentifier = "CellReuseIdentifier"

    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: view.frame)
        view.addSubview(tableView)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        self.tableView = tableView
        tableView.dataSource = self
        tableView.performBatchUpdates(nil) { [weak self] result in
            if result { self?.tableView?.scrollToBottom(animated: true) }
        }
    }
}

extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath )
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

Get value of Span Text

You need to change your code as below:

<html>
<body>

<span id="span_Id">Click the button to display the content.</span>

<button onclick="displayDate()">Click Me</button>

<script>
function displayDate() {
   var span_Text = document.getElementById("span_Id").innerText;
   alert (span_Text);
}
</script>
</body>
</html>

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Show current assembly instruction in GDB

From within gdb press Ctrl x 2 and the screen will split into 3 parts.

First part will show you the normal code in high level language.

Second will show you the assembly equivalent and corresponding instruction Pointer.

Third will present you the normal gdb prompt to enter commands.

See the screen shot

How do I get an empty array of any size in python?

Just declare the list and append each element. For ex:

a = []
a.append('first item')
a.append('second item')

JavaScript Loading Screen while page loads

This method uses the WindowOrWorkerGlobalScope.setInterval(https://developer.mozilla.org/en-US/doc) method to track the ready states of the document & see if the <body> element exists.

// Function > Loader Screen Script
(function LoaderScreenScript(window = window, document = window.document, undefined = window.undefined || void 0) {
    // Initialization > (Processing Time, Condition, Timeout, Loader (...))
    let processingTime = 0,
        condition = function() {
            // Return
            return document.body
        },
        timeout = function() {
            // Return
            return (processingTime * 1e3) / 2
        },
        loaderScreenFontSize = typeof window.loaderScreenFontSize != 'undefined' ? window.loaderScreenFontSize : 14,
        loaderScreenMargin = typeof window.loaderScreenMargin != 'undefined' ? window.loaderScreenMargin : 10,
        loaderScreenMessage = typeof window.loaderScreenMessage != 'undefined' ? window.loaderScreenMessage : 'Loading, please wait&hellip;',
        loaderScreenOpacity = typeof window.loaderScreenOpacity != 'undefined' ? window.loaderScreenOpacity : .75,
        loaderScreenTransition = typeof window.loaderScreenTransition != 'undefined' ? window.loaderScreenTransition : .675,
        loaderScreenWidth = typeof window.loaderScreenWidth != 'undefined' ? window.loaderScreenWidth : 7.5;

    // Function > Update
    function update() {
        // Set Timeout
        setTimeout(function() {
            // Initialization > (Data, Metadata)
            var data = document.createElement('loader-screen-element'),
                metadata = setInterval(function() {
                    /* Logic
                            [if:else if:else statement]
                    */
                    if (document.readyState == 'complete') {
                        // Alpha
                        alpha();

                        // Test
                        test()
                    }
                });

            // Insertion
            document.body.appendChild(data);

            // Style > <body> > Overflow
            document.body.style = ('overflow: hidden !important; pointer-events: none !important; user-drag: none !important; user-select: none !important;' + (document.body.getAttribute('style') || ' ')).trim();

            // Modification > Data
                // Inner HTML
                data.innerHTML =
                    '<style media=all type=text/css>' +
                        'body::selection {' +
                            'background-color: transparent !important;' +
                            'text-shadow: none !important' +
                        '} ' +
                        '@keyframes rotate {' +
                            '0% { transform: rotate(0) }' +
                            'to { transform: rotate(360deg) }' +
                        '}' +
                    '</style>' +
                    "<div style='animation: rotate 1s ease-in-out 0s infinite backwards; border: " + loaderScreenWidth + "px solid rgba(0, 0, 0, " + loaderScreenOpacity + "); border-top-color: rgba(0, 51, 255, " + loaderScreenOpacity + "); border-radius: 50%; height: 75px; margin: 0 auto; margin-bottom: " + loaderScreenMargin + "px; width: 75px'> </div>" +
                    "<small style='color: rgba(127, 127, 127, .675); font-family: \"Open Sans\", \"Calibri Light\", Calibri, sans-serif; font-size: " + loaderScreenFontSize + "px !important; margin: 0 auto; margin-top: " + loaderScreenMargin + "px; text-align: center'> " + loaderScreenMessage + " </small>";

                // Style
                data.style = 'align-items: center; background-color: rgba(255, 255, 255, .98); display: flex; flex-direction: column; height: ' + innerHeight + 'px; justify-content: center; left: 0; margin: auto; max-height: 100% !important; max-width: 100% !important; min-height: 100vh; min-width: 100vh; position: fixed; top: 0; transition: ' + loaderScreenTransition + 's ease-in-out; width: ' + innerWidth + 'px; z-index: 2147483647';

            // Function
                // Alpha
                function alpha() {
                    // Clear Interval
                    clearInterval(metadata)
                };

                // Test
                function test() {
                    // Style > Data
                        // Background Color
                        data.style.backgroundColor = 'transparent';

                        // Opacity
                        data.style.opacity = 0;

                    // Set Timeout
                    setTimeout(function() {
                        // Deletion
                        data.remove();

                        // Modification > <body> > Style
                        document.body.style = document.body.getAttribute('style').replace('overflow: hidden !important;', '').replace('pointer-events: none !important;', '').replace('user-drag: none !important;', '').replace('user-select: none !important;', '');
                        (document.body.getAttribute('style') || '').trim() || document.body.removeAttribute('style')
                    }, ((+getComputedStyle(data).getPropertyValue('animation-delay').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('animation-duration').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('transition-delay').replace(/[a-zA-Z]/g, '').trim() + +getComputedStyle(data).getPropertyValue('transition-duration').replace(/[a-zA-Z]/g, '').trim()) * 1e3) + 100);
                }
        }, timeout())
    };

    /* Logic
            [if:else if:else statement]
    */
    if (condition())
        // Update
        update();

    else {
        // Initialization > Data
        var data = setInterval(function() {
            /* Logic
                    [if:else if:else statement]
            */
            if (condition()) {
                // Update > Processing Time
                processingTime += 1;

                // Update
                update();

                // Metadata
                metadata()
            }
        });

        // Function > Metadata
        function metadata() {
            // Clear Interval
            clearInterval(data);

            /* Logic
                    [if:else if:else statement]

                > Deletion
            */
            if ('data' in window && typeof data == 'undefined')
                delete window.data
        }
    }
})(window, window.document, window.undefined || void 0)

This pre-loading screen was made by Lapys @ https://github.com/LapysDev

How do pointer-to-pointer's work in C? (and when might you use them?)

There so many of the useful explanations, but I didnt found just a short description, so..

Basically pointer is address of the variable. Short summary code:

     int a, *p_a;//declaration of normal variable and int pointer variable
     a = 56;     //simply assign value
     p_a = &a;   //save address of "a" to pointer variable
     *p_a = 15;  //override the value of the variable

//print 0xfoo and 15 
//- first is address, 2nd is value stored at this address (that is called dereference)
     printf("pointer p_a is having value %d and targeting at variable value %d", p_a, *p_a); 

Also useful info can be found in topic What means reference and dereference

And I am not so sure, when can be pointers useful, but in common it is necessary to use them when you are doing some manual/dynamic memory allocation- malloc, calloc, etc.

So I hope it will also helps for clarify the problematic :)

Selenium WebDriver.get(url) does not open the URL

I got the same error when issuing a URL without the protocol (like localhost:4200) instead of a correct one also specifying the protocol (e.g. http://localhost:4200).

Google Chrome works fine without the protocol (it takes http as the default), but Firefox crashes with this error.

Get div's offsetTop positions in React

You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

Check the John Resig's post describing how helpful this method is.

Decimal or numeric values in regular expression validation

A simple regex to match a numeric input and optional 2 digits decimal.

/^\d*(\.)?(\d{0,2})?$/

You can modify the {0,2} to match your decimal preference {min, max}


Snippet for validation:

_x000D_
_x000D_
const source = document.getElementById('source');
source.addEventListener('input', allowOnlyNumberAndDecimals);

function allowOnlyNumberAndDecimals(e) {
  let str = e.target.value
  const regExp = /^\d*(\.)?(\d{0,2})?$/

  status = regExp.test(str) ? 'valid' : 'invalid'

  console.log(status + ' : ' + source.value)
}
_x000D_
<input type="text" id="source" />
_x000D_
_x000D_
_x000D_

Using Mysql in the command line in osx - command not found?

That means /usr/local/mysql/bin/mysql is not in the PATH variable..

Either execute /usr/local/mysql/bin/mysql to get your mysql shell,

or type this in your terminal:

PATH=$PATH:/usr/local/mysql/bin

to add that to your PATH variable so you can just run mysql without specifying the path

Visual Studio window which shows list of methods

Shortcut to Navigation Bar is Ctrl+F2. Takes you to the types dropdown first. Press tab to go to method dropdown, and then enter on a method to go to that one.

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

ArrayList vs List<> in C#

Performance has already been mentioned in several answers as a differentiating factor, but to address the “How much slower is the ArrayList ?” and “Why is it slower overall ?”, have a look below.

Whenever value types are used as elements, performance drops dramatically with ArrayList. Consider the case of simply adding elements. Due to the boxing going on - as ArrayList’s Add only takes object parameters - the Garbage Collector gets triggered into performing a lot more work than with List<T>.

How much is the time difference ? At least several times slower than with List<T>. Just take a look at what happens with code adding 10 mil int values to an ArrayList vs List<T>: enter image description here

That’s a run time difference of 5x in the ‘Mean’ column, highlighted in yellow. Note also the difference in the number of garbage collections done for each, highlighted in red (no of GCs / 1000 runs).

Using a profiler to see what’s going on quickly shows that most of the time is spent doing GCs, as opposed to actually adding elements. The brown bars below represent blocking Garbage Collector activity: enter image description here

I’ve written a detailed analysis of what goes on with the above ArrayList scenario here https://mihai-albert.com/2019/12/15/boxing-performance-in-c-analysis-and-benchmark/.

Similar findings are in “CLR via C#” by Jeffrey Richter. From chapter 12 (Generics):

[…] When I compile and run a release build (with optimizations turned on) of this program on my computer, I get the following output.

00:00:01.6246959 (GCs= 6) List<Int32>
00:00:10.8555008 (GCs=390) ArrayList of Int32
00:00:02.5427847 (GCs= 4) List<String>
00:00:02.7944831 (GCs= 7) ArrayList of String

The output here shows that using the generic List algorithm with the Int32 type is much faster than using the non-generic ArrayList algorithm with Int32. In fact, the difference is phenomenal: 1.6 seconds versus almost 11 seconds. That’s ~7 times faster! In addition, using a value type (Int32) with ArrayList causes a lot of boxing operations to occur, which results in 390 garbage collections. Meanwhile, the List algorithm required 6 garbage collections.

List of strings to one string

If you use .net 4.0 you can use a sorter way:

String.Join<string>(String.Empty, los);

Can a div have multiple classes (Twitter Bootstrap)

You can have multiple css class selectors:

For e.g.:

<div class="col-md-4 a-class-name">
</div>

but only a single id:

<div id = "btn1 btn">  <!-- this is wrong -->
</div>

Get current folder path

This block of code makes a path of your app directory in string type

string path="";
path=System.AppContext.BaseDirectory;

good luck

Changing git commit message after push (given that no one pulled from remote)

git commit --amend

then edit and change the message in the current window. After that do

git push --force-with-lease

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

CSS Circular Cropping of Rectangle Image

Try this:

img {
    height: auto;
    width: 100%;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
}

DEMO here.

OR:

.rounded {
    height: 100px;
    width: 100px;
    -webkit-border-radius: 50%;
    -moz-border-radius: 50%;
    -ms-border-radius: 50%;
    -o-border-radius: 50%;
    border-radius: 50%;
    background:url("http://www.electricvelocity.com.au/Upload/Blogs/smart-e-bike-side_2.jpg") center no-repeat;
    background-size:cover;
}

DEMO here.

How to make a owl carousel with arrows instead of next previous

If you're using Owl Carousel 2, then you should use the following:

$(".category-wrapper").owlCarousel({
     items : 4,
     loop  : true,
     margin : 30,
     nav    : true,
     smartSpeed :900,
     navText : ["<i class='fa fa-chevron-left'></i>","<i class='fa fa-chevron-right'></i>"]
   });

AND/OR in Python?

Try this solution:

for m in ["a", "á", "à", "ã", "â"]:
    try:
        somelist.remove(m)
    except:
        pass

Just for your information. and and or operators are also using to return values. It is useful when you need to assign value to variable but you have some pre-requirements

operator or returns first not null value

#init values
a,b,c,d = (1,2,3,None)

print(d or a or b or c)
#output value of a - 1

print(b or a or c or d)
#output value of b - 2

Operator and returns last value in the sequence if any of the members don't have None value or if they have at least one None value we get None

print(a and d and b and c)
#output: None

print(a or b or c)
#output value of c - 3

CSS: Background image and padding

Use background-position: calc(100% - 20px) center, For pixel perfection calc() is the best solution.

_x000D_
_x000D_
ul {_x000D_
  width: 100px;_x000D_
}_x000D_
ul li {_x000D_
  border: 1px solid orange;_x000D_
  background: url("http://placehold.it/30x15") no-repeat calc(100% - 10px) center;_x000D_
}_x000D_
ul li:hover {_x000D_
  background-position: calc(100% - 20px) center;_x000D_
}
_x000D_
<ul>_x000D_
  <li>Hello</li>_x000D_
  <li>Hello world</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Im new to java hibernate but i could solve this problem, this is how i did it : I was working with hibernate and maven project. First you have to put persistence.xml under project directory, then add jdbc manually. Maven couldn't download my dependency so i added it manually. In the persistence.xml in design jdbc connection add it manually ps: i work with netbeans good luck

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

WARNING: This deletes all commits on the email branch. It's like deleting the email branch and creating it anew at the head of the staging branch.

The easiest way to do it:

//the branch you want to overwrite
git checkout email 

//reset to the new branch
git reset --hard origin/staging

// push to remote
git push -f

Now the email branch and the staging are the same.

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Handling file renames in git

You have to add the two modified files to the index before git will recognize it as a move.

The only difference between mv old new and git mv old new is that the git mv also adds the files to the index.

mv old new then git add -A would have worked, too.

Note that you can't just use git add . because that doesn't add removals to the index.

See Difference between "git add -A" and "git add ."

Understanding timedelta

Because timedelta is defined like:

class datetime.timedelta([days,] [seconds,] [microseconds,] [milliseconds,] [minutes,] [hours,] [weeks])

All arguments are optional and default to 0.

You can easily say "Three days and four milliseconds" with optional arguments that way.

>>> datetime.timedelta(days=3, milliseconds=4)
datetime.timedelta(3, 0, 4000)
>>> datetime.timedelta(3, 0, 0, 4) #no need for that.
datetime.timedelta(3, 0, 4000)

And for str casting, it returns a nice formatted value instead of __repr__ to improve readability. From docs:

str(t) Returns a string in the form [D day[s], ][H]H:MM:SS[.UUUUUU], where D is negative for negative t. (5)

>>> datetime.timedelta(seconds = 42).__repr__()
'datetime.timedelta(0, 42)'
>>> datetime.timedelta(seconds = 42).__str__()
'0:00:42'

Checkout documentation:

http://docs.python.org/library/datetime.html#timedelta-objects

Change Orientation of Bluestack : portrait/landscape mode

Try This...

Go to your notification area in the taskbar.

Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.

There are several options available..

a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.

b. Disabled - It will force the portrait apps to work in landscape mode.

c. Enabled - It will force the portrait apps to work in portrait mode only.

This May help you..

Django error - matching query does not exist

your line raising the error is here:

comment = Comment.objects.get(pk=comment_id)

you try to access a non-existing comment.

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.

Ok up to here I suppose you are aware of this.

Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.

Other users go to addresses from their history, (same if data have been deleted since it may happens).

Efficient SQL test query or validation query that will work across all (or most) databases

If your driver is JDBC 4 compliant, there is no need for a dedicated query to test connections. Instead, there is Connection.isValid to test the connection.

JDBC 4 is part of Java 6 from 2006 and you driver should support this by now!

Famous connection pools, like HikariCP, still have a config parameter for specifying a test query but strongly discourage to use it:

connectionTestQuery

If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" databases that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none

PHP max_input_vars

Have just attempted this fix with 5.3.3 and there's no change. Googling around I found this web page http://anothersysadmin.wordpress.com/2012/02/16/php-5-3-max_input_vars-and-big-forms/ detailing other settings which need changing if your server uses the Suhosin patch which Apache under Debian does.

The site explains:

So, if you want to increase this number to, say, 3000 from the default number which is 1000, you have to put in your php.ini these lines:

max_input_vars = 3000 suhosin.post.max_vars = 3000 suhosin.request.max_vars = 3000

I tested it (added settings to php.ini both in /etc/php5/apache2 and /etc/php5/cli, and restarted Apache successfully) but still no max_input_vars variable in phpinfo.

A few sites point to PHP 5.3.9 as the first PHP version in which this change will take, so my fault for not RTM properly in the first place, although I'm interested to see people reporting it working in version above 5.3.3 but below 5.3.9.

Remove accents/diacritics in a string in JavaScript

Pass a user defined function to the Array.sort() method, and in this user defined function use String.localeCompare()

function myCompareFunction(a, b) {
  return a.localeCompare(b);
}

var values = ["pêches", "épinards", "tomates", "fraises"];

// WRONG: ["fraises", "pêches", "tomates", "épinards"]
values.sort();

 // **GOOD**: ["épinards", "fraises", "pêches", "tomates"]
values.sort(myCompareFunction);

Regular expression for exact match of a string

In malfaux's answer '^' and '$' has been used to detect the beginning and the end of the text.
These are usually used to detect the beginning and the end of a line.
However this may be the correct way in this case.
But if you wish to match an exact word the more elegant way is to use '\b'. In this case following pattern will match the exact phrase'123456'.

/\b123456\b/

How to remove padding around buttons in Android?

It's not a padding but or the shadow of the background drawable or a problem with the minHeight and minWidth.

If you still want the nice ripple affect, you can make your own button style using the ?attr/selectableItemBackground:

<style name="Widget.AppTheme.MyCustomButton" parent="Widget.AppCompat.Button.Borderless">
    <item name="android:minHeight">0dp</item>
    <item name="android:minWidth">0dp</item>
    <item name="android:layout_height">48dp</item>
    <item name="android:background">?attr/selectableItemBackground</item>
</style>

And apply it to the button:

<Button 
    style="@style/Widget.AppTheme.MyCustomButton"
    ... />

How do I get the currently-logged username from a Windows service in .NET?

This is a WMI query to get the user name:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

You will need to add System.Management under References manually.

A non-blocking read on a subprocess.PIPE in Python

Here is a simple solution based on threads which:

  • works on both Linux and Windows (not relying on select).
  • reads both stdout and stderr asynchronouly.
  • doesn't rely on active polling with arbitrary waiting time (CPU friendly).
  • doesn't use asyncio (which may conflict with other libraries).
  • runs until the child process terminates.

printer.py

import time
import sys

sys.stdout.write("Hello\n")
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("World!\n")
sys.stdout.flush()
time.sleep(1)
sys.stderr.write("That's an error\n")
sys.stderr.flush()
time.sleep(2)
sys.stdout.write("Actually, I'm fine\n")
sys.stdout.flush()
time.sleep(1)

reader.py

import queue
import subprocess
import sys
import threading


def enqueue_stream(stream, queue, type):
    for line in iter(stream.readline, b''):
        queue.put(str(type) + line.decode('utf-8'))
    stream.close()


def enqueue_process(process, queue):
    process.wait()
    queue.put('x')


p = subprocess.Popen('python printer.py', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
q = queue.Queue()
to = threading.Thread(target=enqueue_stream, args=(p.stdout, q, 1))
te = threading.Thread(target=enqueue_stream, args=(p.stderr, q, 2))
tp = threading.Thread(target=enqueue_process, args=(p, q))
te.start()
to.start()
tp.start()

while True:
    line = q.get()
    if line[0] == 'x':
        break
    if line[0] == '2':  # stderr
        sys.stdout.write("\033[0;31m")  # ANSI red color
    sys.stdout.write(line[1:])
    if line[0] == '2':
        sys.stdout.write("\033[0m")  # reset ANSI code
    sys.stdout.flush()

tp.join()
to.join()
te.join()

List all indexes on ElasticSearch server?

For a concise list of all indices in your cluster, call

curl http://localhost:9200/_aliases

this will give you a list of indices and their aliases.

If you want it pretty-printed, add pretty=true:

curl http://localhost:9200/_aliases?pretty=true

The result will look something like this, if your indices are called old_deuteronomy and mungojerrie:

{
  "old_deuteronomy" : {
    "aliases" : { }
  },
  "mungojerrie" : {
    "aliases" : {
      "rumpleteazer" : { },
      "that_horrible_cat" : { }
    }
  }
}

Insert a line break in mailto body

As per RFC2368 which defines mailto:, further reinforced by an example in RFC1738, it is explicitly stated that the only valid way to generate a line break is with %0D%0A.

This also applies to all url schemes such as gopher, smtp, sdp, imap, ldap, etc..

How to print the current Stack Trace in .NET without any exception?

There are two ways to do this. The System.Diagnostics.StackTrace() will give you a stack trace for the current thread. If you have a reference to a Thread instance, you can get the stack trace for that via the overloaded version of StackTrace().

You may also want to check out Stack Overflow question How to get non-current thread's stacktrace?.

Stop executing further code in Java

return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop

Concatenate text files with Windows command line, dropping leading lines

In powershell:

Get-Content file1.txt | Out-File out.txt
Get-Content file2.txt | Select-Object -Skip 1 | Out-File -Append out.txt

How to copy a selection to the OS X clipboard

If the clipboard is enabled, you can copy a selected region to the clipboard by hitting "*y

To see if it is enabled, run vim --version and look for +clipboard or -clipboard. For example, it's not enabled by default on my 10.5.6 box:

% which vim
/usr/bin/vim
% vim --version
VIM - Vi IMproved 7.2 (2008 Aug 9, compiled Nov 11 2008 17:20:43)
Included patches: 1-22
Compiled by [email protected]
Normal version without GUI.  Features included (+) or not (-):
...
-clientserver -clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
...

If it had been compiled with +clipboard, I'd be able to use the "* register to access the system clipboard.

I downloaded the 7.2 source and compiled it (easy as tar xjf vim-7.2.tar.bz && cd vim72 && ./configure && make && sudo make install), and the clipboard was enabled:

% which vim
/usr/local/bin/vim
% vim --version
VIM - Vi IMproved 7.2 (2008 Aug 9, compiled Mar 24 2009 17:31:52)
Compiled by [email protected]
Normal version with GTK2 GUI.  Features included (+) or not (-):
...
+clientserver +clipboard +cmdline_compl +cmdline_hist +cmdline_info +comments
...

However, even after compiling, I couldn't copy to the clipboard when running vim in Terminal.app, only in X11.app.

Array of Matrices in MATLAB

myArrayOfMatrices = zeros(unknown,500,800);

If you're running out of memory throw more RAM in your system, and make sure you're running a 64 bit OS. Also try reducing your precision (do you really need doubles or can you get by with singles?):

myArrayOfMatrices = zeros(unknown,500,800,'single');

To append to that array try:

myArrayOfMatrices(unknown+1,:,:) = zeros(500,800);

How to import a CSS file in a React Component

You can also use the required module.

require('./componentName.css');
const React = require('react');

Is it possible to wait until all javascript files are loaded before executing javascript code?

Thats work for me:

var jsScripts = [];

jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );

$(jsScripts).each(function( index, value ) {
    $.holdReady( true );
    $.getScript( value ).done(function(script, status) {
        console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');                
        $.holdReady( false );
    });
});

Operand type clash: uniqueidentifier is incompatible with int

If you're accessing this via a View then try sp_recompile or refreshing views.

sp_recompile:

Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.

Arguments

[ @objname= ] 'object'

The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.

Return Code Values

0 (success) or a nonzero number (failure)

Remarks

sp_recompile looks for an object in the current database only.

The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.

Overwriting my local branch with remote branch

git reset --hard

This is to revert all your local changes to the origin head

Adding to the classpath on OSX

In OSX, you can set the classpath from scratch like this:

export CLASSPATH=/path/to/some.jar:/path/to/some/other.jar

Or you can add to the existing classpath like this:

export CLASSPATH=$CLASSPATH:/path/to/some.jar:/path/to/some/other.jar

This is answering your exact question, I'm not saying it's the right or wrong thing to do; I'll leave that for others to comment upon.

How to save as a new file and keep working on the original one in Vim?

Use the :w command with a filename:

:w other_filename

How can I detect the touch event of an UIImageView?

For those of you looking for a Swift 4 solution to this answer, you can use the following to detect a touch event on a UIImageView.

let gestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageViewTapped))
imageView.addGestureRecognizer(gestureRecognizer)
imageView.isUserInteractionEnabled = true

You will then need to define your selector as follows:

@objc func imageViewTapped() {
    // Image has been tapped
}

Seedable JavaScript random number generator

If you don't need the seeding capability just use Math.random() and build helper functions around it (eg. randRange(start, end)).

I'm not sure what RNG you're using, but it's best to know and document it so you're aware of its characteristics and limitations.

Like Starkii said, Mersenne Twister is a good PRNG, but it isn't easy to implement. If you want to do it yourself try implementing a LCG - it's very easy, has decent randomness qualities (not as good as Mersenne Twister), and you can use some of the popular constants.

EDIT: consider the great options at this answer for short seedable RNG implementations, including an LCG option.

_x000D_
_x000D_
function RNG(seed) {_x000D_
  // LCG using GCC's constants_x000D_
  this.m = 0x80000000; // 2**31;_x000D_
  this.a = 1103515245;_x000D_
  this.c = 12345;_x000D_
_x000D_
  this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1));_x000D_
}_x000D_
RNG.prototype.nextInt = function() {_x000D_
  this.state = (this.a * this.state + this.c) % this.m;_x000D_
  return this.state;_x000D_
}_x000D_
RNG.prototype.nextFloat = function() {_x000D_
  // returns in range [0,1]_x000D_
  return this.nextInt() / (this.m - 1);_x000D_
}_x000D_
RNG.prototype.nextRange = function(start, end) {_x000D_
  // returns in range [start, end): including start, excluding end_x000D_
  // can't modulu nextInt because of weak randomness in lower bits_x000D_
  var rangeSize = end - start;_x000D_
  var randomUnder1 = this.nextInt() / this.m;_x000D_
  return start + Math.floor(randomUnder1 * rangeSize);_x000D_
}_x000D_
RNG.prototype.choice = function(array) {_x000D_
  return array[this.nextRange(0, array.length)];_x000D_
}_x000D_
_x000D_
var rng = new RNG(20);_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.nextRange(10, 50));_x000D_
_x000D_
var digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];_x000D_
for (var i = 0; i < 10; i++)_x000D_
  console.log(rng.choice(digits));
_x000D_
_x000D_
_x000D_

How can I get input radio elements to horizontally align?

In your case, you just need to remove the line breaks (<br> tags) between the elements - input elements are inline-block by default (in Chrome at least). (updated example).

<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change

I'd suggest using <label> elements, though. In doing so, clicking on the label will check the element too. Either associate the <label>'s for attribute with the <input>'s id: (example)

<input type="radio" name="editList" id="always" value="always"/>
<label for="always">Always</label>

<input type="radio" name="editList" id="never" value="never"/>
<label for="never">Never</label>

<input type="radio" name="editList" id="change" value="costChange"/>
<label for="change">Cost Change</label>

..or wrap the <label> elements around the <input> elements directly: (example)

<label>
    <input type="radio" name="editList" value="always"/>Always
</label>
<label>
    <input type="radio" name="editList" value="never"/>Never
</label>
<label>
    <input type="radio" name="editList" value="costChange"/>Cost Change
</label>

You can also get fancy and use the :checked pseudo class.

Sorting hashmap based on keys

Use sorted TreeMap:

Map<String, Float> map = new TreeMap<>(yourMap);

It will automatically put entries sorted by keys. I think natural String ordering will be fine in your case.

Note that HashMap due to lookup optimizations does not preserve order.

How to iterate through an ArrayList of Objects of ArrayList of Objects?

We can do a nested loop to visit all the elements of elements in your list:

 for (Gun g: gunList) {
   System.out.print(g.toString() + "\n   "); 
   for(Bullet b : g.getBullet() {
      System.out.print(g);    
   }
   System.out.println(); 
 }

Eclipse - "Workspace in use or cannot be created, chose a different one."

for windows users: In case of you can't remove .lock file and it gives you the following:

enter image description here

And you know that eclipse is already closed, just open Task Manager then processes then end precess for all eclipse.exe occurrences in the processes list.

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

How to include header files in GCC search path?

Using environment variable is sometimes more convenient when you do not control the build scripts / process.

For C includes use C_INCLUDE_PATH.

For C++ includes use CPLUS_INCLUDE_PATH.

See this link for other gcc environment variables.

Example usage in MacOS / Linux

# `pip install` will automatically run `gcc` using parameters
# specified in the `asyncpg` package (that I do not control)

C_INCLUDE_PATH=/home/scott/.pyenv/versions/3.7.9/include/python3.7m pip install asyncpg

Example usage in Windows

set C_INCLUDE_PATH="C:\Users\Scott\.pyenv\versions\3.7.9\include\python3.7m"

pip install asyncpg

# clear the environment variable so it doesn't affect other builds
set C_INCLUDE_PATH=

Is it possible to auto-format your code in Dreamweaver?

Auto formatting can be done by

  • Select View > Code View Options
  • Click the View Options button enter image description here in the toolbar at the top of Code view or the Code inspector.

Auto Indent Makes your code indent automatically when you press Enter while writing code.

source

Why does the JFrame setSize() method not set the size correctly?

I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.

Using this

setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));

But this always work in any size:

setSize(width + 14, height + 7);

If you don't want the border to border, and only want the white area, here:

setSize(width + 16, height + 39);

Also this only works on Windows 10, for MacOS users, use @ben's answer.

Timer function to provide time in nano seconds using C++

For C++11, here is a simple wrapper:

#include <iostream>
#include <chrono>

class Timer
{
public:
    Timer() : beg_(clock_::now()) {}
    void reset() { beg_ = clock_::now(); }
    double elapsed() const {
        return std::chrono::duration_cast<second_>
            (clock_::now() - beg_).count(); }

private:
    typedef std::chrono::high_resolution_clock clock_;
    typedef std::chrono::duration<double, std::ratio<1> > second_;
    std::chrono::time_point<clock_> beg_;
};

Or for C++03 on *nix,

class Timer
{
public:
    Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }

    double elapsed() {
        clock_gettime(CLOCK_REALTIME, &end_);
        return end_.tv_sec - beg_.tv_sec +
            (end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
    }

    void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }

private:
    timespec beg_, end_;
};

Example of usage:

int main()
{
    Timer tmr;
    double t = tmr.elapsed();
    std::cout << t << std::endl;

    tmr.reset();
    t = tmr.elapsed();
    std::cout << t << std::endl;
    return 0;
}

From https://gist.github.com/gongzhitaao/7062087

How to fetch data from local JSON file on react native?

maybe you could use AsyncStorage setItem and getItem...and store the data as string, then use the json parser for convert it again to json...

How can I do GUI programming in C?

C is more of a hardware programming language, there are easy GUI builders for C, GTK, Glade, etc. The problem is making a program in C that is the easy part, making a GUI that is a easy part, the hard part is to combine both, to interface between your program and the GUI is a headache, and different GUI use different ways, some threw global variables, some use slots. It would be nice to have a GUI builder that would bind easily your C program variables, and outputs. CLI programming is easy when you overcome memory allocation and pointers, GUI you can use a IDE that uses drag and drop. But all around I think it could be simpler.

IF statement: how to leave cell blank if condition is false ("" does not work)

The formula in C1

=IF(A1=1,B1,"")

is either giving an answer of "" (which isn't treated as blank) or the contents of B1.

If you want the formula in D1 to show TRUE if C1 is "" and FALSE if C1 has something else in then use the formula

=IF(C2="",TRUE,FALSE)

instead of ISBLANK

[Vue warn]: Cannot find element

I think the problem is your script is executed before the target dom element is loaded in the dom... one reason could be that you have placed your script in the head of the page or in a script tag that is placed before the div element #main. So when the script is executed it won't be able to find the target element thus the error.

One solution is to place your script in the load event handler like

window.onload = function () {
    var main = new Vue({
        el: '#main',
        data: {
            currentActivity: 'home'
        }
    });
}

Another syntax

window.addEventListener('load', function () {
    //your script
})

SQL to search objects, including stored procedures, in Oracle

In Oracle 11g, if you want to search any text in whole database or procedure below mentioned query can be used:

select * from user_source WHERE UPPER(text) LIKE '%YOUR SAGE%'

Format date to MM/dd/yyyy in JavaScript

All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.

i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.

I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
  var year = date.getFullYear();_x000D_
_x000D_
  var month = (1 + date.getMonth()).toString();_x000D_
  month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
  var day = date.getDate().toString();_x000D_
  day = day.length > 1 ? day : '0' + day;_x000D_
  _x000D_
  return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_


Update for ES2017 using String.padStart(), supported by all major browsers except IE.

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
    let year = date.getFullYear();_x000D_
    let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
    let day = date.getDate().toString().padStart(2, '0');_x000D_
  _x000D_
    return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

After insuring that the string "strOutput" has a correct XML structure, you can do this:

Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");

What is difference between INNER join and OUTER join

Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.

SELECT from nothing?

There is another possibility - standalone VALUES():

VALUES ('Hello World');

Output:

column1
Hello World

It is useful when you need to specify multiple values in compact way:

VALUES (1, 'a'), (2, 'b'), (3, 'c');

Output:

column1     column2
      1     a
      2     b
      3     c

DBFiddle Demo

This syntax is supported by SQLite/PostgreSQL/DB LUW/MariaDB 10.3.

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

How can I display a JavaScript object?

Another modification of pagewils code... his doesn't print out anything other than strings and leaves the number and boolean fields blank and I fixed the typo on the second typeof just inside the function as created by megaboss.

var print = function( o, maxLevel, level )
{
    if ( typeof level == "undefined" )
    {
        level = 0;
    }
    if ( typeof maxlevel == "undefined" )
    {
        maxLevel = 0;
    }

    var str = '';
    // Remove this if you don't want the pre tag, but make sure to remove
    // the close pre tag on the bottom as well
    if ( level == 0 )
    {
        str = '<pre>';   // can also be <pre>
    }

    var levelStr = '<br>';
    for ( var x = 0; x < level; x++ )
    {
        levelStr += '    ';   // all those spaces only work with <pre>
    }

    if ( maxLevel != 0 && level >= maxLevel )
    {
        str += levelStr + '...<br>';
        return str;
    }

    for ( var p in o )
    {
        switch(typeof o[p])
        {
          case 'string':
          case 'number':    // .tostring() gets automatically applied
          case 'boolean':   // ditto
            str += levelStr + p + ': ' + o[p] + ' <br>';
            break;

          case 'object':    // this is where we become recursive
          default:
            str += levelStr + p + ': [ <br>' + print( o[p], maxLevel, level + 1 ) + levelStr + ']</br>';
            break;
        }
    }

    // Remove this if you don't want the pre tag, but make sure to remove
    // the open pre tag on the top as well
    if ( level == 0 )
    {
        str += '</pre>';   // also can be </pre>
    }
    return str;
};

Throw HttpResponseException or return Request.CreateErrorResponse?

As far as I can tell, whether you throw an exception, or you return Request.CreateErrorResponse, the result is the same. If you look at the source code for System.Web.Http.dll, you will see as much. Take a look at this general summary, and a very similar solution that I have made: Web Api, HttpError, and the behavior of exceptions

Removing index column in pandas when reading a csv

DataFrames and Series always have an index. Although it displays alongside the column(s), it is not a column, which is why del df['index'] did not work.

If you want to replace the index with simple sequential numbers, use df.reset_index().

To get a sense for why the index is there and how it is used, see e.g. 10 minutes to Pandas.

Why use deflate instead of gzip for text files served by Apache?

mod_deflate requires fewer resources on your server, although you may pay a small penalty in terms of the amount of compression.

If you are serving many small files, I'd recommend benchmarking and load testing your compressed and uncompressed solutions - you may find some cases where enabling compression will not result in savings.

ExtJs Gridpanel store refresh

Try refreshing the view:

Ext.getCmp('yourGridId').getView().refresh();

How to uncheck a checkbox in pure JavaScript?

Recommended, without jQuery:

Give your <input> an ID and refer to that. Also, remove the checked="" part of the <input> tag if you want the checkbox to start out unticked. Then it's:

document.getElementById("my-checkbox").checked = true;

Pure JavaScript, with no Element ID (#1):

var inputs = document.getElementsByTagName('input');

for(var i = 0; i<inputs.length; i++){

  if(typeof inputs[i].getAttribute === 'function' && inputs[i].getAttribute('name') === 'copyNewAddrToBilling'){

    inputs[i].checked = true;

    break;

  }
}

Pure Javascript, with no Element ID (#2):

document.querySelectorAll('.text input[name="copyNewAddrToBilling"]')[0].checked = true;

document.querySelector('.text input[name="copyNewAddrToBilling"]').checked = true;

Note that the querySelectorAll and querySelector methods are supported in these browsers: IE8+, Chrome 4+, Safari 3.1+, Firefox 3.5+ and all mobile browsers.

If the element may be missing, you should test for its existence, e.g.:

var input = document.querySelector('.text input[name="copyNewAddrToBilling"]');
if (!input) { return; }

With jQuery:

$('.text input[name="copyNewAddrToBilling"]').prop('checked', true);

JavaScript: SyntaxError: missing ) after argument list

You have an extra closing } in your function.

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        }        // <== remove this brace
    }, false);
};

You really should be using something like JSHint or JSLint to help find these things. These tools integrate with many editors and IDEs, or you can just paste a code fragment into the above web sites and ask for an analysis.

Remove unwanted parts from strings in a column

Try this using regular expression:

import re
data['result'] = data['result'].map(lambda x: re.sub('[-+A-Za-z]',x)

Hibernate error: ids for this class must be manually assigned before calling save():

Your @Entity class has a String type for its @Id field, so it can't generate ids for you.

If you change it to an auto increment in the DB and a Long in java, and add the @GeneratedValue annotation:

@Id
@Column(name="U_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long U_id;

it will handle incrementing id generation for you.

How to re import an updated package while in Python Interpreter?

All the answers above about reload() or imp.reload() are deprecated.

reload() is no longer a builtin function in python 3 and imp.reload() is marked deprecated (see help(imp)).

It's better to use importlib.reload() instead.

dotnet ef not found in .NET Core 3

I was having this problem after I installed the dotnet-ef tool using Ansible with sudo escalated previllage on Ubuntu. I had to add become: no for the Playbook task, then the dotnet-ef tool became available to the current user.

  - name: install dotnet tool dotnet-ef
    command: dotnet tool install --global dotnet-ef --version {{dotnetef_version}}
    become: no

Use css gradient over background image

The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):

body{
  $colorStart: rgba(0,0,0,0);
  $colorEnd: rgba(0,0,0,0.8);
  @include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}

Remove spacing between table cells and rows

If you see table class it has border-spacing: 2px; You could override table class in your css and set its border-spacing: 0px!important in table; I did it like

table {
      border-collapse: separate;
      white-space: normal;
      line-height: normal;
      font-weight: normal;
      font-size: medium;
      font-style: normal;
      color: -internal-quirk-inherit;
      text-align: start;
      border-spacing: 0px!important;
      font-variant: normal;   }

It saved my day.Hope it would be of help. Thanks.

Variable interpolation in the shell

Use

"$filepath"_newstap.sh

or

${filepath}_newstap.sh

or

$filepath\_newstap.sh

_ is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

Opening a folder in explorer and selecting a file

You need to put the arguments to pass ("/select etc") in the second parameter of the Start method.

how to import csv data into django models

If you want to use a library, a quick google search for csv and django reveals two libraries - django-csvimport and django-adaptors. Let's read what they have to say about themselves...

  • django-adaptors:

Django adaptor is a tool which allow you to transform easily a CSV/XML file into a python object or a django model instance.

  • django-importcsv:

django-csvimport is a generic importer tool to allow the upload of CSV files for populating data.

The first requires you to write a model to match the csv file, while the second is more of a command-line importer, which is a huge difference in the way you work with them, and each is good for a different type of project.

So which one to use? That depends on which of those will be better suited for your project in the long run.

However, you can also avoid a library altogether, by writing your own django script to import your csv file, something along the lines of (warning, pseudo-code ahead):

# open file & create csvreader
import csv, yada yada yada

# import the relevant model
from myproject.models import Foo

#loop:
for line in csv file:
     line = parse line to a list
     # add some custom validation\parsing for some of the fields

     foo = Foo(fieldname1=line[1], fieldname2=line[2] ... etc. )
     try:
         foo.save()
     except:
         # if the're a problem anywhere, you wanna know about it
         print "there was a problem with line", i 

It's super easy. Hell, you can do it interactively through the django shell if it's a one-time import. Just - figure out what you want to do with your project, how many files do you need to handle and then - if you decide to use a library, try figuring out which one better suits your needs.

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

Getting parts of a URL (Regex)

regexp to get the URL path without the file.

url = 'http://domain/dir1/dir2/somefile' url.scan(/^(http://[^/]+)((?:/[^/]+)+(?=/))?/?(?:[^/]+)?$/i).to_s

It can be useful for adding a relative path to this url.

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

problem is not in the code, but you don't have added the driver to your project!!! You have to add the *.jar driver to your project...

Try putting this in your lib directory, then re-starting tomcat...

problem is Class.forName("com.mysql.jdbc.Driver"); it tries to load the driver, but it is not getting it, this is the reason you are getting:

java.lang.ClassNotFoundException.

Laravel - Session store not set on request

I'm using laravel 7.x and this problem arose.. the following fixed it:

go to kernel.php and add these 2 classes to protected $middleware

\Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class,

How to sum a list of integers with java streams?

You can use reduce method:

long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, (x, y) -> x + y);

or

long sum = result.stream().map(e -> e.getCreditAmount()).reduce(0L, Integer::sum);

Read files from a Folder present in project

This was helpful for me, if you use the

var dir = Directory.GetCurrentDirectory()

the path fill be beyond the current folder, it will incluide this path \bin\debug What I recommend you, is that you can use the

string dir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName

then print the dir value and verify the path is giving you

Is it possible to break a long line to multiple lines in Python?

From PEP 8 - Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

Example of implicit line continuation:

a = some_function(
    '1' + '2' + '3' - '4')

On the topic of line-breaks around a binary operator, it goes on to say:-

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.

Example of explicit line continuation:

a = '1'   \
    + '2' \
    + '3' \
    - '4'

open program minimized via command prompt

Try:

start  "" "C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE" --new-window/min

I had the same problem, but I was trying to open chrome.exe maximized. If I put the /min anywhere else in the command line, like before or after the empty title, it was ignored.

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;

public List<string> GetJsonValues(string filePath, string propertyName)
{
  List<string> values = new List<string>();
  string read = string.Empty;
  using (StreamReader r = new StreamReader(filePath))
  {
    var json = r.ReadToEnd();
    var jObj = JObject.Parse(json);
    foreach (var j in jObj.Properties())
    {
      if (j.Name.Equals(propertyName))
      {
        var value = jObj[j.Name] as JArray;
        return values = value.ToObject<List<string>>();
      }
    }
    return values;
  }
}

How to read all of Inputstream in Server Socket JAVA

The problem you have is related to TCP streaming nature.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

In client you need to write:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 Byte indicating type (For example, it could also be 2 or whatever).
  • 1 Byte (or whatever) for length of message
  • N Bytes for the value (N is indicated in length).

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

This is just a suggestion of a possible protocol. You could also get rid of "Type".

So it would be something like:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Command to find information about CPUs on a UNIX machine

The nproc command shows the number of processing units available:
$ nproc

Sample outputs: 4

lscpu gathers CPU architecture information form /proc/cpuinfon in human-read-able format:
$ lscpu

Sample outputs:

Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 1
Core(s) per socket: 4
CPU socket(s): 2
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 15
Stepping: 7
CPU MHz: 1866.669
BogoMIPS: 3732.83
Virtualization: VT-x
L1d cache: 32K
L1i cache: 32K
L2 cache: 4096K
NUMA node0 CPU(s): 0-7

jQuery/Javascript function to clear all the fields of a form

You can simply use the reset button type.

<input type="text" />
<input type="reset" />

jsfiddle

Edit: Remember that, the reset button, reset the form for the original values, so, if the field has some value set on the field <input type="text" value="Name" /> after press reset the field will reset the value inserted by user and come back with the word "name" in this example.

Reference: http://api.jquery.com/reset-selector/

How do detect Android Tablets in general. Useragent?

While Mobile Android may have "mobile" in it's user-agent string, what if it's using Opera Mobile for Android on a Tablet? It'll still have "mobile" in it's user-agent string, but should be displaying Tablet-sized sites. You'll need to test for "mobile" that is not preceded by "opera" rather than just "mobile"

or you could just forget about Opera Mobile.

"VT-x is not available" when I start my Virtual machine

You might try reducing your base memory under settings to around 3175MB and reduce your cores to 1. That should work given that your BIOS is set for virtualization. Use the f12 key, security, virtualization to make sure that it is enabled. If it doesn't say VT-x that is ok, it should say VT-d or the like.

How to get the return value from a thread in python?

join always return None, i think you should subclass Thread to handle return codes and so.

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

What is the format specifier for unsigned short int?

From the Linux manual page:

h      A  following  integer conversion corresponds to a short int or unsigned short int argument, or a fol-
       lowing n conversion corresponds to a pointer to a short int argument.

So to print an unsigned short integer, the format string should be "%hu".

Deleting rows with Python in a CSV file

You are very close; currently you compare the row[2] with integer 0, make the comparison with the string "0". When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:

row[2]!="0":

Also, you can use the with keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close statements:

import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

Note that input is a Python builtin, so I've used another variable name instead.


Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0" would work, so you can either use strip(row[2]) != 0, or check against " 0".

The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:

$ cat test.py 
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != " 0":
            writer.writerow(row)
$ cat first.csv 
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py 
$ cat first_edit.csv 
6.5, 5.4, 1, 320

Oracle: SQL query that returns rows with only numeric values

You can use the REGEXP_LIKE function as:

SELECT X 
FROM myTable 
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

Sample run:

SQL> SELECT X FROM SO;

X
--------------------
12c
123
abc
a12

SQL> SELECT X  FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

X
--------------------
123

SQL> 

How to resolve compiler warning 'implicit declaration of function memset'

A good way to findout what header file you are missing:

 man <section> <function call>

To find out the section use:

apropos <function call>

Example:

 man 3 memset
 man 2 send

Edit in response to James Morris:

  • Section | Description
  • 1 General commands
  • 2 System calls
  • 3 C library functions
  • 4 Special files (usually devices, those found in /dev) and drivers
  • 5 File formats and conventions
  • 6 Games and screensavers
  • 7 Miscellanea
  • 8 System administration commands and daemons

Source: Wikipedia Man Page

How do I use arrays in C++?

Assignment

For no particular reason, arrays cannot be assigned to one another. Use std::copy instead:

#include <algorithm>

// ...

int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);

This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays. std::copy is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy performs better. If in doubt, measure.

Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.

Parameter passing

Arrays cannot be passed by value. You can either pass them by pointer or by reference.

Pass by pointer

Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):

#include <numeric>
#include <cstddef>

int sum(const int* p, std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

int sum(const int* p, const int* q)
{
    return std::accumulate(p, q, 0);
}

As a syntactic alternative, you can also declare parameters as T p[], and it means the exact same thing as T* p in the context of parameter lists only:

int sum(const int p[], std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

You can think of the compiler as rewriting T p[] to T *p in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.

Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:

int sum(const int* p, std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n)   // the 8 has no meaning here

Pass by reference

Arrays can also be passed by reference:

int sum(const int (&a)[8])
{
    return std::accumulate(a + 0, a + 8, 0);
}

In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:

template <std::size_t n>
int sum(const int (&a)[n])
{
    return std::accumulate(a + 0, a + n, 0);
}

Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

As stated here this can happen when using the Gradle Tools v1.1.0. After updating to v1.1.3, this has not happened anymore.

How to close form

There are different methods to open or close winform. Form.Close() is one method in closing a winform.

When 'Form.Close()' execute , all resources created in that form are destroyed. Resources means control and all its child controls (labels , buttons) , forms etc.

Some other methods to close winform

  1. Form.Hide()
  2. Application.Exit()

Some methods to Open/Start a form

  1. Form.Show()
  2. Form.ShowDialog()
  3. Form.TopMost()

All of them act differently , Explore them !

How do I convert a String to a BigInteger?

BigInteger has a constructor where you can pass string as an argument.

try below,

private void sum(String newNumber) {
    // BigInteger is immutable, reassign the variable:
    this.sum = this.sum.add(new BigInteger(newNumber));
}

difference between variables inside and outside of __init__()

This is very easy to understand if you track class and instance dictionaries.

class C:
   one = 42
   def __init__(self,val):
        self.two=val
ci=C(50)
print(ci.__dict__)
print(C.__dict__)

The result will be like this:

{'two': 50}
{'__module__': '__main__', 'one': 42, '__init__': <function C.__init__ at 0x00000213069BF6A8>, '__dict__': <attribute '__dict__' of 'C' objects>, '__weakref__': <attribute '__weakref__' of 'C' objects>, '__doc__': None}

Note I set the full results in here but what is important that the instance ci dict will be just {'two': 50}, and class dictionary will have the 'one': 42 key value pair inside.

This is all you should know about that specific variables.

Passing bash variable to jq

Jq now have better way to acces environment variables, you can use env.EMAILI:

projectID=$(cat file.json | jq -r ".resource[] | select(.username==env.EMAILID) | .id")

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

How should I use Outlook to send code snippets?

Here's what works for me, and is quickest and causes the least amount of pain / annoyance:

1) Paste you code snippet into sublime; make sure your syntax is looking good.

2) Right click and choose 'Copy as RTF'

3) Paste into your email

4) Done

Can an AJAX response set a cookie?

Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

"Uncaught TypeError: Illegal invocation" in Chrome

You can also use:

var obj = {
    alert: alert.bind(window)
};
obj.alert('I´m an alert!!');

SOAP PHP fault parsing WSDL: failed to load external entity?

The problem may lie in you don't have enabled openssl extention in your php.ini file

go to your php.ini file end remove ; in line where extension=openssl is

Of course in question code there is a part of code responsible for checking whether extension is loaded or not but maybe some uncautious forget about it

Overlay with spinner

Here is simple overlay div without using any gif, This can be applied over another div.

<style>
.loader {
  position: relative;
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 70px;
  height: 70px;
  left:50%;
  top:50%;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
}
#overlay{
    position: absolute;
    top:0px;
    left:0px;
    width: 100%;
    height: 100%;
    background: black;
    opacity: .5;
}
.container{
    position:relative;
    height: 300px;
    width: 200px;
    border:1px solid
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

<h2>How To Create A Loader</h2>

<div class="container">
  <h3>Overlay over this div</h3>
  <div id="overlay">
      <div class="loader"></div>
  </div>
<div>

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

Sometime the default version will not update. Add this command

AWS_S3_SIGNATURE_VERSION = "s3v4"

in settings.py

remove inner shadow of text input

here is a small snippet that might be cool to try out:

input {
border-radius: 10px;
border-color: violet;
border-style: solid;
}

note that: border-style removes the inner shadow.

_x000D_
_x000D_
input {_x000D_
    border-radius: 10px;_x000D_
    border-color: violet;_x000D_
    border-style: solid;_x000D_
  }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Codeigniter - multiple database connections

While looking at your code, the only thing I see wrong, is when you try to load the second database:

$DB2=$this->load->database($config);

When you want to retrieve the database object, you have to pass TRUE in the second argument.

From the Codeigniter User Guide:

By setting the second parameter to TRUE (boolean) the function will return the database object.

So, your code should instead be:

$DB2=$this->load->database($config, TRUE);

That will make it work.

Installing MySQL Python on Mac OS X

Here's what I would install, especially if you want to use homebrew:

  • XCode and the command line tools (as suggested by @7stud, @kjti)
  • Install homebrew
  • brew install mysql-connector-c
  • pip install mysql-python

Adding double quote delimiters into csv file

open powershell and run below command:

import-csv C:\Users\Documents\Weekly_Status.csv | export-csv C:\Users\Documents\Weekly_Status2.csv  -NoTypeInformation -Encoding UTF8

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I solved this issue by running the following command in an elevated command prompt as specified in this post.

net start mssqlserver

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

Psql list all tables

A one-line example is

\dt schemaname.* 

in your senario

\dt public.*

Format Date/Time in XAML in Silverlight

you can also use just

StringFormat=d

in your datagrid column for date time showing

finally it will be

   <sdk:DataGridTextColumn  Binding="{Binding Path=DeliveryDate,StringFormat=d}" Header="Delivery date" Width="*" />

the out put will look like

enter image description here

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

MySQL query to get column names?

This question is old, but I got here looking for a way to find a given query its field names in a dynamic way (not necessarily only the fields of a table). And since people keep pointing this as the answer for that given task in other related questions, I'm sharing the way I found it can be done, using Gavin Simpson's tips:

//Function to generate a HTML table from a SQL query
function myTable($obConn,$sql)
{
    $rsResult = mysqli_query($obConn, $sql) or die(mysqli_error($obConn));
    if(mysqli_num_rows($rsResult)>0)
    {
        //We start with header. >>>Here we retrieve the field names<<<
        echo "<table width=\"100%\" border=\"0\" cellspacing=\"2\" cellpadding=\"0\"><tr align=\"center\" bgcolor=\"#CCCCCC\">";
        $i = 0;
        while ($i < mysqli_num_fields($rsResult)){
           $field = mysqli_fetch_field_direct($rsResult, $i);
           $fieldName=$field->name;
           echo "<td><strong>$fieldName</strong></td>";
           $i = $i + 1;
        }
        echo "</tr>"; 
        //>>>Field names retrieved<<<

        //We dump info
        $bolWhite=true;
        while ($row = mysqli_fetch_assoc($rsResult)) {
            echo $bolWhite ? "<tr bgcolor=\"#CCCCCC\">" : "<tr bgcolor=\"#FFF\">";
            $bolWhite=!$bolWhite;
            foreach($row as $data) {
                echo "<td>$data</td>";
            }
            echo "</tr>";
        }
        echo "</table>";
    }
}

This can be easily modded to insert the field names in an array.

Using a simple: $sql="SELECT * FROM myTable LIMIT 1" can give you the fields of any table, without needing to use SHOW COLUMNS or any extra php module, if needed (removing the data dump part).

Hopefully this helps someone else.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

As noted in the official documentation, simply apply the class(es) btn btn-link:

<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>

For example, with the code you have provided:

_x000D_
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<form action="..." method="post">_x000D_
  <div class="row-fluid">_x000D_
    <!-- Navigation for the form -->_x000D_
    <div class="span3">_x000D_
      <ul class="nav nav-tabs nav-stacked">_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 1">Link 1</button>_x000D_
        </li>_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 2">Link 2</button>_x000D_
        </li>_x000D_
        <!-- ... -->_x000D_
      </ul>_x000D_
    </div>_x000D_
    <!-- The actual form -->_x000D_
    <div class="span9">_x000D_
      <!-- ... -->_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Plot multiple lines in one graph

Instead of using the outrageously convoluted data structures required by ggplot2, you can use the native R functions:

tab<-read.delim(text="
Company 2011 2013
Company1 300 350
Company2 320 430
Company3 310 420
",as.is=TRUE,sep=" ",row.names=1)

tab<-t(tab)

plot(tab[,1],type="b",ylim=c(min(tab),max(tab)),col="red",lty=1,ylab="Value",lwd=2,xlab="Year",xaxt="n")
lines(tab[,2],type="b",col="black",lty=2,lwd=2)
lines(tab[,3],type="b",col="blue",lty=3,lwd=2)
grid()
legend("topleft",legend=colnames(tab),lty=c(1,2,3),col=c("red","black","blue"),bg="white",lwd=2)
axis(1,at=c(1:nrow(tab)),labels=rownames(tab))

R multiple lines plot

Switching a DIV background image with jQuery

One way to do this is to put both images in the HTML, inside a SPAN or DIV, you can hide the default either with CSS, or with JS on page load. Then you can toggle on click. Here is a similar example I am using to put left/down icons on a list:

$(document).ready(function(){
    $(".button").click(function () {
        $(this).children(".arrow").toggle();
            return false;
    });
});

<a href="#" class="button">
    <span class="arrow">
        <img src="/images/icons/left.png" alt="+" />
    </span>
    <span class="arrow" style="display: none;">
        <img src="/images/down.png" alt="-" />
    </span>
</a>

Using CSS in Laravel views?

You can simply put all the files in its specified folder in public like


public/css
public/js
public/images


Then just call the files as in normal html like
<link href="css/file.css" rel="stylesheet" type="text/css">

It works just fine in any version of Laravel

Change Input to Upper Case

I think the most easiest way to do is by using Bootstrap's class ".text-uppercase"

<input type="text" class="text-uppercase" />

error: package javax.servlet does not exist

In my case, migrating a Spring 3.1 app up to 3.2.7, my solution was similar to Matthias's but a bit different -- thus why I'm documenting it here:

In my POM I found this dependency and changed it from 6.0 to 7.0:

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

Then later in the POM I upgraded this plugin from 6.0 to 7.0:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    ...
                    <configuration>
                        ...
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

How to know the version of pip itself

Many people use both 2.X and 3.X python. You can use pip -V to show default pip version.
If you have many python versions, and you want to install some packages through different pip, I advise this way:

sudo python2.X -m pip install some-package==0.16

How to move up a directory with Terminal in OS X

cd .. will back the directory up by one. If you want to reach a folder in the parent directory, you can do something like cd ../foldername. You can use the ".." trick as many times as you want to back up through multiple parent directories. For example, cd ../../Applications would take you to Macintosh HD/Applications

Replace all 0 values to NA

Replacing all zeroes to NA:

df[df == 0] <- NA



Explanation

1. It is not NULL what you should want to replace zeroes with. As it says in ?'NULL',

NULL represents the null object in R

which is unique and, I guess, can be seen as the most uninformative and empty object.1 Then it becomes not so surprising that

data.frame(x = c(1, NULL, 2))
#   x
# 1 1
# 2 2

That is, R does not reserve any space for this null object.2 Meanwhile, looking at ?'NA' we see that

NA is a logical constant of length 1 which contains a missing value indicator. NA can be coerced to any other vector type except raw.

Importantly, NA is of length 1 so that R reserves some space for it. E.g.,

data.frame(x = c(1, NA, 2))
#    x
# 1  1
# 2 NA
# 3  2

Also, the data frame structure requires all the columns to have the same number of elements so that there can be no "holes" (i.e., NULL values).

Now you could replace zeroes by NULL in a data frame in the sense of completely removing all the rows containing at least one zero. When using, e.g., var, cov, or cor, that is actually equivalent to first replacing zeroes with NA and setting the value of use as "complete.obs". Typically, however, this is unsatisfactory as it leads to extra information loss.

2. Instead of running some sort of loop, in the solution I use df == 0 vectorization. df == 0 returns (try it) a matrix of the same size as df, with the entries TRUE and FALSE. Further, we are also allowed to pass this matrix to the subsetting [...] (see ?'['). Lastly, while the result of df[df == 0] is perfectly intuitive, it may seem strange that df[df == 0] <- NA gives the desired effect. The assignment operator <- is indeed not always so smart and does not work in this way with some other objects, but it does so with data frames; see ?'<-'.


1 The empty set in the set theory feels somehow related.
2 Another similarity with the set theory: the empty set is a subset of every set, but we do not reserve any space for it.

How to split an integer into an array of digits?

While list(map(int, str(x))) is the Pythonic approach, you can formulate logic to derive digits without any type conversion:

from math import log10

def digitize(x):
    n = int(log10(x))
    for i in range(n, -1, -1):
        factor = 10**i
        k = x // factor
        yield k
        x -= k * factor

res = list(digitize(5243))

[5, 2, 4, 3]

One benefit of a generator is you can feed seamlessly to set, tuple, next, etc, without any additional logic.