Programs & Examples On #Qlocalsocket

QLocalSocket is a class in Qt framework to create local sockets mostly used for IPC.

Setting Environment Variables for Node to retrieve

As expansion of @ctrlplusb answer,
I would suggest you to also take a look to the env-dot-prop package.

It allows you to set/get properties from process.env using a dot-path.

Let's assume that your process.env contains the following:

process.env = {
  FOO_BAR: 'baz'
  'FOO_': '42'
}

Then you can manipulate the environment variables like that:

const envDotProp = require('env-dot-prop');

console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_': '42'}

envDotProp.get('foo');
//=> {bar: 'baz', '': '42'}

envDotProp.get('foo.');
//=> '42'

envDotProp.get('foo.', {parse: true});
//=> 42

envDotProp.set('baz.foo', 'bar');
envDotProp.get('', {parse: true});
//=> {foo: {bar: 'baz', '': 42}, baz: {foo: 'bar'}}

console.log(process.env);
//=> {FOO_BAR: 'baz', 'FOO_': '42', BAZ_FOO: 'bar'}

envDotProp.delete('foo');
envDotProp.get('');
//=> {baz: {foo: 'bar'}}

console.log(process.env);
//=> {BAZ_FOO: 'bar'}

This helps you to parse the environment variables and use them as a config object in your app.
It also helps you implement a 12-factor configuration.

Create a mocked list by mockito

We can mock list properly for foreach loop. Please find below code snippet and explanation.

This is my actual class method where I want to create test case by mocking list. this.nameList is a list object.

public void setOptions(){
    // ....
    for (String str : this.nameList) {
        str = "-"+str;
    }
    // ....
}

The foreach loop internally works on iterator, so here we crated mock of iterator. Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn(), i.e. on hasNext() we pass 1st true and on second call false, so that our loop will continue only two times. On next() we just return actual return value.

@Test
public void testSetOptions(){
    // ...
    Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
    Mockito.when(itr.hasNext()).thenReturn(true, false);
    Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);  

    List mockNameList = Mockito.mock(List.class);
    Mockito.when(mockNameList.iterator()).thenReturn(itr);
    // ...
}

In this way we can avoid sending actual list to test by using mock of list.

How do I get the APK of an installed app without root access?

I got a does not exist error

Here is how I make it works:

adb shell pm list packages -f | findstr zalo

package:/data/app/com.zing.zalo-1/base.apk=com.zing.zalo

adb shell

mido:/ $ cp /data/app/com.zing.zalo-1/base.apk /sdcard/zalo.apk
mido:/ $ exit


adb pull /sdcard/zalo.apk Desktop

/sdcard/zalo.apk: 1 file pulled. 7.7 MB/s (41895394 bytes in 5.200s)

How to prevent a jQuery Ajax request from caching in Internet Explorer?

you can define it like this :

let table = $('.datatable-sales').DataTable({
        processing: true,
        responsive: true,
        serverSide: true,
        ajax: {
            url: "<?php echo site_url("your url"); ?>",
            cache: false,
            type: "POST",
            data: {
                <?php echo your api; ?>,
            }
        }

or like this :

$.get({url: <?php echo json_encode(site_url('your api'))?>, cache: false})

hope it helps

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/

Javascript close alert box

I want to be able to close an alert box automatically using javascript after a certain amount of time or on a specific event (i.e. onkeypress)

A sidenote: if you have an Alert("data"), you won't be able to keep code running in background (AFAIK)... . the dialog box is a modal window, so you can't lose focus too. So you won't have any keypress or timer running...

How to write to a JSON file in the correct format

With formatting

require 'json'
tempHash = {
    "key_a" => "val_a",
    "key_b" => "val_b"
}
File.open("public/temp.json","w") do |f|
  f.write(JSON.pretty_generate(tempHash))
end

Output

{
    "key_a":"val_a",
    "key_b":"val_b"
}

How to git-cherry-pick only changes to certain files?

I usually use the -p flag with a git checkout from the other branch which I find easier and more granular than most other methods I have come across.

In principle:

git checkout <other_branch_name> <files/to/grab in/list/separated/by/spaces> -p

example:

git checkout mybranch config/important.yml app/models/important.rb -p

You then get a dialog asking you which changes you want in "blobs" this pretty much works out to every chunk of continuous code change which you can then signal y (Yes) n (No) etc for each chunk of code.

The -p or patch option works for a variety of commands in git including git stash save -p which allows you to choose what you want to stash from your current work

I sometimes use this technique when I have done a lot of work and would like to separate it out and commit in more topic based commits using git add -p and choosing what I want for each commit :)

Excel doesn't update value unless I hit Enter

I Encounter this problem before. I suspect that is some of ur cells are link towards other sheet, which the other sheets is returning #NAME? which ends up the current sheets is not working on calculation.

Try solve ur other sheets that is linked

Javascript - removing undefined fields from an object

I prefer to use something like Lodash:

import { pickBy, identity } from 'lodash'

const cleanedObject = pickBy(originalObject, identity)

Note that the identity function is just x => x and its result will be false for all falsy values. So this removes undefined, "", 0, null, ...

If you only want the undefined values removed you can do this:

const cleanedObject = pickBy(originalObject, v => v !== undefined)

It gives you a new object, which is usually preferable over mutating the original object like some of the other answers suggest.

-bash: export: `=': not a valid identifier

You cannot put spaces around the = sign when you do:

export foo=bar

Remove the spaces you have and you should be good to go.

If you type:

export foo = bar

the shell will interpret that as a request to export three names: foo, = and bar. = isn't a valid variable name, so the command fails. The variable name, equals sign and it's value must not be separated by spaces for them to be processed as a simultaneous assignment and export.

Centering a div block without the width

Try this new css and markup

Here is modified HTML:

<div class="product_container">
<div class="products" id="products">
   <div id="product_15" class="products_box">
       <img src="/images/ecommerce/card_default.png">
       <div class="price">R$ 0,01</div>
   </div>
   <div id="product_15" class="products_box">
       <img src="/images/ecommerce/card_default.png">
       <div class="price">R$ 0,01</div>
   </div>   
   <div id="product_15" class="products_box">
       <img src="/images/ecommerce/card_default.png">
       <div class="price">R$ 0,01</div>
   </div>
</div>

And here is modified CSS:

<pre>
.product_container 
 {
 text-align:    center;
 height:        150px;
 }

.products {
    left: 50%;
height:35px;
float:left;
position: relative;
margin: 0 auto;
width:auto;
}
.products .products_box
{
width:auto;
height:auto;
float:left;
  right: 50%;
  position: relative;
}
.price {
    margin:        6px 2px;
    width:         137px;
    color:         #666;
    font-size:     14pt;
    font-style:    normal;
    border:        1px solid #CCC;
    background-color:   #EFEFEF;
}

Spring MVC - How to return simple String as JSON in Rest Controller

Make simple:

    @GetMapping("/health")
    public ResponseEntity<String> healthCheck() {
        LOG.info("REST request health check");
        return new ResponseEntity<>("{\"status\" : \"UP\"}", HttpStatus.OK);
    }

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

Do you use source control for your database items?

I've heard people say you absolutely have to keep your schemas in the database. I'm not sure I agree. This really depends on the system you're working with. If your system is relatively small and the data is not terribly important. And the the speed at which you need to bring another development environment online is crucial.. then yes.. you can benefit from it. However when your schema is useless without the data and the database is extremely large, it becomes virtually impossible to "source control" your database. Sure, you can still keep your DDL code in source control but that's essentially useless. You can't get the data needed without backup/restore.

In larger database development efforts, I've found backup and restore as the preferred rollback option. Sure you can keep procs, views, functions etc in source control but keeping table.sql is not necessary. Also, if your deployment process is airtight, you'll most likely never have to "rollback" your production environment.

How to change the status bar color in Android?

For Java Developers:

As @Niels said you have to place in values-v21/styles.xml:

<item name="android:statusBarColor">@color/black</item>

But add tools:targetApi="lollipop" if you want single styles.xml, like:

<item name="android:statusBarColor" tools:targetApi="lollipop">@color/black</item>

For Kotlin Developers:

window.statusBarColor = ContextCompat.getColor(this, R.color.color_name)

Remove unused imports in Android Studio

Press Alt + Enter with the cursor on top of the import. The Optimize imports menu will show. Press Enter again. Your unused imports will be removed.

enter image description here

Insert an element at a specific index in a list and return the updated list

The cleanest approach is to copy the list and then insert the object into the copy. On Python 3 this can be done via list.copy:

new = old.copy()
new.insert(index, value)

On Python 2 copying the list can be achieved via new = old[:] (this also works on Python 3).

In terms of performance there is no difference to other proposed methods:

$ python --version
Python 3.8.1
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b.insert(500, 3)"
100000 loops, best of 5: 2.84 µsec per loop
$ python -m timeit -s "a = list(range(1000))" "b = a.copy(); b[500:500] = (3,)"
100000 loops, best of 5: 2.76 µsec per loop

vagrant login as root by default

Adding this to the Vagrantfile worked for me. These lines are the equivalent of you entering sudo su - every time you login. Please notice that this requires reprovisioning the VM.

config.vm.provision "shell", inline: <<-SHELL
    echo "sudo su -" >> .bashrc
SHELL

multi line comment vb.net in Visual studio 2010

Highlight block of text, then:

Comment Block: Ctrl + K + C

Uncomment Block: Ctrl + K + U

Tested in Visual Studio 2012

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

Build solution will build any projects in the solution that have changed. Rebuild builds all projects no matter what, clean solution removes all temporary files ensuring that the next build is complete.

How to hide a TemplateField column in a GridView

A slight improvement using column name, IMHO:

    Private Sub GridView1_Init(sender As Object, e As System.EventArgs) Handles GridView1.Init
    For Each dcf As DataControlField In GridView1.Columns
        Select Case dcf.HeaderText.ToUpper
            Case "CBSELECT"
                dcf.Visible = Me.CheckBoxVisible
                dcf.HeaderText = "<small>Select</small>"
        End Select
    Next
End Sub

This allows control over multiple column. I initially use a 'technical' column name, matching the control name within. This makes it obvious within the ASCX page that it's a control column. Then swap out the name as desired for presentation. If I spy the odd name in production, I know I skipped something. The "ToUpper" avoids case-issues.

Finally, this runs ONE time on any post instead of capturing the event during row-creation.

How to import RecyclerView for Android L-preview

in my case I fixed it by putting compile 'com.android.support:recyclerview-v7:22.0.0' as a dependency into my gradle build

(with Android studio v. 1.2.1.1 and all sdk's updated.)

It's really annoying when codes are updated so fast and the IDE can't keep track of them, and you have to manually fix for them, wasting time and resources.

But well, at last it works.

How to extend a class in python?

class MyParent:

    def sayHi():
        print('Mamma says hi')
from path.to.MyParent import MyParent

class ChildClass(MyParent):
    pass

An instance of ChildClass will then inherit the sayHi() method.

How to get the HTML for a DOM element in javascript

old question but for newcomers that come around :

document.querySelector('div').outerHTML

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.

How to connect with Java into Active Directory

You can use DDC (Domain Directory Controller). It is a new, easy to use, Java SDK. You don't even need to know LDAP to use it. It exposes an object-oriented API instead.

You can find it here.

Import module from subfolder

There's no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

Understanding the difference between Object.create() and new SomeFunction()

Let me try to explain (more on Blog) :

  1. When you write Car constructor var Car = function(){}, this is how things are internally: A diagram of prototypal chains when creating javascript objects We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.
  2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods What is happening?

    Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
    Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).

Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.

Preferred way in OO JavaScript :

Suppose we have two objects a and b.

var a = new Object();
var b = new Object();

Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.

Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).

Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype. Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:

var b = Object.create(a);

then,

a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)

So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.

How to import js-modules into TypeScript file?

2021 Solution

If you're still getting this error message:

TS7016: Could not find a declaration file for module './myjsfile'

Then you might need to add the following to tsconfig.json

{
  "compilerOptions": {
    ...
    "allowJs": true,
    "checkJs": false,
    ...
  }
}

This prevents typescript from trying to apply module types to the imported javascript.

Mac OS X and multiple Java versions

I answer lately and I really recommand you to use SDKMAN instead of Homebrew.

With SDKMAN you can install easily different version of JAVA in your mac and switch from on version to another.

Java in your mac

You can also use SDKMAN for ANT, GRADLE, KOTLIN, MAVEN, SCALA, etc...

To install a version in your mac you can run the command sdk install java 15.0.0.j9-adpt cmd

Android Eclipse - Could not find *.apk

This is caused by JAVA_HOME not being set correctly. It can be easily resolved by following the steps in this article.

How do I close an Android alertdialog

I would try putting a

Log.e("SOMETAG", "dialog button was clicked");

before the dialog.dismiss() line in your code to see if it actually reaches that section.

How do you access the value of an SQL count () query in a Java program

The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

rs3.getInt(1);

to get the value in the first, and in your case, only column.

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

Mutex lock threads

Below, code snippet, will help you in understanding the mutex-lock-unlock concept. Attempt dry-run on the code. (further by varying the wait-time and process-time, you can build you understanding).

Code for your reference:

#include <stdio.h>
#include <pthread.h>

void in_progress_feedback(int);

int global = 0;
pthread_mutex_t mutex;
void *compute(void *arg) {

    pthread_t ptid = pthread_self();
    printf("ptid : %08x \n", (int)ptid);    

    int i;
    int lock_ret = 1;   
    do{

        lock_ret = pthread_mutex_trylock(&mutex);
        if(lock_ret){
            printf("lock failed(%08x :: %d)..attempt again after 2secs..\n", (int)ptid,  lock_ret);
            sleep(2);  //wait time here..
        }else{  //ret =0 is successful lock
            printf("lock success(%08x :: %d)..\n", (int)ptid, lock_ret);
            break;
        }

    } while(lock_ret);

        for (i = 0; i < 10*10 ; i++) 
        global++;

    //do some stuff here
    in_progress_feedback(10);  //processing-time here..

    lock_ret = pthread_mutex_unlock(&mutex);
    printf("unlocked(%08x :: %d)..!\n", (int)ptid, lock_ret);

     return NULL;
}

void in_progress_feedback(int prog_delay){

    int i=0;
    for(;i<prog_delay;i++){
    printf(". ");
    sleep(1);
    fflush(stdout);
    }

    printf("\n");
    fflush(stdout);
}

int main(void)
{
    pthread_t tid0,tid1;
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid0, NULL, compute, NULL);
    pthread_create(&tid1, NULL, compute, NULL);
    pthread_join(tid0, NULL);
    pthread_join(tid1, NULL);
    printf("global = %d\n", global);
    pthread_mutex_destroy(&mutex);
          return 0;
}

Disable firefox same origin policy

The cors-everywhere addon works for me until Firefox 68, after 68 I need to adjust 'privacy.file_unique_origin' -> false (by open 'about:config') to solve 'CORS request not HTTP' for new CORS same-origin rule introduced.

How to include() all PHP files from a directory?

<?php
//Loading all php files into of functions/ folder 

$folder =   "./functions/"; 
$files = glob($folder."*.php"); // return array files

 foreach($files as $phpFile){   
     require_once("$phpFile"); 
}

How can I open a URL in Android's web browser from my application?

Simply go with short one to open your Url in Browser:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("YourUrlHere"));
startActivity(browserIntent);

Appending output of a Batch file To log file

Instead of using ">" to redirect like this:

java Foo > log

use ">>" to append normal "stdout" output to a new or existing file:

java Foo >> log

However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:

java Foo >> log 2>&1 

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Create a Maven project in Eclipse complains "Could not resolve archetype"

This might sound silly, but make sure the "Offline" checkbox in Maven settings is unchecked. I was trying to create a project and got this error until I noticed the checkbox.

how to get the value of a textarea in jquery?

You can also get the value by element's name attribute.

var message = $("#formId textarea[name=message]").val();

Good tool for testing socket connections?

Hercules is fantastic. It's a fully functioning tcp/udp client/server, amazing for debugging sockets. More details on the web site.

Raise warning in Python without interrupting program

By default, unlike an exception, a warning doesn't interrupt.

After import warnings, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning by default.

>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.

To simply use a preexisting class instead, e.g. DeprecationWarning:

>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.

Creating a custom warning class is similar to creating a custom exception class:

>>> class MyCustomWarning(UserWarning):
...     pass
... 
... warnings.warn('This is my custom warning.', MyCustomWarning)

<string>:1: MyCustomWarning: This is my custom warning.

For testing, consider assertWarns or assertWarnsRegex.


As an alternative, especially for standalone applications, consider the logging module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.

How to set background image of a view?

It's a very bad idea to directly display any text on an irregular and ever changing background. No matter what you do, some of the time the text will be hard to read.

The best design would be to have the labels on a constant background with the images changing behind that.

You can set the labels background color from clear to white and set the from alpha to 50.0 you get a nice translucent effect. The only problem is that the label's background is a stark rectangle.

To get a label with a background with rounded corners you can use a button with user interaction disabled but the user might mistake that for a button.

The best method would be to create image of the label background you want and then put that in an imageview and put the label with the default transparent background onto of that.

Plain UIViews do not have an image background. Instead, you should make a UIImageView your main view and then rotate the images though its image property. If you set the UIImageView's mode to "Scale to fit" it will scale any image to fit the bounds of the view.

Egit rejected non-fast-forward

In the meantime (while you were updating your project), other commits have been made to the 'master' branch. Therefore, you must pull those changes first to be able to push your changes.

What is event bubbling and capturing?

As other said, bubbling and capturing describe in which order some nested elements receive a given event.

I wanted to point out that for the innermost element may appear something strange. Indeed, in this case the order in which the event listeners are added does matter.

In the following example, capturing for div2 will be executed first than bubbling; while bubbling for div4 will be executed first than capturing.

_x000D_
_x000D_
function addClickListener (msg, num, type) {
  document.querySelector("#div" + num)
    .addEventListener("click", () => alert(msg + num), type);
}
bubble  = (num) => addClickListener("bubble ", num, false);
capture = (num) => addClickListener("capture ", num, true);

// first capture then bubble
capture(1);
capture(2);
bubble(2);
bubble(1);

// try reverse order
bubble(3);
bubble(4);
capture(4);
capture(3);
_x000D_
#div1, #div2, #div3, #div4 {
  border: solid 1px;
  padding: 3px;
  margin: 3px;
}
_x000D_
<div id="div1">
  div 1
  <div id="div2">
    div 2
  </div>
</div>
<div id="div3">
  div 3
  <div id="div4">
    div 4
  </div>
</div>
_x000D_
_x000D_
_x000D_

How I can get web page's content and save it into the string variable

Webclient client = new Webclient();
string content = client.DownloadString(url);

Pass the URL of page who you want to get. You can parse the result using htmlagilitypack.

Get file size before uploading

<script type="text/javascript">
function AlertFilesize(){
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }

    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}

    alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>

<input id="fileInput" type="file" onchange="AlertFilesize();" />

Work on IE and FF

How to remove time portion of date in C# in DateTime object only?

To get only the date portion use the ToString() method,

example: DateTime.Now.Date.ToString("dd/MM/yyyy")

Note: The mm in the dd/MM/yyyy format must be capitalized

Can't push image to Amazon ECR - fails with "no basic auth credentials"

For Mac OSX

TL;DR Make sure your "auths" key matches your credential store key exactly

  • Check your docker config:

cat ~/.docker/config.json

Sample Result:

{
    "auths": {
        "https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },
    "HttpHeaders": {
        "User-Agent": "Docker-Client/19.03.5 (darwin)"
    },
    "credsStore": "osxkeychain"
}

Notice that the "auths" value is an empty object and docker is using a credential store "osxkeychain".

  • Open Mac's "Keychain Access" app and find the name "Docker Credentials"

enter image description here

Notice the Where: field

  • Make sure the auths key in ~/.docker/config.json matches the Where: field in Keychain Access.

If the auths key in ~/.docker/config.json does NOT match they Where: field in the keychain, you may get a Login Succeeded from docker login... but still get ERROR: Service 'web' failed to build: Get https://55511155511.dkr.ecr.us-east-1.amazonaws.com/v2/path/to/image/latest: no basic auth credentials when you try to pull.

In my case, I needed to add https://

Original

    "auths": {
        "55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },

Fixed

    "auths": {
        "https://55511155511.dkr.ecr.us-east-1.amazonaws.com": {}
    },

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

How do I read a large csv file with pandas?

The function read_csv and read_table is almost the same. But you must assign the delimiter “,” when you use the function read_table in your program.

def get_from_action_data(fname, chunk_size=100000):
    reader = pd.read_csv(fname, header=0, iterator=True)
    chunks = []
    loop = True
    while loop:
        try:
            chunk = reader.get_chunk(chunk_size)[["user_id", "type"]]
            chunks.append(chunk)
        except StopIteration:
            loop = False
            print("Iteration is stopped")

    df_ac = pd.concat(chunks, ignore_index=True)

How to Convert UTC Date To Local time Zone in MySql Select Query

SELECT CONVERT_TZ() will work for that.but its not working for me.

Why, what error do you get?

SELECT CONVERT_TZ(displaytime,'GMT','MET');

should work if your column type is timestamp, or date

http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_convert-tz

Test how this works:

SELECT CONVERT_TZ(a_ad_display.displaytime,'+00:00','+04:00');

Check your timezone-table

SELECT * FROM mysql.time_zone;
SELECT * FROM mysql.time_zone_name;

http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html

If those tables are empty, you have not initialized your timezone tables. According to link above you can use mysql_tzinfo_to_sql program to load the Time Zone Tables. Please try this

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo

or if not working read more: http://dev.mysql.com/doc/refman/5.5/en/mysql-tzinfo-to-sql.html

Get the size of the screen, current web page and browser window

I developed a library for knowing the real viewport size for desktops and mobiles browsers, because viewport sizes are inconsistents across devices and cannot rely on all the answers of that post (according to all the research I made about this) : https://github.com/pyrsmk/W

Hibernate Union alternatives

Here is a special case, but might inspire you to create your own work around. The goal here is to count the total number of records from two different tables where records meet a particular criteria. I believe this technique will work for any case where you need to aggregate data from across multiple tables/sources.

I have some special intermediate classes setup, so the code which calls the named query is short and sweet, but you can use whatever method you normally use in conjunction with named queries to execute your query.

QueryParms parms=new QueryParms();
parms.put("PROCDATE",PROCDATE);

Long pixelAll = ((SourceCount)Fetch.row("PIXEL_ALL",parms,logger)).getCOUNT();

As you can see here, the named query begins to look an aweful lot like a union statement:

@Entity
@NamedQueries({
        @NamedQuery(
            name  ="PIXEL_ALL",
            query = "" +
                    "  SELECT new SourceCount(" +
                    "     (select count(a) from PIXEL_LOG_CURR1 a " +
                    "       where to_char(a.TIMESTAMP, 'YYYYMMDD') = :PROCDATE " +
                    "     )," +
                    "     (select count(b) from PIXEL_LOG_CURR2 b" +
                    "       where to_char(b.TIMESTAMP, 'YYYYMMDD') = :PROCDATE " +
                    "     )" +
                    ") from Dual1" +
                    ""
    )
})

public class SourceCount {
    @Id
    private Long   COUNT;

    public SourceCount(Long COUNT1, Long COUNT2) {
        this.COUNT = COUNT1+COUNT2;
    }

    public Long getCOUNT() {
        return COUNT;
    }

    public void setCOUNT(Long COUNT) {
        this.COUNT = COUNT;
    }
}

Part of the magic here is to create a dummy table and insert one record into it. In my case, I named it dual1 because my database is Oracle, but I don't think it matters what you call the dummy table.

@Entity
@Table(name="DUAL1")
public class Dual1 {
    @Id
    Long ID;
}

Don't forget to insert your dummy record:

SQL> insert into dual1 values (1);

How do you remove an array element in a foreach loop?

if you have scenario in which you have to remove more then one values from the foreach array in this case you have to pass value by reference in for each: I try to explain this scenario:

foreach ($manSkuQty as $man_sku => &$man_qty) {

               foreach ($manufacturerSkus as $key1 => $val1) {

  // some processing here and unset first loops entries                     
 //  here dont include again for next iterations
                           if(some condition)
                            unset($manSkuQty[$key1]);

                        }
               }
}

in second loop you want to unset first loops entries dont come again in the iteration for performance purpose or else then unset from memory as well because in memory they present and will come in iterations.

Finding all positions of substring in a larger string in C#

@csam is correct in theory, although his code will not complie and can be refractored to

public static IEnumerable<int> IndexOfAll(this string sourceString, string matchString)
{
    matchString = Regex.Escape(matchString);
    return from Match match in Regex.Matches(sourceString, matchString) select match.Index;
}

Node.js Logging

Observe that errorLogger is a wrapper around logger.trace. But the level of logger is ERROR so logger.trace will not log its message to logger's appenders.

The fix is to change logger.trace to logger.error in the body of errorLogger.

A weighted version of random.choice

Here is another version of weighted_choice that uses numpy. Pass in the weights vector and it will return an array of 0's containing a 1 indicating which bin was chosen. The code defaults to just making a single draw but you can pass in the number of draws to be made and the counts per bin drawn will be returned.

If the weights vector does not sum to 1, it will be normalized so that it does.

import numpy as np

def weighted_choice(weights, n=1):
    if np.sum(weights)!=1:
        weights = weights/np.sum(weights)

    draws = np.random.random_sample(size=n)

    weights = np.cumsum(weights)
    weights = np.insert(weights,0,0.0)

    counts = np.histogram(draws, bins=weights)
    return(counts[0])

Excel VBA Check if directory exists error

To check for the existence of a directory using Dir, you need to specify vbDirectory as the second argument, as in something like:

If Dir("C:\2013 Recieved Schedules" & "\" & client, vbDirectory) = "" Then

Note that, with vbDirectory, Dir will return a non-empty string if the specified path already exists as a directory or as a file (provided the file doesn't have any of the read-only, hidden, or system attributes). You could use GetAttr to be certain it's a directory and not a file.

How to simplify a null-safe compareTo() implementation?

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Comparator;

public class TestClass {

    public static void main(String[] args) {

        Student s1 = new Student("1","Nikhil");
        Student s2 = new Student("1","*");
        Student s3 = new Student("1",null);
        Student s11 = new Student("2","Nikhil");
        Student s12 = new Student("2","*");
        Student s13 = new Student("2",null);
        List<Student> list = new ArrayList<Student>();
        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s11);
        list.add(s12);
        list.add(s13);

        list.sort(Comparator.comparing(Student::getName,Comparator.nullsLast(Comparator.naturalOrder())));

        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            Student student = (Student) iterator.next();
            System.out.println(student);
        }


    }

}

output is

Student [name=*, id=1]
Student [name=*, id=2]
Student [name=Nikhil, id=1]
Student [name=Nikhil, id=2]
Student [name=null, id=1]
Student [name=null, id=2]

Where is my m2 folder on Mac OS X Mavericks

On the top of the screen you can find the Finder. Click Go -> Go to Folder -> search ~/.m2

If it is not found, as m2 is a hidden file you need to enable visibility by typing the following command in terminal:

defaults write com.apple.finder AppleShowAllFiles YES

How do you programmatically update query params in react-router?

Within the push method of hashHistory, you can specify your query parameters. For instance,

history.push({
  pathname: '/dresses',
  search: '?color=blue'
})

or

history.push('/dresses?color=blue')

You can check out this repository for additional examples on using history

Proper way to set response status and JSON content in a REST API made with nodejs and express

status of 200 will be the default when using res.send, res.json, etc.

You can set the status like res.status(500).json({ error: 'something is wrong' });

Often I'll do something like...

router.get('/something', function(req, res, next) {
  // Some stuff here
  if(err) {
    res.status(500);
    return next(err);
  }
  // More stuff here
});

Then have my error middleware send the response, and do anything else I need to do when there is an error.

Additionally: res.sendStatus(status) has been added as of version 4.9.0 http://expressjs.com/4x/api.html#res.sendStatus

Delete commit on gitlab

Supose you have the following scenario:

* 1bd2200 (HEAD, master) another commit
* d258546 bad commit
* 0f1efa9 3rd commit
* bd8aa13 2nd commit
* 34c4f95 1st commit

Where you want to remove d258546 i.e. "bad commit".

You shall try an interactive rebase to remove it: git rebase -i 34c4f95

then your default editor will pop with something like this:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick d258546 bad commit
 pick 1bd2200 another commit

 # Rebase 34c4f95..1bd2200 onto 34c4f95
 #
 # Commands:
 #  p, pick = use commit
 #  r, reword = use commit, but edit the commit message
 #  e, edit = use commit, but stop for amending
 #  s, squash = use commit, but meld into previous commit
 #  f, fixup = like "squash", but discard this commit's log message
 #  x, exec = run command (the rest of the line) using shell
 #
 # These lines can be re-ordered; they are executed from top to bottom.
 #
 # If you remove a line here THAT COMMIT WILL BE LOST.
 #
 # However, if you remove everything, the rebase will be aborted.
 #
 # Note that empty commits are commented out

just remove the line with the commit you want to strip and save+exit the editor:

 pick bd8aa13 2nd commit
 pick 0f1efa9 3rd commit
 pick 1bd2200 another commit
 ...

git will proceed to remove this commit from your history leaving something like this (mind the hash change in the commits descendant from the removed commit):

 * 34fa994 (HEAD, master) another commit
 * 0f1efa9 3rd commit
 * bd8aa13 2nd commit
 * 34c4f95 1st commit

Now, since I suppose that you already pushed the bad commit to gitlab, you'll need to repush your graph to the repository (but with the -f option to prevent it from being rejected due to a non fastforwardeable history i.e. git push -f <your remote> <your branch>)

Please be extra careful and make sure that none coworker is already using the history containing the "bad commit" in their branches.

Alternative option:

Instead of rewrite the history, you may simply create a new commit which negates the changes introduced by your bad commit, to do this just type git revert <your bad commit hash>. This option is maybe not as clean, but is far more safe (in case you are not fully aware of what are you doing with an interactive rebase).

Cannot use string offset as an array in php

I believe what are you asking about is a variable interpolation in PHP.

Let's do a simple fixture:

$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';

Now we have an object, where:

print_r($obj);

Will give output:

stdClass Object
    (
        [foo] => Array
            (
                [0] => bar
            )

        [property] => value
    )

And we have variable $var containing string "foo".

If you'll try to use:

$give_me_foo = $obj->$var[0];

Instead of:

$give_me_foo = $obj->foo[0];

You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0] to object $obj. And - as you can see from fixture - there is no content of $var[0] defined. Variable $var is a string and not an array.

What you can do in this case is to use curly braces, which will assure that at first is called content of $var, and subsequently the rest of message-sent:

$give_me_foo = $obj->{$var}[0];

The result is "bar", as you would expect.

Xcode 5 and iOS 7: Architecture and Valid architectures

Set the architecture in build setting to Standard architectures(armv7,armv7s)

enter image description here

iPhone 5S is powered by A7 64bit processor. From apple docs

Xcode can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 7 or later.

Note: A future version of Xcode will let you create a single app that supports the 32-bit runtime on iOS 6 and later, and that supports the 64-bit runtime on iOS 7.

From the documentation what i understood is

  • Xcode can create both 64bit 32bit binaries for a single app but the deployment target should be iOS7. They are saying in future it will be iOS 6.0
  • 32 bit binary will work fine in iPhone 5S(64 bit processor).

Update (Xcode 5.0.1)
In Xcode 5.0.1 they added the support to create 64 bit binary for iOS 5.1.1 onwards.

Xcode 5.0.1 can build your app with both 32-bit and 64-bit binaries included. This combined binary requires a minimum deployment target of iOS 5.1.1 or later. The 64-bit binary runs only on 64-bit devices running iOS 7.0.3 and later.

Update (Xcode 5.1)
Xcode 5.1 made significant change in the architecture section. This answer will be a followup for you. Check this

How do I calculate a point on a circle’s circumference?

Implemented in JavaScript (ES6):

/**
    * Calculate x and y in circle's circumference
    * @param {Object} input - The input parameters
    * @param {number} input.radius - The circle's radius
    * @param {number} input.angle - The angle in degrees
    * @param {number} input.cx - The circle's origin x
    * @param {number} input.cy - The circle's origin y
    * @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){

    angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
    const x = cx + radius * Math.sin(angle);
    const y = cy + radius * Math.cos(angle);
    return [ x, y ];

}

Usage:

const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );

Codepen

_x000D_
_x000D_
/**
 * Calculate x and y in circle's circumference
 * @param {Object} input - The input parameters
 * @param {number} input.radius - The circle's radius
 * @param {number} input.angle - The angle in degrees
 * @param {number} input.cx - The circle's origin x
 * @param {number} input.cy - The circle's origin y
 * @returns {Array[number,number]} The calculated x and y
 */
function pointsOnCircle({ radius, angle, cx, cy }){
  angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
  const x = cx + radius * Math.sin(angle);
  const y = cy + radius * Math.cos(angle);
  return [ x, y ];
}

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");

function draw( x, y ){

  ctx.clearRect( 0, 0, canvas.width, canvas.height );
  ctx.beginPath();
  ctx.strokeStyle = "orange";
  ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
  ctx.lineWidth = 3;
  ctx.stroke();
  ctx.closePath();

  ctx.beginPath();
  ctx.fillStyle = "indigo";
  ctx.arc( x, y, 6, 0, 2 * Math.PI);
  ctx.fill();
  ctx.closePath();
  
}

let angle = 0;  // In degrees
setInterval(function(){

  const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
  console.log( x, y );
  draw( x, y );
  document.querySelector("#degrees").innerHTML = angle + "&deg;";
  document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();

}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
_x000D_
_x000D_

How to convert hex to ASCII characters in the Linux shell?

echo -n 5a | perl -pe 's/([0-9a-f]{2})/chr hex $1/gie'

Note that this won't skip non-hex characters. If you want just the hex (no whitespace from the original string etc):

echo 5a | perl -ne 's/([0-9a-f]{2})/print chr hex $1/gie'

Also, zsh and bash support this natively in echo:

echo -e '\x5a'

Including one C source file in another?

Used properly, this can be a useful technique.

Say you have a complex, performance critical subsystem with a fairly small public interface and a lot of non-reusable implementation code. The code runs to several thousand lines, a hundred or so private functions and quite a bit of private data. If you work with non-trivial embedded systems, you probably deal with this situation frequently enough.

Your solution will probably be layered, modular and decoupled and these aspects can be usefully represented and reinforced by coding different parts of the subsystem in different files.

With C, you can lose a lot by doing this. Almost all toolchains provide decent optimisation for a single compilation unit, but are very pessimistic about anything declared extern.

If you put everything into one C source module, you get -

  • Performance & code size improvements - function calls will be inlined in many cases. Even without inlining, the compiler has opportunities to produce more efficient code.

  • Link level data & function hiding.

  • Avoidance of namespace pollution and its corollary - you can use less unwieldy names.

  • Faster compilation & linkage.

But you also get an unholy mess when it comes to editing this file and you lose the implied modularity. This can be overcome by splitting the source into several files and including these to produce a single compilation unit.

You need to impose some conventions to manage this properly though. These will depend on your toolchain to some extent, but some general pointers are -

  • Put the public interface in a separate header file - you should be doing this anyway.

  • Have one main .c file that includes all the subsidiary .c files. This could also include the code for the public interface.

  • Use compiler guards to ensure that private headers and source modules are not included by external compilation units.

  • All private data & functions should be declared static.

  • Maintain the conceptual distinction between .c and .h files. This leverages existing conventions. The difference is that you will have a lot of static declarations in your headers.

  • If your toolchain doesn't impose any reason not to, name the private implementation files as .c and .h. If you use include guards, these will produce no code and introduce no new names (you may end up with some empty segments during linkage). The huge advantage is that other tools (e.g. IDEs) will treat these files appropriately.

How to set dropdown arrow in spinner?

One simple way is to wrap your Spinner + Drop Down Arrow Image inside a Layout. Set the background of Spinner as transparent so that the default arrow icon gets hidden. Something like this:

 <LinearLayout

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/background"
        android:orientation="horizontal">

        <Spinner
            android:id="@+id/spinner"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="4"
            android:gravity="center"
            android:background="@android:color/transparent"
            android:spinnerMode="dropdown" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:onClick="showDropDown"
            android:src="@drawable/ic_chevron_down_blue" />

    </LinearLayout>

Here background.xml is a drawable to produce a box type background.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/transparent" />
    <corners android:radius="2dp" />
    <stroke
        android:width="1dp"
        android:color="#BDBDBD" />
</shape>

The above code produces this type of a Spinner and icon.

Spinner with a custom drop down arrow

How to select distinct query using symfony2 doctrine query builder?

If you use the "select()" statement, you can do this:

$category = $catrep->createQueryBuilder('cc')
    ->select('DISTINCT cc.contenttype')
    ->Where('cc.contenttype = :type')
    ->setParameter('type', 'blogarticle')
    ->getQuery();

$categories = $category->getResult();

installing JDK8 on Windows XP - advapi32.dll error

There is also an alternate solution for those who aren't afraid of using hex editors (e.g. XVI32) [thanks to Trevor for this]: in the unpacked 1 installer executable (jdk-8uXX-windows-i586.exe in case of JDK) simply replace all occurrences of RegDeleteKeyExA (the name of API found in "new" ADVAPI32.DLL) with RegDeleteKeyA (legacy API name), followed by two hex '00's (to preserve padding/segmentation boundaries). The installer will complain about unsupported Windows version, but will work nevertheless.

For reference, the raw hex strings will be:

52 65 67 44 65 6C 65 74 65 4B 65 79 45 78 41

replaced with

52 65 67 44 65 6C 65 74 65 4B 65 79 41 00 00

Note: this procedure applies to both offline (standalone) and online (downloader) package.

1: some newer installer versions are packed with UPX - you'd need to unpack them first, otherwise you simply won't be able to find the hex string required

hibernate - get id after save object

By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

Execute a command line binary with Node.js

Node JS v15.8.0, LTS v14.15.4, and v12.20.1 --- Feb 2021

Async method (Unix):

'use strict';

const { spawn } = require( 'child_process' );
const ls = spawn( 'ls', [ '-lh', '/usr' ] );

ls.stdout.on( 'data', ( data ) => {
    console.log( `stdout: ${ data }` );
} );

ls.stderr.on( 'data', ( data ) => {
    console.log( `stderr: ${ data }` );
} );

ls.on( 'close', ( code ) => {
    console.log( `child process exited with code ${ code }` );
} );

Async method (Windows):

'use strict';

const { spawn } = require( 'child_process' );
// NOTE: Windows Users, this command appears to be differ for a few users.
// You can think of this as using Node to execute things in your Command Prompt.
// If `cmd` works there, it should work here.
// If you have an issue, try `dir`:
// const dir = spawn( 'dir', [ '.' ] );
const dir = spawn( 'cmd', [ '/c', 'dir' ] );

dir.stdout.on( 'data', ( data ) => console.log( `stdout: ${ data }` ) );
dir.stderr.on( 'data', ( data ) => console.log( `stderr: ${ data }` ) );
dir.on( 'close', ( code ) => console.log( `child process exited with code ${code}` ) );

Sync:

'use strict';

const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );

console.log( `stderr: ${ ls.stderr.toString() }` );
console.log( `stdout: ${ ls.stdout.toString() }` );

From Node.js v15.8.0 Documentation

The same goes for Node.js v14.15.4 Documentation and Node.js v12.20.1 Documentation

IndexError: list index out of range and python

If you read a list from text file, you may get the last empty line as a list element. You can get rid of it like this:

list.pop()
for i in list:
   i[12]=....

No visible cause for "Unexpected token ILLEGAL"

I had this same problem and it occurred because I had hit the enter key when adding code in a text string.

Because it was a long string of text I wanted to see it all without having to scroll in my text editor, however hitting enter added an invisible character to the string which was illegal. I was using Sublime Text as my editor.

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

Renaming files using node.js

You'll need to use fs for that: http://nodejs.org/api/fs.html

And in particular the fs.rename() function:

var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
    if ( err ) console.log('ERROR: ' + err);
});

Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

(This assumes here that your .json file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)

Bootstrap - How to add a logo to navbar class?

I would suggest you to use either an image or text. So, Remove the text and add it in your image(using Photoshop, maybe). Then, Use a width and height 100% for the image. it will do the trick. because the image can be resized based on the container. But, you have to manually resize the text. If you can provide the fiddle, I can help you achieve this.

Line break (like <br>) using only css

You can use ::after to create a 0px-height block after the <h4>, which effectively moves anything after the <h4> to the next line:

_x000D_
_x000D_
h4 {_x000D_
  display: inline;_x000D_
}_x000D_
h4::after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
}
_x000D_
<ul>_x000D_
  <li>_x000D_
    Text, text, text, text, text. <h4>Sub header</h4>_x000D_
    Text, text, text, text, text._x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

Make sure you have a start page specified, as well. Right click on the .aspx page you want to use as your start page and choose "Set as start page"

In Python, is there an elegant way to print a list in a custom format without explicit looping?

Take a look on pprint, The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets or classes are included, as well as many other objects which are not representable as Python literals.

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']
>>> pp = pprint.PrettyPrinter(width=41, compact=True)
>>> pp.pprint(stuff)
[['spam', 'eggs', 'lumberjack',
  'knights', 'ni'],
 'spam', 'eggs', 'lumberjack', 'knights',
 'ni']
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> pp = pprint.PrettyPrinter(depth=6)
>>> pp.pprint(tup)
('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

video as site background? HTML 5

Take a look at my jquery videoBG plugin

http://syddev.com/jquery.videoBG/

Make any HTML5 video a site background... has an image fallback for browsers that don't support html5

Really easy to use

Let me know if you need any help.

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Failed to connect to camera service

I came up with the same problem and I'm sharing how I fixed it. It may help some people.

First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :

  1. Declare a permission in the app manifest. Make sure to insert the permission above the application tag.

**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**

<application ...>
    ...
</application>

  1. Then, request that the user approve each permission at runtime

      if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
        != PackageManager.PERMISSION_GRANTED) {
    // here, Permission is not granted
    ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
    }
    

For more information, have a look at the API documentation here

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Access a function variable outside the function without using "global"

I've experienced the same problem. One of the responds to your question led me to the following idea (which worked eventually). I use Python 3.7.

    # just an example 
    def func(): # define a function
       func.y = 4 # here y is a local variable, which I want to access; func.y defines 
                  # a method for my example function which will allow me to access 
                  # function's local variable y
       x = func.y + 8 # this is the main task for the function: what it should do
       return x

    func() # now I'm calling the function
    a = func.y # I put it's local variable into my new variable
    print(a) # and print my new variable

Then I launch this program in Windows PowerShell and get the answer 4. Conclusion: to be able to access a local function's variable one might add the name of the function and a dot before the name of the local variable (and then, of course, use this construction for calling the variable both in the function's body and outside of it). I hope this will help.

Java: Best way to iterate through a Collection (here ArrayList)

None of them are "better" than the others. The third is, to me, more readable, but to someone who doesn't use foreaches it might look odd (they might prefer the first). All 3 are pretty clear to anyone who understands Java, so pick whichever makes you feel better about the code.

The first one is the most basic, so it's the most universal pattern (works for arrays, all iterables that I can think of). That's the only difference I can think of. In more complicated cases (e.g. you need to have access to the current index, or you need to filter the list), the first and second cases might make more sense, respectively. For the simple case (iterable object, no special requirements), the third seems the cleanest.

How do I get into a non-password protected Java keystore or change the password?

Getting into a non-password protected Java keystore and changing the password can be done with a help of Java programming language itself.

That article contains the code for that:

thetechawesomeness.ideasmatter.info

Pylint "unresolved import" error in Visual Studio Code

Conda environment

pylint error: "Unable to import 'django.X'"

After activating the desired Python interpreter in your conda environment, VS Code will sometimes continue to use pylint from the default conda environment. For example:

/home/<username>/anaconda3/bin/pylint

1. Install pylint in your target conda environment

$ conda activate <target environment>
$ conda install pylint

2. Update VS Code Settings

  • In VS Code Settings, search for "pylint path"
  • Click the Workspace tab (instead of the default User)
  • Under "Extensions (##)", click "Python (#)"
  • Scroll down to Python > Linting: Pylint Path
  • Enter the pylint path pointing to the copy of pylint that was just installed, for example:

/home/<username>/anaconda3/envs/<target environment>/bin/pylint

Replace <username> and <target environment> according to your system configuration.

Now pylint will find the installed libraries, including Django, presuming that Django has been installed in <target environment>.

3. Install the Django pylint plugin

$ conda install pylint-django

Update the VS Code Settings to use the plugin:

  • Search VS Code settings for "pylint args"
  • Under Python > Linting: Pylint Args, click "Add Item"
  • Enter: --load-plugins=pylint_django
  • Click "OK"
  • Click "Add Item"
  • Enter: --django-settings-module=<PROJECT FOLDER>.settings
    • Replace <PROJECT FOLDER> with the folder containing the "settings.py" Django configuration file.
  • Click "OK"
  • Restart VS Code

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable. It uses the Trim function to remove both types of spaces and means before and after spaces of string.

SELECT LTRIM(RTRIM(REVERSE(' NEXT LEVEL EMPLOYEE ')))

Are multiple `.gitignore`s frowned on?

You can have multiple .gitignore, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore: git check-ignore -v -- afile.

And you can have different version of a .gitignore file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.

If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.


Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile in order to see which gitignore run (from which .gitignore file) is applied to 'yourfile', and better understand why said file is ignored.
See "which gitignore rule is ignoring my file?"

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

System.Net.WebException: The operation has timed out

proxy issue can cause this. IIS webconfig put this in

<defaultProxy useDefaultCredentials="true" enabled="true">
          <proxy usesystemdefault="True" />
        </defaultProxy>

How can I see the request headers made by curl when sending a request to the server?

Make a sample request to https://http-tools.appspot.com/reflect-http-request/some-unique-id and check what this request contains (request header, request body, request parameters) by its corresponding finder url https://http-tools.appspot.com/reflect-http-request-finder/some-unique-id. You can use any string instead of some-unique-id, check out https://http-tools.appspot.com for more details.

How to get method parameter names?

Here is another way to get the function parameters without using any module.

def get_parameters(func):
    keys = func.__code__.co_varnames[:func.__code__.co_argcount][::-1]
    sorter = {j: i for i, j in enumerate(keys[::-1])} 
    values = func.__defaults__[::-1]
    kwargs = {i: j for i, j in zip(keys, values)}
    sorted_args = tuple(
        sorted([i for i in keys if i not in kwargs], key=sorter.get)
    )
    sorted_kwargs = {
        i: kwargs[i] for i in sorted(kwargs.keys(), key=sorter.get)
    }   
    return sorted_args, sorted_kwargs


def f(a, b, c="hello", d="world"): var = a
    

print(get_parameters(f))

Output:

(('a', 'b'), {'c': 'hello', 'd': 'world'})

"date(): It is not safe to rely on the system's timezone settings..."

Add the following in your index.php file. I first came across this when I moved my application from my XAMPP server to Apache 2.2 and PHP 5.4...

I would advise you do it in your index.php file instead of the php.ini file.

if( ! ini_get('date.timezone') )
{
    date_default_timezone_set('GMT');
}

Can't run Curl command inside my Docker Container

You don't need to install curl to download the file into Docker container, use ADD command, e.g.

ADD https://raw.githubusercontent.com/Homebrew/install/master/install /tmp
RUN ruby -e /tmp/install

Note: Add above lines to your Dockerfile file.


Another example which installs Azure CLI:

ADD https://aka.ms/InstallAzureCLIDeb /tmp
RUN bash /tmp/InstallAzureCLIDeb

Font scaling based on width of container

Take look at my code. It makes the font size smaller to fit whatever there.

But I think this doesn't lead to a good user experience

var containerWidth = $("#ui-id-2").width();
var items = $(".quickSearchAutocomplete .ui-menu-item");
var fontSize = 16;

items.each(function(){
    // Displaying a value depends sometimes on your case. You may make it block or inline-table instead of inline-block or whatever value that make the div take overflow width.
    $(this).css({"whiteSpace": "nowrap", "display": "inline-block"});
    while ($(this).width() > containerWidth){
         console.log("$(this).width()" + $(this).width() + "containerWidth" + containerWidth)
         $(this).css("font-size", fontSize -= 0.5);
    }
});

Result

How to pass a parameter to routerLink that is somewhere inside the URL?

There are multiple ways of achieving this.

  • Through [routerLink] directive
  • The navigate(Array) method of the Router class
  • The navigateByUrl(string) method which takes a string and returns a promise

The routerLink attribute requires you to import the routingModule into the feature module in case you lazy loaded the feature module or just import the app-routing-module if it is not automatically added to the AppModule imports array.

  • RouterLink
<a [routerLink]="['/user', user.id]">John Doe</a>
<a routerLink="urlString">John Doe</a> // urlString is computed in your component
  • Navigate
// Inject Router into your component
// Inject ActivatedRoute into your component. This will allow the route to be done related to the current url
this._router.navigate(['user',user.id], {relativeTo: this._activatedRoute})
  • NavigateByUrl
this._router.navigateByUrl(urlString).then((bool) => {}).catch()

How to retrieve the LoaderException property?

Another Alternative for those who are probing around and/or in interactive mode:

$Error[0].Exception.LoaderExceptions

Note: [0] grabs the most recent Error from the stack

How can I implement rate limiting with Apache? (requests per second)

Depends on why you want to rate limit.

If it's to protect against overloading the server, it actually makes sense to put NGINX in front of it, and configure rate limiting there. It makes sense because NGINX uses much less resources, something like a few MB per ten thousand connections. So, if the server is flooded, NGINX will do the rate limiting(using an insignificant amount of resources) and only pass the allowed traffic to Apache.

If all you're after is simplicity, then use something like mod_evasive.

As usual, if it's to protect against DDoS or DoS attacks, use a service like Cloudflare which also has rate limiting.

Where is Ubuntu storing installed programs?

They are usually stored in the following folders:

/bin/
/usr/bin/
/sbin/
/usr/sbin/

If you're not sure, use the which command:

~$ which firefox
/usr/bin/firefox

Correct way to push into state array

Using react hooks, you can do following way

const [countryList, setCountries] = useState([]);


setCountries((countryList) => [
        ...countryList,
        "India",
      ]);

How does the stack work in assembly language?

The call stack is implemented by the x86 instruction set and the operating system.

Instructions like push and pop adjust the stack pointer while the operating system takes care of allocating memory as the stack grows for each thread.

The fact that the x86 stack "grows down" from higher to lower addresses make this architecture more susceptible to the buffer overflow attack.

How to free memory in Java?

I have done experimentation on this.

It's true that System.gc(); only suggests to run the Garbage Collector.

But calling System.gc(); after setting all references to null, will improve performance and memory occupation.

How to link html pages in same or different folders?

If you'd like to link to the root directory you can use

/, or /index.html

If you'd like to link to a file in the same directory, simply put the file name

<a href="/employees.html">Employees Click Here</a>

To move back a folder, you can use

../

To link to the index page in the employees directory from the root directory, you'd do this

<a href="../employees/index.html">Employees Directory Index Page</a>

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Thanks for the original answer here. With python 3 the following line of code:

print(json.dumps(result_dict,ensure_ascii=False))

was ok. Consider trying not writing too much text in the code if it's not imperative.

This might be good enough for the python console. However, to satisfy a server you might need to set the locale as explained here (if it is on apache2) http://blog.dscpl.com.au/2014/09/setting-lang-and-lcall-when-using.html

basically install he_IL or whatever language locale on ubuntu check it is not installed

locale -a 

install it where XX is your language

sudo apt-get install language-pack-XX

For example:

sudo apt-get install language-pack-he

add the following text to /etc/apache2/envvrs

export LANG='he_IL.UTF-8'
export LC_ALL='he_IL.UTF-8'

Than you would hopefully not get python errors on from apache like:

print (js) UnicodeEncodeError: 'ascii' codec can't encode characters in position 41-45: ordinal not in range(128)

Also in apache try to make utf the default encoding as explained here:
How to change the default encoding to UTF-8 for Apache?

Do it early because apache errors can be pain to debug and you can mistakenly think it's from python which possibly isn't the case in that situation

What is the correct wget command syntax for HTTPS with username and password?

It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).

I followed the link suggested by @thomasbabuj and figured it out eventually.

You should try adding --auth-no-challenge and as @thomasbabuj suggested replace your password entry

I.e

wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip

Converting an int to std::string

You can use std::to_string in C++11

int i = 3;
std::string str = std::to_string(i);

Regular expression to match numbers with or without commas and decimals in text

\b\d+,

\b------->word boundary

\d+------>one or digit

,-------->containing commas,

Eg:

sddsgg 70,000 sdsfdsf fdgfdg70,00

sfsfsd 5,44,4343 5.7788,44 555

It will match:

70,

5,

44,

,44

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

example:

c++ -Wall filefork.cpp -lrt -O2

For gcc version 4.6.1, -lrt must be after filefork.cpp otherwise you get a link error.

Some older gcc version doesn't care about the position.

Disable a link in Bootstrap

I just created my own version using CSS. As I need to disabled, then when document is ready use jQuery to make active. So that way a user cannot click on a button until after the document is ready. So i can substitute with AJAX instead. The way I came up with, was to add a class to the anchor tag itself and remove the class when document is ready. Could re-purpose this for your needs.

CSS:

a.disabled{
    pointer-events: none;
    cursor: default;
}

HTML:

<a class="btn btn-info disabled">Link Text</a>

JS:

$(function(){
    $('a.disabled').on('click',function(event){
        event.preventDefault();
    }).removeClass('disabled');
});

How do I test a single file using Jest?

Simple solution that works:

yarn test -g fileName or

npm test -g fileName

Example:

yarn test -g cancelTransaction or

npm test -g cancelTransaction

More about test filters:

Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]

Rails: How can I rename a database column in a Ruby on Rails migration?

Run the below command to create a migration file:

rails g migration ChangeHasedPasswordToHashedPassword

Then in the file generated in the db/migrate folder, write rename_column as below:

class ChangeOldCoulmnToNewColumn < ActiveRecord::Migration
  def change
     rename_column :table_name, :hased_password, :hashed_password
  end
end

LaTeX Optional Arguments

I had a similar problem, when I wanted to create a command, \dx, to abbreviate \;\mathrm{d}x (i.e. put an extra space before the differential of the integral and have the "d" upright as well). But then I also wanted to make it flexible enough to include the variable of integration as an optional argument. I put the following code in the preamble.

\usepackage{ifthen}

\newcommand{\dx}[1][]{%
   \ifthenelse{ \equal{#1}{} }
      {\ensuremath{\;\mathrm{d}x}}
      {\ensuremath{\;\mathrm{d}#1}}
}

Then

\begin{document}
   $$\int x\dx$$
   $$\int t\dx[t]$$
\end{document}

gives \dx with optional argument

How to find EOF through fscanf?

If you have integers in your file fscanf returns 1 until integer occurs. For example:

FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;

for ( int i = 0; i < 10; i++ ) {
    counter = fscanf(in, "%d", &sequence);
    if ( counter == 1 ) {
        length += 1;
    }
}

To find out the end of the file with symbols you can use EOF. For example:

char symbol;
FILE *in = fopen("./task.in", "r");

for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
    printf("%c", symbol); 
}

Case insensitive comparison of strings in shell script

For zsh the syntax is slightly different, but still shorter than most answers here:

> str1='mAtCh'
> str2='MaTcH'
> [[ "$str1:u" = "$str2:u" ]] && echo 'Strings Match!'
Strings Match!
>

This will convert both strings to uppercase before the comparison.


Another method makes use zsh's globbing flags, which allows us to directly make use of case-insensitive matching by using the i glob flag:

setopt extendedglob
[[ $str1 = (#i)$str2 ]] && echo "Match success"
[[ $str1 = (#i)match ]] && echo "Match success"

Convert base class to derived class

I have found one solution to this, not saying it's the best one, but it feels clean to me and doesn't require any major changes to my code. My code looked similar to yours until I realized it didn't work.

My Base Class

public class MyBaseClass
{
   public string BaseProperty1 { get; set; }
   public string BaseProperty2 { get; set; }
   public string BaseProperty3 { get; set; }
   public string BaseProperty4 { get; set; }
   public string BaseProperty5 { get; set; }
}

My Derived Class

public class MyDerivedClass : MyBaseClass
{
   public string DerivedProperty1 { get; set; }
   public string DerivedProperty2 { get; set; }
   public string DerivedProperty3 { get; set; }
}

Previous method to get a populated base class

public MyBaseClass GetPopulatedBaseClass()
{
   var myBaseClass = new MyBaseClass();

   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...

   return myBaseClass;
}

Before I was trying this, which gave me a unable to cast error

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

I changed my code as follows bellow and it seems to work and makes more sense now:

Old

public MyBaseClass GetPopulatedBaseClass()
{
   var myBaseClass = new MyBaseClass();

   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...

   return myBaseClass;
}

New

public void FillBaseClass(MyBaseClass myBaseClass)
{
   myBaseClass.BaseProperty1 = "Something"
   myBaseClass.BaseProperty2 = "Something else"
   myBaseClass.BaseProperty3 = "Something more"
   //etc...
}

Old

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = (MyDerivedClass)GetPopulatedBaseClass();

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

New

public MyDerivedClass GetPopulatedDerivedClass()
{
   var newDerivedClass = new MyDerivedClass();

   FillBaseClass(newDerivedClass);

   newDerivedClass.UniqueProperty1 = "Some One";
   newDerivedClass.UniqueProperty2 = "Some Thing";
   newDerivedClass.UniqueProperty3 = "Some Thing Else";

   return newDerivedClass;
}

onCreateOptionsMenu inside Fragments

Call

setSupportActionBar(toolbar)

inside

onViewCreated(...) 

of Fragment

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
    ((MainActivity)getActivity()).setSupportActionBar(toolbar);
    setHasOptionsMenu(true);
}

The remote server returned an error: (403) Forbidden

This probably won't help too many people, but this was my case: I was using the Jira Rest Api and was using my personal credentials (the ones I use to log into Jira). I had updated my Jira password but forgot to update them in my code. I got the 403 error, I tried updating my password in the code but still got the error.

The solution: I tried logging into Jira (from their login page) and I had to enter the text to prove I wasn't a bot. After that I tried again from the code and it worked. Takeaway: The server may have locked you out.

How can I read a large text file line by line using Java?

Java 9:

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
}

Pandas: Subtracting two date columns and the result being an integer

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

How to remove empty lines with or without whitespace in Python

If you are not willing to try regex (which you should), you can use this:

s.replace('\n\n','\n')

Repeat this several times to make sure there is no blank line left. Or chaining the commands:

s.replace('\n\n','\n').replace('\n\n','\n')


Just to encourage you to use regex, here are two introductory videos that I find intuitive:
Regular Expressions (Regex) Tutorial
Python Tutorial: re Module

Is there a vr (vertical rule) in html?

You can very easily do this by

_x000D_
_x000D_
hr{_x000D_
 transform: rotate(90deg);_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<hr>_x000D_
</body> _x000D_
</html>
_x000D_
_x000D_
_x000D_ Be careful about the height and width of hr

Prevent screen rotation on Android

Activity.java

@Override     
 public void onConfigurationChanged(Configuration newConfig) {       
        try {     
            super.onConfigurationChanged(newConfig);      
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {      
                // land      
            } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {      
               // port       
            }    
        } catch (Exception ex) {       
     }   

AndroidManifest.xml

 <application android:icon="@drawable/icon" android:label="@string/app_name">
  <activity android:name="QRCodeActivity" android:label="@string/app_name"
  android:screenOrientation="landscape" >
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>

Spring Boot application.properties value not populating

Using Environment class we can get application. Properties values

@Autowired,

private Environment env;

and access using

String password =env.getProperty(your property key);

Create a simple 10 second countdown

_x000D_
_x000D_
var seconds_inputs =  document.getElementsByClassName('deal_left_seconds');
    var total_timers = seconds_inputs.length;
    for ( var i = 0; i < total_timers; i++){
        var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';
        var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');
        var cal_seconds = seconds_inputs[i].getAttribute('value');

        eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');
        eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');
    }
    function timer() {
        for ( var i = 0; i < total_timers; i++) {
            var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');

            var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);
            var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));
            var hours = Math.floor(hoursLeft / 3600);
            var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
            var minutes = Math.floor(minutesLeft / 60);
            var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;

            function pad(n) {
                return (n < 10 ? "0" + n : n);
            }
            document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);
            document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);
            document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);
            document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);

            if (eval('seconds_'+ seconds_prod_id) == 0) {
                clearInterval(countdownTimer);
                document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);
            } else {
                var value = eval('seconds_'+seconds_prod_id);
                value--;
                eval('seconds_' + seconds_prod_id + '= ' + value + ';');
            }
        }
    }

    var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">
<div class="box-wrapper">
    <div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>
</div>
<div class="box-wrapper">
    <div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>
</div>
<div class="box-wrapper">
    <div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>
</div>
<div class="box-wrapper hidden-md">
    <div class="seconds box"> <span class="key" id="deal_sec_1">0p0</span> <span class="value">SEC</span> </div>
</div>
_x000D_
_x000D_
_x000D_

Concatenate chars to form String in java

Try this:

 str = String.valueOf(a)+String.valueOf(b)+String.valueOf(c);

Output:

ice

How to check if a variable is set in Bash?

if [[ ${1:+isset} ]]
then echo "It was set and not null." >&2
else echo "It was not set or it was null." >&2
fi

if [[ ${1+isset} ]]
then echo "It was set but might be null." >&2
else echo "It was was not set." >&2
fi

Returning data from Axios API

The axios library creates a Promise() object. Promise is a built-in object in JavaScript ES6. When this object is instantiated using the new keyword, it takes a function as an argument. This single function in turn takes two arguments, each of which are also functions — resolve and reject.

Promises execute the client side code and, due to cool Javascript asynchronous flow, could eventually resolve one or two things, that resolution (generally considered to be a semantically equivalent to a Promise's success), or that rejection (widely considered to be an erroneous resolution). For instance, we can hold a reference to some Promise object which comprises a function that will eventually return a response object (that would be contained in the Promise object). So one way we could use such a promise is wait for the promise to resolve to some kind of response.

You might raise we don't want to be waiting seconds or so for our API to return a call! We want our UI to be able to do things while waiting for the API response. Failing that we would have a very slow user interface. So how do we handle this problem?

Well a Promise is asynchronous. In a standard implementation of engines responsible for executing Javascript code (such as Node, or the common browser) it will resolve in another process while we don't know in advance what the result of the promise will be. A usual strategy is to then send our functions (i.e. a React setState function for a class) to the promise, resolved depending on some kind of condition (dependent on our choice of library). This will result in our local Javascript objects being updated based on promise resolution. So instead of getters and setters (in traditional OOP) you can think of functions that you might send to your asynchronous methods.

I'll use Fetch in this example so you can try to understand what's going on in the promise and see if you can replicate my ideas within your axios code. Fetch is basically similar to axios without the innate JSON conversion, and has a different flow for resolving promises (which you should refer to the axios documentation to learn).

GetCache.js

const base_endpoint = BaseEndpoint + "cache/";
// Default function is going to take a selection, date, and a callback to execute.
// We're going to call the base endpoint and selection string passed to the original function.
// This will make our endpoint.
export default (selection, date, callback) => {  
  fetch(base_endpoint + selection + "/" + date) 
     // If the response is not within a 500 (according to Fetch docs) our promise object
     // will _eventually_ resolve to a response. 
    .then(res => {
      // Lets check the status of the response to make sure it's good.
      if (res.status >= 400 && res.status < 600) {
        throw new Error("Bad response");
      }
      // Let's also check the headers to make sure that the server "reckons" its serving 
      //up json
      if (!res.headers.get("content-type").includes("application/json")) {
        throw new TypeError("Response not JSON");
      }
      return res.json();
    })
    // Fulfilling these conditions lets return the data. But how do we get it out of the promise? 
    .then(data => {
      // Using the function we passed to our original function silly! Since we've error 
      // handled above, we're ready to pass the response data as a callback.
      callback(data);
    })
    // Fetch's promise will throw an error by default if the webserver returns a 500 
    // response (as notified by the response code in the HTTP header). 
    .catch(err => console.error(err));
};

Now we've written our GetCache method, lets see what it looks like to update a React component's state as an example...

Some React Component.jsx

// Make sure you import GetCache from GetCache.js!

resolveData() {
    const { mySelection, date } = this.state; // We could also use props or pass to the function to acquire our selection and date.
    const setData = data => {
      this.setState({
        data: data,
        loading: false 
        // We could set loading to true and display a wee spinner 
        // while waiting for our response data, 
        // or rely on the local state of data being null.
      });
    };
  GetCache("mySelelection", date, setData);
  }

Ultimately, you don't "return" data as such, I mean you can but it's more idiomatic to change your way of thinking... Now we are sending data to asynchronous methods.

Happy Coding!

How to measure elapsed time in Python?

on python3:

from time import sleep, perf_counter as pc
t0 = pc()
sleep(1)
print(pc()-t0)

elegant and short.

Deciding between HttpClient and WebClient

HttpClientFactory

It's important to evaluate the different ways you can create an HttpClient, and part of that is understanding HttpClientFactory.

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

This is not a direct answer I know - but you're better off starting here than ending up with new HttpClient(...) everywhere.

How to loop through key/value object in Javascript?

Beware of properties inherited from the object's prototype (which could happen if you're including any libraries on your page, such as older versions of Prototype). You can check for this by using the object's hasOwnProperty() method. This is generally a good idea when using for...in loops:

var user = {};

function setUsers(data) {
    for (var k in data) {
        if (data.hasOwnProperty(k)) {
           user[k] = data[k];
        }
    }
}

How to change the ROOT application?

In Tomcat 7 (under Windows server) I didn't add or edit anything to any configuration file. I just renamed the ROOT folder to something else and renamed my application folder to ROOT and it worked fine.

How to fix SSL certificate error when running Npm on Windows?

This problem was fixed for me by using http version of repository:

npm config set registry http://registry.npmjs.org/

Git checkout: updating paths is incompatible with switching branches

For me I had a typo and my remote branch didn't exist

Use git branch -a to list remote branches

Initialising mock objects - MockIto

MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:

XXX mockedXxx = mock(XXX.class);

I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.

Changing default startup directory for command prompt in Windows 7

Make a shortcut pointing to cmd.exe somwhere (e.g. desktop) then right-click on the copy and select "properties". Navigate to the "Shortcut" menu and change the "Start in:" directory.

Convert a python UTC datetime to a local datetime using only python standard library?

You can't do it with only the standard library as the standard library doesn't have any timezones. You need pytz or dateutil.

>>> from datetime import datetime
>>> now = datetime.utcnow()
>>> from dateutil import tz
>>> HERE = tz.tzlocal()
>>> UTC = tz.gettz('UTC')

The Conversion:
>>> gmt = now.replace(tzinfo=UTC)
>>> gmt.astimezone(HERE)
datetime.datetime(2010, 12, 30, 15, 51, 22, 114668, tzinfo=tzlocal())

Or well, you can do it without pytz or dateutil by implementing your own timezones. But that would be silly.

List of zeros in python

$python 2.7.8

from timeit import timeit
import numpy

timeit("list(0 for i in xrange(0, 100000))", number=1000)
> 8.173301935195923

timeit("[0 for i in xrange(0, 100000)]", number=1000)
> 4.881675958633423

timeit("[0] * 100000", number=1000)
> 0.6624710559844971

timeit('list(itertools.repeat(0, 100000))', 'import itertools', number=1000)
> 1.0820629596710205

You should use [0] * n to generate a list with n zeros.

See why [] is faster than list()

There is a gotcha though, both itertools.repeat and [0] * n will create lists whose elements refer to same id. This is not a problem with immutable objects like integers or strings but if you try to create list of mutable objects like a list of lists ([[]] * n) then all the elements will refer to the same object.

a = [[]] * 10
a[0].append(1)
a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

[0] * n will create the list immediately while repeat can be used to create the list lazily when it is first accessed.

If you're dealing with really large amount of data and your problem doesn't need variable length of list or multiple data types within the list it is better to use numpy arrays.

timeit('numpy.zeros(100000, numpy.int)', 'import numpy', number=1000)
> 0.057849884033203125

numpy arrays will also consume less memory.

Should I use PATCH or PUT in my REST API?

One possible option to implement such behavior is

PUT /groups/api/v1/groups/{group id}/status
{
    "Status":"Activated"
}

And obviously, if someone need to deactivate it, PUT will have Deactivated status in JSON.

In case of necessity of mass activation/deactivation, PATCH can step into the game (not for exact group, but for groups resource:

PATCH /groups/api/v1/groups
{
    { “op”: “replace”, “path”: “/group1/status”, “value”: “Activated” },
    { “op”: “replace”, “path”: “/group7/status”, “value”: “Activated” },
    { “op”: “replace”, “path”: “/group9/status”, “value”: “Deactivated” }
}

In general this is idea as @Andrew Dobrowolski suggesting, but with slight changes in exact realization.

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

How to pass a parameter like title, summary and image in a Facebook sharer URL

Looks like Facebook disabled passing parameters to the sharer.

We have changed the behavior of the sharer plugin to be consistent with other plugins and features on our platform.

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Here's the URL to the post: https://developers.facebook.com/x/bugs/357750474364812/

Why can't I use a list as a dict key in python?

According to the Python 2.7.2 documentation:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a hash() method), and can be compared to other objects (it needs an eq() or cmp() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

A tuple is immutable in the sense that you cannot add, remove or replace its elements, but the elements themselves may be mutable. List's hash value depends on the hash values of its elements, and so it changes when you change the elements.

Using id's for list hashes would imply that all lists compare differently, which would be surprising and inconvenient.

Remove "whitespace" between div element

Although probably not the best method you could add:

#div1 {
    ...
    font-size:0;
}

ProcessStartInfo hanging on "WaitForExit"? Why?

The problem with unhandled ObjectDisposedException happens when the process is timed out. In such case the other parts of the condition:

if (process.WaitForExit(timeout) 
    && outputWaitHandle.WaitOne(timeout) 
    && errorWaitHandle.WaitOne(timeout))

are not executed. I resolved this problem in a following way:

using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
    using (Process process = new Process())
    {
        // preparing ProcessStartInfo

        try
        {
            process.OutputDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                    }
                    else
                    {
                        outputBuilder.AppendLine(e.Data);
                    }
                };
            process.ErrorDataReceived += (sender, e) =>
                {
                    if (e.Data == null)
                    {
                        errorWaitHandle.Set();
                    }
                    else
                    {
                        errorBuilder.AppendLine(e.Data);
                    }
                };

            process.Start();

            process.BeginOutputReadLine();
            process.BeginErrorReadLine();

            if (process.WaitForExit(timeout))
            {
                exitCode = process.ExitCode;
            }
            else
            {
                // timed out
            }

            output = outputBuilder.ToString();
        }
        finally
        {
            outputWaitHandle.WaitOne(timeout);
            errorWaitHandle.WaitOne(timeout);
        }
    }
}

How to sort a dataframe by multiple column(s)

Dirk's answer is good but if you need the sort to persist you'll want to apply the sort back onto the name of that data frame. Using the example code:

dd <- dd[with(dd, order(-z, b)), ] 

How do you add a JToken to an JObject?

Just adding .First to your bananaToken should do it:
foodJsonObj["food"]["fruit"]["orange"].Parent.AddAfterSelf(bananaToken .First);
.First basically moves past the { to make it a JProperty instead of a JToken.

@Brian Rogers, Thanks I forgot the .Parent. Edited

Set "Homepage" in Asp.Net MVC

Look at the Default.aspx/Default.aspx.cs and the Global.asax.cs

You can set up a default route:

        routes.MapRoute(
            "Default", // Route name
            "",        // URL with parameters
            new { controller = "Home", action = "Index"}  // Parameter defaults
        );

Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table.

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

An easy fix to this would be going to the SQL tab and just simply put in the code

ALTER TABLE `tablename`
ADD PRIMARY KEY (`id`);

Asuming that you have a row named id.

How to automatically generate getters and setters in Android Studio

Just in case someone is working with Eclipse

Windows 8.1 OS | Eclipse Idle Luna

Declare top level variable private String username Eclipse kindly generate a warning on the left of your screen click that warning and couple of suggestions show up, then select generate.enter image description here

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

You could compile and link in one command:

gcc file1.c file2.c -o myprogram

And run with:

./myprogram

But to answer the question as asked, simply pass the object files to gcc:

gcc file1.o file2.o -o myprogram

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

Best check for this problem : (If you are behind proxy),(tested on ubuntu 18.04), (will work on other ubuntu also),(mostly error in : https_proxy="http://192.168.0.251:808/)

  1. Check these files:

    #sudo cat /etc/environment :
    http_proxy="http://192.168.0.251:808/"
    https_proxy="http://192.168.0.251:808/"
    ftp_proxy="ftp://192.168.0.251:808/"
    socks_proxy="socks://192.168.0.251:808/"
    #sudo cat /etc/apt/apt.conf :
    Acquire::http::proxy "http://192.168.0.251:808/";
    Acquire::https::proxy "http://192.168.0.251:808/";
    Acquire::ftp::proxy "ftp://192.168.0.251:808/";
    Acquire::socks::proxy "socks://192.168.0.251:808/";
    
  2. Add docker stable repo

    #sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" 
    
  3. Run apt-get update:

    #sudo apt-get update
    
  4. Check Docker CE

    #apt-cache policy docker-ce
    
  5. install Docker

    #sudo apt-get install docker-ce
    

Parse JSON String into a Particular Object Prototype in JavaScript

See an example below (this example uses the native JSON object). My changes are commented in CAPITALS:

function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
    this.a = 3;
    this.b = 2;
    this.test = function() {return this.a*this.b;};

    // IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
    for (var prop in obj) this[prop] = obj[prop];
}

var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6

// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));

alert(fooJSON.test() ); //Prints 12

Call js-function using JQuery timer

Might want to check out jQuery Timer to manage one or multiple timers.

http://code.google.com/p/jquery-timer/

var timer = $.timer(yourfunction, 10000);

function yourfunction() { alert('test'); }

Then you can control it with:

timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...

Can typescript export a function?

To answer the title of your question directly because this comes up in Google first:

YES, TypeScript can export a function!

Here is a direct quote from the TS Documentation:

"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

Reference Link

How to programmatically disable page scrolling with jQuery

I put an answer that might help here: jQuery simplemodal disable scrolling

It shows how to turn off the scroll bars without shifting the text around. You can ignore the parts about simplemodal.

How do you use global variables or constant values in Ruby?

Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $ are global, variables with @ are instance variables, @@ means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.

I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:

  1. Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo and create a constant Offset, so then all the classes could access Foo::Offset.

  2. Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.

Pushing an existing Git repository to SVN

If you don't have to use any specific SVN and you are using GitHub you can use their SVN connector.

More information is here: Collaborating on GitHub with Subversion

How to grep and replace

Other solutions mix regex syntaxes. To use perl/PCRE patterns for both search and replace, and only process matching files, this works quite well:

grep -rlIZPi 'match1' | xargs -0r perl -pi -e 's/match2/replace/gi;'

match1 and match2 are usually identical but match1 can be simplified to remove more advanced features that are only relevant to the substitution, e.g. capturing groups.

Translation: grep recursively and list matching filenames, each separated by nul to protect any special characters; pipe any filenames to xargs which is expecting a nul-separated list; if any filenames are received, pass them to perl to perform the actual substitutions.

For case-sensitive matching, drop the i flag from grep and the i pattern modifier from the s/// expression, but not the i flag from perl itself. Remove the I flag from grep to include binary files.

How to format a QString?

You can use QString.arg like this

QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"

This method is preferred over sprintf because:

Changing the position of the string without having to change the ordering of substitution, e.g.

// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");

Or, changing the type of the arguments doesn't require changing the format string, e.g.

// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));

As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.

One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.

UPDATE: Examples are updated thanks to Frank Osterfeld.

UPDATE: Examples are updated thanks to alexisdm.

How to implement class constants?

Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("my.config");

export interface MyAppConfig {
    apiEndpoint: string;
}

export const AppConfig: MyAppConfig = {    
    apiEndpoint: "http://localhost:8080/api/"    
};

Inject it in providers in app.module.ts

You will be able to use it across every components.

EDIT for Angular 4 :

For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.

Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject

Example Code

Angular 2 Using Opaque Tokens

const API_URL = new OpaqueToken('apiUrl'); //no Type Check


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      new Inject(API_URL) //notice the new Inject
    ]
  }
]

Angular 4 Using Injection Tokens

const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      API_URL // no `new Inject()` needed!
    ]
  }
]

Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.

How to set focus on input field?

Just throwing in some coffee.

app.directive 'ngAltFocus', ->
    restrict: 'A'
    scope: ngAltFocus: '='
    link: (scope, el, attrs) ->
        scope.$watch 'ngAltFocus', (nv) -> el[0].focus() if nv

How to load specific image from assets with Swift

You can easily pick image from asset without UIImage(named: "green-square-Retina").

Instead use the image object directly from bundle.
Start typing the image name and you will get suggestions with actual image from bundle. It is advisable practice and less prone to error.

See this Stackoverflow answer for reference.

Check if a variable is null in plsql

Another way:

var := coalesce (var, 5);

COALESCE is the ANSI equivalent (more or less) of Oracle's NVL function.

What does [object Object] mean? (JavaScript)

If you are popping it in the DOM then try wrapping it in

<pre>
    <code>{JSON.stringify(REPLACE_WITH_OBJECT, null, 4)}</code>
</pre>

makes a little easier to visually parse.

How can I align the columns of tables in Bash?

function printTable()
{
    local -r delimiter="${1}"
    local -r data="$(removeEmptyLines "${2}")"

    if [[ "${delimiter}" != '' && "$(isEmptyString "${data}")" = 'false' ]]
    then
        local -r numberOfLines="$(wc -l <<< "${data}")"

        if [[ "${numberOfLines}" -gt '0' ]]
        then
            local table=''
            local i=1

            for ((i = 1; i <= "${numberOfLines}"; i = i + 1))
            do
                local line=''
                line="$(sed "${i}q;d" <<< "${data}")"

                local numberOfColumns='0'
                numberOfColumns="$(awk -F "${delimiter}" '{print NF}' <<< "${line}")"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi

                # Add Header Or Body

                table="${table}\n"

                local j=1

                for ((j = 1; j <= "${numberOfColumns}"; j = j + 1))
                do
                    table="${table}$(printf '#| %s' "$(cut -d "${delimiter}" -f "${j}" <<< "${line}")")"
                done

                table="${table}#|\n"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]] || [[ "${numberOfLines}" -gt '1' && "${i}" -eq "${numberOfLines}" ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi
            done

            if [[ "$(isEmptyString "${table}")" = 'false' ]]
            then
                echo -e "${table}" | column -s '#' -t | awk '/^\+/{gsub(" ", "-", $0)}1'
            fi
        fi
    fi
}

function removeEmptyLines()
{
    local -r content="${1}"

    echo -e "${content}" | sed '/^\s*$/d'
}

function repeatString()
{
    local -r string="${1}"
    local -r numberToRepeat="${2}"

    if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
    then
        local -r result="$(printf "%${numberToRepeat}s")"
        echo -e "${result// /${string}}"
    fi
}

function isEmptyString()
{
    local -r string="${1}"

    if [[ "$(trimString "${string}")" = '' ]]
    then
        echo 'true' && return 0
    fi

    echo 'false' && return 1
}

function trimString()
{
    local -r string="${1}"

    sed 's,^[[:blank:]]*,,' <<< "${string}" | sed 's,[[:blank:]]*$,,'
}

SAMPLE RUNS

$ cat data-1.txt
HEADER 1,HEADER 2,HEADER 3

$ printTable ',' "$(cat data-1.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+

$ cat data-2.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3

$ printTable ',' "$(cat data-2.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
+-----------+-----------+-----------+

$ cat data-3.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3
data 4,data 5,data 6

$ printTable ',' "$(cat data-3.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
| data 4    | data 5    | data 6    |
+-----------+-----------+-----------+

$ cat data-4.txt
HEADER
data

$ printTable ',' "$(cat data-4.txt)"
+---------+
| HEADER  |
+---------+
| data    |
+---------+

$ cat data-5.txt
HEADER

data 1

data 2

$ printTable ',' "$(cat data-5.txt)"
+---------+
| HEADER  |
+---------+
| data 1  |
| data 2  |
+---------+

REF LIB at: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash

how do I get eclipse to use a different compiler version for Java?

Just to clarify, do you have JAVA_HOME set as a system variable or set in Eclipse classpath variables? I'm pretty sure (but not totally sure!) that the system variable is used by the command line compiler (and Ant), but that Eclipse modifies this accroding to the JDK used

How do I use Ruby for shell scripting?

Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.

So, if you had a script called my_shell_script:

#!/usr/bin/env ruby
puts "I was passed: "
ARGV.each do |value|
  puts value
end

...make it executable (as others have mentioned):

chmod u+x my_shell_script

And call it like so:

> ./my_shell_script one two three four five

You'd get this:

I was passed: 
one
two
three
four
five

The arguments work nicely with filename expansion:

./my_shell_script *

I was passed: 
a_file_in_the_current_directory
another_file    
my_shell_script
the_last_file

Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.

Warn user before leaving web page with unsaved changes

The solution by Eerik Sven Puudist ...

var isSubmitting = false;

$(document).ready(function () {
    $('form').submit(function(){
        isSubmitting = true
    })

    $('form').data('initial-state', $('form').serialize());

    $(window).on('beforeunload', function() {
        if (!isSubmitting && $('form').serialize() != $('form').data('initial-state')){
            return 'You have unsaved changes which will not be saved.'
        }
    });
})

... spontaneously did the job for me in a complex object-oriented setting without any changes necessary.

The only change I applied was to refer to the concrete form (only one form per file) called "formForm" ('form' -> '#formForm'):

<form ... id="formForm" name="formForm" ...>

Especially well done is the fact that the submit button is being "left alone".

Additionally, it works for me also with the lastest version of Firefox (as of February 7th, 2019).

Less than or equal to

You can use:

EQU - equal

NEQ - not equal

LSS - less than

LEQ - less than or equal

GTR - greater than

GEQ - greater than or equal

AVOID USING:

() ! ~ - * / % + - << >> & | = *= /= %= += -= &= ^= |= <<= >>=

Find provisioning profile in Xcode 5

I wrote a simple bash script to get around this stupid problem. Pass in the path to a named copy of your provision (downloaded from developer.apple.com) and it will identify the matching GUID-renamed file in your provision library:

#!/bin/bash

if [ -z "$1" ] ; then
  echo -e "\nUsage: $0 <myprovision>\n"
  exit
fi

if [ ! -f "$1" ] ; then
  echo -e "\nFile not found: $1\n"
  exit
fi

provisionpath="$HOME/Library/MobileDevice/Provisioning Profiles"
provisions=$( ls "$provisionpath" )

for i in $provisions ; do
  match=$( diff "$1" "$provisionpath/$i" )
  if [ "$match" = "" ] ; then
    echo -e "\nmatch: $provisionpath/$i\n"
  fi
done

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

What are the obj and bin folders (created by Visual Studio) used for?

The obj directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.

You can change the actual directories used for both purposes within the project settings, if you like.

How to change the background-color of jumbrotron?

In the .css try

_x000D_
_x000D_
.jumbotron {_x000D_
    background-color:red !important; _x000D_
}
_x000D_
_x000D_
_x000D_

In Python, what is the difference between ".append()" and "+= []"?

In the example you gave, there is no difference, in terms of output, between append and +=. But there is a difference between append and + (which the question originally asked about).

>>> a = []
>>> id(a)
11814312
>>> a.append("hello")
>>> id(a)
11814312

>>> b = []
>>> id(b)
11828720
>>> c = b + ["hello"]
>>> id(c)
11833752
>>> b += ["hello"]
>>> id(b)
11828720

As you can see, append and += have the same result; they add the item to the list, without producing a new list. Using + adds the two lists and produces a new list.

Does Python support short-circuiting?

Yep, both and and or operators short-circuit -- see the docs.

Installing lxml module in python

If you're running python3, you'll have to do:

pip3 install lxml

What does "where T : class, new()" mean?

That is a constraint on the generic parameter T. It must be a class (reference type) and must have a public parameter-less default constructor.

That means T can't be an int, float, double, DateTime or any other struct (value type).

It could be a string, or any other custom reference type, as long as it has a default or parameter-less constructor.

How can I execute Shell script in Jenkinsfile?

Previous answers are correct but here is one more way of doing this and some tips:

Option #1 Go to you Jenkins job and search for "add build step" and then just copy and paste your script there

Option #2 Go to Jenkins and do the same again "add build step" but this time put the fully qualified path for your script in there example : ./usr/somewhere/helloWorld.sh

enter image description here enter image description here

things to watch for /tips:

  • Environment variables, if your job is running at the same time then you need to worry about concurrency issues. One job may be setting the value of environment variables and the next may use the value or take some action based on that incorrectly.
  • Make sure all paths are fully qualified
  • Think about logging /var/log or somewhere so you would also have something to go to on the server (optional)
  • thing about space issue and permissions, running out of space and permission issues are very common in linux environment
  • Alerting and make sure your script/job fails the jenkin jobs when your script fails

What are good ways to prevent SQL injection?

SQL injection should not be prevented by trying to validate your input; instead, that input should be properly escaped before being passed to the database.

How to escape input totally depends on what technology you are using to interface with the database. In most cases and unless you are writing bare SQL (which you should avoid as hard as you can) it will be taken care of automatically by the framework so you get bulletproof protection for free.

You should explore this question further after you have decided exactly what your interfacing technology will be.

How can I consume a WSDL (SOAP) web service in Python?

Zeep is a decent SOAP library for Python that matches what you're asking for: http://docs.python-zeep.org

What is the difference between require and require-dev sections in composer.json?

Different Environments

Typically, software will run in different environments:

  • development
  • testing
  • staging
  • production

Different Dependencies in Different Environments

The dependencies which are declared in the require section of composer.json are typically dependencies which are required for running an application or a package in

  • staging
  • production

environments, whereas the dependencies declared in the require-dev section are typically dependencies which are required in

  • developing
  • testing

environments.

For example, in addition to the packages used for actually running an application, packages might be needed for developing the software, such as:

  • friendsofphp/php-cs-fixer (to detect and fix coding style issues)
  • squizlabs/php_codesniffer (to detect and fix coding style issues)
  • phpunit/phpunit (to drive the development using tests)
  • etc.

Deployment

Now, in development and testing environments, you would typically run

$ composer install

to install both production and development dependencies.

However, in staging and production environments, you only want to install dependencies which are required for running the application, and as part of the deployment process, you would typically run

$ composer install --no-dev

to install only production dependencies.

Semantics

In other words, the sections

  • require
  • require-dev

indicate to composer which packages should be installed when you run

$ composer install

or

$ composer install --no-dev

That is all.

Note Development dependencies of packages your application or package depend on will never be installed

For reference, see:

How to limit the maximum value of a numeric field in a Django model?

You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields

In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.

The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.

This is working for me:

from django.db import models

class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, verbose_name, name, **kwargs)
    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)

Then in your model class, you would use it like this (field being the module where you put the above code):

size = fields.IntegerRangeField(min_value=1, max_value=50)

OR for a range of negative and positive (like an oscillator range):

size = fields.IntegerRangeField(min_value=-100, max_value=100)

What would be really cool is if it could be called with the range operator like this:

size = fields.IntegerRangeField(range(1, 50))

But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...

How to iterate through table in Lua?

If you want to refer to a nested table by multiple keys you can just assign them to separate keys. The tables are not duplicated, and still reference the same values.

arr = {}
apples = {'a', "red", 5 }
arr.apples = apples
arr[1] = apples

This code block lets you iterate through all the key-value pairs in a table (http://lua-users.org/wiki/TablesTutorial):

for k,v in pairs(t) do
 print(k,v)
end

how to auto select an input field and the text in it on page load

From http://www.codeave.com/javascript/code.asp?u_log=7004:

_x000D_
_x000D_
var input = document.getElementById('myTextInput');_x000D_
input.focus();_x000D_
input.select();
_x000D_
<input id="myTextInput" value="Hello world!" />
_x000D_
_x000D_
_x000D_

Rails - Could not find a JavaScript runtime?

I ran into this issue using Phusion Passenger (running as an nginx module) on a Redhat server. We already had a Javascript runtime installed. Other Rails apps in the same parent directory worked fine.

It turned out that we had a permissions issue. Run "ls -l" and see if the folder has the same owner and group as other working apps on the system. I had to run chown and chgrp on the folder (with the recursive switch) to fix it.

Find a class somewhere inside dozens of JAR files?

grep -l "classname" *.jar

gives you the name of the jar

find . -name "*.jar" -exec jar -t -f {} \; | grep  "classname"

gives you the package of the class

Java count occurrence of each item in an array

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class MultiString {

    public HashMap<String, Integer> countIntem( String[] array ) {

        Arrays.sort(array);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        Integer count = 0;
        String first = array[0];
        for( int counter = 0; counter < array.length; counter++ ) {
            if(first.hashCode() == array[counter].hashCode()) {
                count = count + 1;
            } else {
                map.put(first, count);
                count = 1;
            }
            first = array[counter];
            map.put(first, count);
        }

        return map;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] array = { "name1", "name1", "name2", "name2", "name2",
                "name3", "name1", "name1", "name2", "name2", "name2", "name3" };

        HashMap<String, Integer> countMap = new MultiString().countIntem(array);
        System.out.println(countMap);
    }
}



Gives you O(n) complexity.

Create a .txt file if doesn't exist, and if it does append a new line

using(var tw = new StreamWriter(path, File.Exists(path)))
{
    tw.WriteLine(message);
}

How to specify multiple return types using type-hints

From the documentation

class typing.Union

Union type; Union[X, Y] means either X or Y.

Hence the proper way to represent more than one return data type is

from typing import Union


def foo(client_id: str) -> Union[list,bool]

But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."

>>> def foo(a:str) -> list:
...     return("Works")
... 
>>> foo(1)
'Works'

As you can see I am passing a int value and returning a str. However the __annotations__ will be set to the respective values.

>>> foo.__annotations__ 
{'return': <class 'list'>, 'a': <class 'str'>}

Please Go through PEP 483 for more about Type hints. Also see What are Type hints in Python 3.5?

Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.

Vue v-on:click does not work on component

As mentioned by Chris Fritz (Vue.js Core Team Emeriti) in VueCONF US 2019

if we had Kia enter .native and then the root element of the base input changed from an input to a label suddenly this component is broken and it's not obvious and in fact, you might not even catch it right away unless you have a really good test. Instead by avoiding the use of the .native modifier which I currently consider an anti-pattern will be removed in Vue 3 you'll be able to explicitly define that the parent might care about which element listeners are added to...

With Vue 2

Using $listeners:

So, if you are using Vue 2 a better option to resolve this issue would be to use a fully transparent wrapper logic. For this Vue provides a $listeners property containing an object of listeners being used on the component. For example:

{
  focus: function (event) { /* ... */ }
  input: function (value) { /* ... */ },
}

and then we just need to add v-on="$listeners" to the test component like:

Test.vue (child component)

<template>
  <div v-on="$listeners">
    click here
  </div>
</template>

Now the <test> component is a fully transparent wrapper, meaning it can be used exactly like a normal <div> element: all the listeners will work, without the .native modifier.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" v-on="$listeners">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using $emit method:

We can also use $emit method for this purpose, which helps us to listen to child components events in parent component. For this, we first need to emit a custom event from child component like:

Test.vue (child component)

<test @click="$emit('my-event')"></test>

Important: Always use kebab-case for event names. For more information and demo regading this point please check out this answer: VueJS passing computed value from component to parent.

Now, we just need to listen to this emitted custom event in parent component like:

App.vue

<test @my-event="testFunction"></test>

So, basically instead of v-on:click or the shorthand @click we will simply use v-on:my-event or just @my-event.

Demo:

_x000D_
_x000D_
Vue.component('test', {_x000D_
  template: `_x000D_
    <div class="child" @click="$emit('my-event')">_x000D_
      Click here_x000D_
    </div>`_x000D_
})_x000D_
_x000D_
new Vue({_x000D_
  el: "#myApp",_x000D_
  data: {},_x000D_
  methods: {_x000D_
    testFunction: function(event) {_x000D_
      console.log('test clicked')_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>_x000D_
<div id="myApp">_x000D_
  <test @my-event="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_


With Vue 3

Using v-bind="$attrs":

Vue 3 is going to make our life much easier in many ways. One of the examples for it is that it will help us to create a simpler transparent wrapper with very less config by just using v-bind="$attrs". By using this on child components not only our listener will work directly from the parent but also any other attribute will also work just like it a normal <div> only.

So, with respect to this question, we will not need to update anything in Vue 3 and your code will still work fine as <div> is the root element here and it will automatically listen to all child events.

Demo #1:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const Test = {_x000D_
  template: `_x000D_
    <div class="child">_x000D_
      Click here_x000D_
    </div>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { Test },_x000D_
  setup() {_x000D_
    const testFunction = event => {_x000D_
      console.log("test clicked");_x000D_
    };_x000D_
    return { testFunction };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
div.child{border:5px dotted orange; padding:20px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <test v-on:click="testFunction"></test>_x000D_
</div>
_x000D_
_x000D_
_x000D_

But for complex components with nested elements where we need to apply attributes and events to main <input /> instead of the parent label we can simply use v-bind="$attrs"

Demo #2:

_x000D_
_x000D_
const { createApp } = Vue;_x000D_
_x000D_
const BaseInput = {_x000D_
  props: ['label', 'value'],_x000D_
  template: `_x000D_
    <label>_x000D_
      {{ label }}_x000D_
      <input v-bind="$attrs">_x000D_
    </label>`_x000D_
};_x000D_
_x000D_
const App = {_x000D_
  components: { BaseInput },_x000D_
  setup() {_x000D_
    const search = event => {_x000D_
      console.clear();_x000D_
      console.log("Searching...", event.target.value);_x000D_
    };_x000D_
    return { search };_x000D_
  }_x000D_
};_x000D_
_x000D_
createApp(App).mount("#myApp");
_x000D_
input{padding:8px;}
_x000D_
<script src="//unpkg.com/vue@next"></script>_x000D_
<div id="myApp">_x000D_
  <base-input _x000D_
    label="Search: "_x000D_
    placeholder="Search"_x000D_
    @keyup="search">_x000D_
  </base-input><br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I get the name of the active user via the command line in OS X?

as 'whoami' has been obsoleted, it's probably more forward compatible to use:

id -un