Programs & Examples On #Cgiapp

How to count number of records per day?

This one is like the answer above which uses the MySql DATE_FORMAT() function. I also selected just one specific week in Jan.

SELECT 
    DatePart(day, DateAdded) AS date, 
    COUNT(entryhash) AS count 
FROM Responses 
    where DateAdded > '2020-01-25' and DateAdded < '2020-02-01' 
GROUP BY 
    DatePart(day, DateAdded )

Disable same origin policy in Chrome

If you are using Google Chrome on Linux, following command works.

google-chrome  --disable-web-security

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

I had the same problem for Visual Studio 2019 v16.8.6. It was fixed after repair Visual Studio from Visual Studio Installer.

Linux command to list all available commands and aliases

Here's a solution that gives you a list of all executables and aliases. It's also portable to systems without xargs -d (e.g. Mac OS X), and properly handles paths with spaces in them.

#!/bin/bash
(echo -n $PATH | tr : '\0' | xargs -0 -n 1 ls; alias | sed 's/alias \([^=]*\)=.*/\1/') | sort -u | grep "$@"

Usage: myscript.sh [grep-options] pattern, e.g. to find all commands that begin with ls, case-insensitive, do:

myscript -i ^ls

How to alter a column and change the default value?

Accepted Answer works good.

In case of Invalid use of NULL value error, on NULL values, update all null values to default value in that column and then try to do the alter.

UPDATE foobar_data SET col = '{}' WHERE col IS NULL;

ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}';

Setting a Sheet and cell as variable

Yes. For that ensure that you declare the worksheet

For example

Previous Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet3")

    Debug.Print ws.Cells(23, 4).Value
End Sub

New Code

Sub Sample()
    Dim ws As Worksheet

    Set ws = Sheets("Sheet4")

    Debug.Print ws.Cells(23, 4).Value
End Sub

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

How to install Flask on Windows?

Assuming you are a PyCharm User, its pretty easy to install Flask This will help users without shell pip access also.

  • Open Settings(Ctrl+Alt+s) >>
  • Goto Project Interpreter>>
  • Double click pip>> Search for flask
  • Select and click Install Package ( Check Install to site users if intending to use Flask for this project alone Done!!!

Cases in which flask is not shown in pip: Open Manage Repository>> Add(+) >> Add this following url

https://www.palletsprojects.com/p/flask/

Now back to pip, it will show related packages of flask,

  • select flask>>
  • install package>>

Voila!!!

Disable dragging an image from an HTML page

Answer is simple:

<body oncontextmenu="return false"/> - disable right-click <body ondragstart="return false"/> - disable mouse dragging <body ondrop="return false"/> - disable mouse drop

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

just go to the window bottom tray click on wamp icon ,click mysql->my.ini,then there is option ;sql-mode="" uncomment this make it like sql-mode="" and restart wamp worked for me

How to get the PYTHONPATH in shell?

Just write:

just write which python in your terminal and you will see the python path you are using.

Get Image Height and Width as integer values?

Like this :

imageCreateFromPNG($var);
//I don't know where from you get your image, here it's in the png case
// and then :
list($width, $height) = getimagesize($image);
echo $width;
echo $height;

CSS to set A4 paper size

I looked into this a bit more and the actual problem seems to be with assigning initial to page width under the print media rule. It seems like in Chrome width: initial on the .page element results in scaling of the page content if no specific length value is defined for width on any of the parent elements (width: initial in this case resolves to width: auto ... but actually any value smaller than the size defined under the @page rule causes the same issue).

So not only the content is now too long for the page (by about 2cm), but also the page padding will be slightly more than the initial 2cm and so on (it seems to render the contents under width: auto to the width of ~196mm and then scale the whole content up to the width of 210mm ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than 210mm).

To fix this problem you can simply in the print media rule assign the A4 paper width and hight to html, body or directly to .page and in this case avoid the initial keyword.

DEMO

@page {
  size: A4;
  margin: 0;
}
@media print {
  html, body {
    width: 210mm;
    height: 297mm;
  }
  /* ... the rest of the rules ... */
}

This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).

Detect if a NumPy array contains at least one non-numeric value?

With numpy 1.3 or svn you can do this

In [1]: a = arange(10000.).reshape(100,100)

In [3]: isnan(a.max())
Out[3]: False

In [4]: a[50,50] = nan

In [5]: isnan(a.max())
Out[5]: True

In [6]: timeit isnan(a.max())
10000 loops, best of 3: 66.3 µs per loop

The treatment of nans in comparisons was not consistent in earlier versions.

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

To this error:

# git pull
sign_and_send_pubkey: signing failed: agent refused operation
[email protected]: Permission denied (publickey).    
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

Verify or add again the public key in Github account > profile > ssh.

I solved like this:

# chmod 400 ~/.ssh/id_rsa

# ls  ~/.ssh/id_rsa -ls  
4 -r--------. 1 reinaldo reinaldo 1679 Jul 26  2017 /home/reinaldo/.ssh/id_rsa

# git pull                                 
remote: Counting objects: 35, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 35 (delta 9), reused 34 (delta 9), pack-reused 0
Unpacking objects: 100% (35/35), done.

Thank you.

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Components should start with capital letters. Also remember to change the first letter in the line to export!

The difference between fork(), vfork(), exec() and clone()

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

SASS :not selector

I tried re-creating this, and .someclass.notip was being generated for me but .someclass:not(.notip) was not, for as long as I did not have the @mixin tip() defined. Once I had that, it all worked.

http://sassmeister.com/gist/9775949

$dropdown-width: 100px;
$comp-tip: true;

@mixin tip($pos:right) {

}

@mixin dropdown-pos($pos:right) {
  &:not(.notip) {
    @if $comp-tip == true{
      @if $pos == right {
        top:$dropdown-width * -0.6;
        background-color: #f00;
        @include tip($pos:$pos);
      }
    }
  }
  &.notip {
    @if $pos == right {
      top: 0;
      left:$dropdown-width * 0.8;
      background-color: #00f;
    }
  }
}

.someclass { @include dropdown-pos(); }

EDIT: http://sassmeister.com/ is a good place to debug your SASS because it gives you error messages. Undefined mixin 'tip'. it what I get when I remove @mixin tip($pos:right) { }

PostgreSQL "DESCRIBE TABLE"

When your table is not part of the default schema, you should write:

\d+ schema_name.table_name

Otherwise, you would get the error saying that "the relation doesn not exist."

How to truncate string using SQL server

You can use

LEFT(column, length)

or

SUBSTRING(column, start index, length)

Iterate over object attributes in python

in general put a __iter__ method in your class and iterate through the object attributes or put this mixin class in your class.

class IterMixin(object):
    def __iter__(self):
        for attr, value in self.__dict__.iteritems():
            yield attr, value

Your class:

>>> class YourClass(IterMixin): pass
...
>>> yc = YourClass()
>>> yc.one = range(15)
>>> yc.two = 'test'
>>> dict(yc)
{'one': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], 'two': 'test'}

Looping from 1 to infinity in Python

Reiterating thg435's comment:

from itertools import takewhile, count

def thereIsAReasonToContinue(i):
    return not thereIsAReasonToBreak(i)

for i in takewhile(thereIsAReasonToContinue, count()):
    pass # or something else

Or perhaps more concisely:

from itertools import takewhile, count

for i in takewhile(lambda x : not thereIsAReasonToBreak(x), count()):
    pass # or something else

takewhile imitates a "well-behaved" C for loop: you have a continuation condition, but you have a generator instead of an arbitrary expression. There are things you can do in a C for loop that are "badly behaved", such as modifying i in the loop body. It's possible to imitate those too using takewhile, if the generator is a closure over some local variable i that you then mess with. In a way, defining that closure makes it especially obvious that you're doing something potentially confusing with your control structure.

jQuery Validate - Enable validation for hidden fields

Just find the text ignore: ":hidden" in your jquery validation file and comment it. After comment this it will never loss any hidden elements to validate...

Thanks

How to check if an user is logged in Symfony2 inside a controller?

To add to answer given by Anil, In symfony3, you can use $this->getUser() to determine if the user is logged in, a simple condition like if(!$this->getUser()) {} will do.

If you look at the source code which is available in base controller, it does the exact same thing defined by Anil.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

127.0.0.1 is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1 for connections will only receive local connections on that socket.

"localhost" is normally the hostname for the 127.0.0.1 IP address. It's usually set in /etc/hosts (or the Windows equivalent named "hosts" somewhere under %WINDIR%). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1.

0.0.0.0 has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0 that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1 from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0 will accept connections on that interface too.

That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000 is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1

str.startswith with a list of strings to test for

str.startswith allows you to supply a tuple of strings to test for:

if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:

>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Try setting core.autocrlf value like this :

git config --global core.autocrlf true

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.

You need to add the parameters both to the URL and to the signature creating process. Creating a signature is the article that helped me. Here is my code:

$oauth = array(
           'screen_name' => 'DwightHoward',
           'count' => 2,
           'oauth_consumer_key' => $consumer_key,
           'oauth_nonce' => time(),
           'oauth_signature_method' => 'HMAC-SHA1',
           'oauth_token' => $oauth_access_token,
           'oauth_timestamp' => time(),
           'oauth_version' => '1.0'
         );

$options = array(
             CURLOPT_HTTPHEADER => $header,
             //CURLOPT_POSTFIELDS => $postfields,
             CURLOPT_HEADER => false,
             CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
             CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
           );

Inserting an item in a Tuple

For the case where you are not adding to the end of the tuple

>>> a=(1,2,3,5,6)
>>> a=a[:3]+(4,)+a[3:]
>>> a
(1, 2, 3, 4, 5, 6)
>>> 

How to succinctly write a formula with many variables from a data frame?

An extension of juba's method is to use reformulate, a function which is explicitly designed for such a task.

## Create a formula for a model with a large number of variables:
xnam <- paste("x", 1:25, sep="")

reformulate(xnam, "y")
y ~ x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 + x10 + x11 + 
    x12 + x13 + x14 + x15 + x16 + x17 + x18 + x19 + x20 + x21 + 
    x22 + x23 + x24 + x25

For the example in the OP, the easiest solution here would be

# add y variable to data.frame d
d <- cbind(y, d)
reformulate(names(d)[-1], names(d[1]))
y ~ x1 + x2 + x3

or

mod <- lm(reformulate(names(d)[-1], names(d[1])), data=d)

Note that adding the dependent variable to the data.frame in d <- cbind(y, d) is preferred not only because it allows for the use of reformulate, but also because it allows for future use of the lm object in functions like predict.

How to remove list elements in a for loop in Python?

Iterate through a copy of the list:

>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
    print item
    if item == "b":
        a.remove(item)

a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']

How to resize superview to fit all subviews with autolayout?

You can do this by creating a constraint and connecting it via interface builder

See explanation: Auto_Layout_Constraints_in_Interface_Builder

raywenderlich beginning-auto-layout

AutolayoutPG Articles constraint Fundamentals

@interface ViewController : UIViewController {
    IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
    IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;

connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this

 self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign

I hope this clarifies it.

How to debug Angular JavaScript Code

IMHO, the most frustrating experience comes from getting / setting a value of a specific scope related to an visual element. I did a lot of breakpoints not only in my own code, but also in angular.js itself, but sometimes it is simply not the most effective way. Although the methods below are very powerful, they are definitely considered to be bad practice if you actually use in production code, so use them wisely!

Get a reference in console from a visual element

In many non-IE browsers, you can select an element by right clicking an element and clicking "Inspect Element". Alternatively you can also click on any element in Elements tab in Chrome, for example. The latest selected element will be stored in variable $0 in console.

Get a scope linked to an element

Depending on whether there exists a directive that creates an isolate scope, you can retrieve the scope by angular.element($0).scope() or angular.element($0).isolateScope() (use $($0).scope() if $ is enabled). This is exactly what you get when you are using the latest version of Batarang. If you are changing the value directly, remember to use scope.$digest() to reflect the changes on UI.

$eval is evil

Not necessarily for debugging. scope.$eval(expression) is very handy when you want to quickly check whether an expression has the expected value.

The missing prototype members of scope

The difference between scope.bla and scope.$eval('bla') is the former does not consider the prototypically inherited values. Use the snippet below to get the whole picture (you cannot directly change the value, but you can use $eval anyway!)

scopeCopy = function (scope) {
    var a = {}; 
    for (x in scope){ 
        if (scope.hasOwnProperty(x) && 
            x.substring(0,1) !== '$' && 
            x !== 'this') {
            a[x] = angular.copy(scope[x])
        }
    }
    return a
};

scopeEval = function (scope) {
    if (scope.$parent === null) {
        return hoho(scope)
    } else {
        return angular.extend({}, haha(scope.$parent), hoho(scope))
    }
};

Use it with scopeEval($($0).scope()).

Where is my controller?

Sometimes you may want to monitor the values in ngModel when you are writing a directive. Use $($0).controller('ngModel') and you will get to check the $formatters, $parsers, $modelValue, $viewValue $render and everything.

Android getting value from selected radiobutton

Tested and working. Check this

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioGroup = (RadioGroup) findViewById(R.id.radio);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

xml

<RadioGroup
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />

    </RadioGroup>

"call to undefined function" error when calling class method

Mates,

I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this

      try{
             foo();
         }
       catch (exception $e)
           {
            echo "$e->getMessage()";
           }

       function foo(){
                       echo "blah blah blah";
                     }

so php was throwing me error "call to undefined function ".

This kinda seem classic programming error but may help someone in need of clue.

Java Strings: "String s = new String("silly");"

In most versions of the JDK the two versions will be the same:

String s = new String("silly");

String s = "No longer silly";

Because strings are immutable the compiler maintains a list of string constants and if you try to make a new one will first check to see if the string is already defined. If it is then a reference to the existing immutable string is returned.

To clarify - when you say "String s = " you are defining a new variable which takes up space on the stack - then whether you say "No longer silly" or new String("silly") exactly the same thing happens - a new constant string is compiled into your application and the reference points to that.

I dont see the distinction here. However for your own class, which is not immutable, this behaviour is irrelevant and you must call your constructor.

UPDATE: I was wrong! Based on a down vote and comment attached I tested this and realise that my understanding is wrong - new String("Silly") does indeed create a new string rather than reuse the existing one. I am unclear why this would be (what is the benefit?) but code speaks louder than words!

DateTime.TryParse issue with dates of yyyy-dd-MM format

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

Spring default behavior for lazy-init

The default behaviour is false:

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.

I suggest reading up

Make hibernate ignore class variables that are not mapped

JPA will use all properties of the class, unless you specifically mark them with @Transient:

@Transient
private String agencyName;

The @Column annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length attribute of @Column is only used when auto-generating table definitions, it has no effect on the runtime.

Display current date and time without punctuation

A simple example in shell script

#!/bin/bash

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S

Array versus linked-list

For me it is like this,

  1. Access

    • Linked Lists allow only sequential access to elements. Thus the algorithmic complexities is order of O(n)
    • Arrays allow random access to its elements and thus the complexity is order of O(1)
  2. Storage

    • Linked lists require an extra storage for references. This makes them impractical for lists of small data items such as characters or boolean values.
    • Arrays do not need an extra storage to point to next data item. Each element can be accessed via indexes.
  3. Size

    • The size of Linked lists are dynamic by nature.
    • The size of array is restricted to declaration.
  4. Insertion/Deletion

    • Elements can be inserted and deleted in linked lists indefinitely.
    • Insertion/Deletion of values in arrays are very expensive. It requires memory reallocation.

How to check edittext's text is email address or not?

here email is your email-id.

  public boolean validateEmail(String email) {

    Pattern pattern;
    Matcher matcher;
    String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    return matcher.matches();

    }

Encapsulation vs Abstraction?

Encapsulation protects to collapse the internal behaviour of object/instance from external entity. So, a control should be provided to confirm that the data which is being supplied is not going to harm the internal system of instance/object to survive its existance.

Good example, Divider is a class which has two instance variable dividend and divisor and a method getDividedValue.

Can you please think, if the divisor is set to 0 then internal system/behaviour (getDivided ) will break.

So, the object internal behaviour could be protected by throwing exception through a method.

Default value to a parameter while passing by reference in C++

You cannot use a constant literal for a default parameter for the same reason you cannot use one as a parameter to the function call. Reference values must have an address, constant references values need not (ie they can be r-values or constant literals).

int* foo (int& i )
{
   return &i;
}

foo(0); // compiler error.

const int* bar ( const int& i )
{
   return &i;
}

bar(0); // ok.

Ensure that you're default value has an address and you're fine.

int null_object = 0;

int Write(int &state = null_object, bool sequence = true)
{
   if( &state == &null_object )
   {
      // called with default paramter
      return sequence? 1: rand();
   }
   else
   {
      // called with user parameter
      state += sequence? 1: rand();
      return state;
   }
}

I've used this pattern a few times where I had a parameter that could be a variable or null. The regular approach is to have the user pass in a pointer this is case. They pass in a NULL pointer if they don't want you to fill in the value. I like to null object approach. It makes the callers life easier without terribly complicating the callee code.

How to get value at a specific index of array In JavaScript?

You can just use []:

var valueAtIndex1 = myValues[1];

Detecting Browser Autofill

If you only want to detect whether auto-fill has been used or not, rather than detecting exactly when and to which field auto-fill has been used, you can simply add a hidden element that will be auto-filled and then check whether this contains any value. I understand that this may not be what many people are interested in. Set the input field with a negative tabIndex and with absolute coordinates well off the screen. It's important that the input is part of the same form as the rest of the input. You must use a name that will be picked up by Auto-fill (ex. "secondname").

var autofilldetect = document.createElement('input');
autofilldetect.style.position = 'absolute';
autofilldetect.style.top = '-100em';
autofilldetect.style.left = '-100em';
autofilldetect.type = 'text';
autofilldetect.name = 'secondname';
autofilldetect.tabIndex = '-1';

Append this input to the form and check its value on form submit.

How to animate RecyclerView items when they appear

I animated fading in of Recyclerview items when they first appear as shown in the code below. Perhaps this will be of use to someone.

private final static int FADE_DURATION = 1000; //FADE_DURATION in milliseconds

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    holder.getTextView().setText("some text");

    // Set the view to fade in
    setFadeAnimation(holder.itemView);            
}

private void setFadeAnimation(View view) {
    AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

You can also replace setFadeAnimation() with the following setScaleAnimation() to animate appearance of items by scaling them from a point:

private void setScaleAnimation(View view) {
    ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

The code above has some warts in so far as when you scroll the RecyclerView items always fade or scale. If you wish you can add code to just allow the animation to happen when the fragment or activity containing the RecyclerView is first created (e.g. get the system time on creation and only allow animation for the first FADE_DURATION milliseconds).

Jquery If radio button is checked

Try this

if($("input:radio[name=postage]").is(":checked")){
  //Code to append goes here
}

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

After following the steps from @Johnride, I still got the same error.

This fixed the problem:

Tools-> Options-> Select no proxy

source: https://www.youtube.com/watch?v=uI1j-8F8eN4

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

Live video streaming using Java?

JMF was abandoned. VLC is more up to date and it reads everything. https://stackoverflow.com/a/5160010

I think vlc beats every other software out there yet, or at least the ones that I know...

How to find MySQL process list and to kill those processes?

You can do something like this to check if any mysql process is running or not:

ps aux | grep mysqld
ps aux | grep mysql

Then if it is running you can killall by using(depending on what all processes are running currently):

killall -9 mysql
killall -9 mysqld
killall -9 mysqld_safe    

How can I add an element after another element?

First of all, input element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the after(), not append() function.

@Autowired - No qualifying bean of type found for dependency

Instead of @Autowire MailManager mailManager, you can mock the bean as given below:

import org.springframework.boot.test.mock.mockito.MockBean;

::
::

@MockBean MailManager mailManager;

Also, you can configure @MockBean MailManager mailManager; separately in the @SpringBootConfiguration class and initialize like below:

@Autowire MailManager mailManager

How can I do an OrderBy with a dynamic string parameter?

Look at this blog here. It describes a way to do this, by defining an EntitySorter<T>.

It allows you to pass in an IEntitySorter<T> into your service methods and use it like this:

public static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
    using (var db = ContextFactory.CreateContext())
    {
        IOrderedQueryable<Person> sortedList = sorter.Sort(db.Persons);

        return sortedList.ToArray();
    }
}

And you can create an EntitiySorter like this:

IEntitySorter<Person> sorter = EntitySorter<Person>
    .OrderBy(p => p.Name)
    .ThenByDescending(p => p.Id);

Or like this:

var sorter = EntitySorter<Person>
     .OrderByDescending("Address.City")
     .ThenBy("Id");

Django - after login, redirect user to his custom page --> mysite.com/username

When using Class based views, another option is to use the dispatch method. https://docs.djangoproject.com/en/2.2/ref/class-based-views/base/

Example Code:

Settings.py

LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'

urls.py

from django.urls import path
from django.contrib.auth import views as auth_views
urlpatterns = [
path('', HomeView.as_view(), name='home'),
path('login/', auth_views.LoginView.as_view(),name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]

views.py

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic import View
from django.shortcuts import redirect

@method_decorator([login_required], name='dispatch')
class HomeView(View):
    model = models.User

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            return redirect('login')
        elif some-logic:
            return redirect('some-page') #needs defined as valid url
        return super(HomeView, self).dispatch(request, *args, **kwargs)

How to retrieve checkboxes values in jQuery

If you want to insert the value of any checkbox immediately as it is being checked then this should work for you:

$(":checkbox").click(function(){
  $("#id").text(this.value)
})

How can I generate a 6 digit unique number?

Here's another one:

substr(number_format(time() * rand(),0,'',''),0,6);

Permutations between two lists of unequal length

I was looking for a list multiplied by itself with only unique combinations, which is provided as this function.

import itertools
itertools.combinations(list, n_times)

Here as an excerpt from the Python docs on itertools That might help you find what your looking for.

Combinatoric generators:

Iterator                                 | Results
-----------------------------------------+----------------------------------------
product(p, q, ... [repeat=1])            | cartesian product, equivalent to a 
                                         |   nested for-loop
-----------------------------------------+----------------------------------------
permutations(p[, r])                     | r-length tuples, all possible 
                                         |   orderings, no repeated elements
-----------------------------------------+----------------------------------------
combinations(p, r)                       | r-length tuples, in sorted order, no 
                                         |   repeated elements
-----------------------------------------+----------------------------------------
combinations_with_replacement(p, r)      | r-length tuples, in sorted order, 
                                         | with repeated elements
-----------------------------------------+----------------------------------------
product('ABCD', repeat=2)                | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations('ABCD', 2)                  | AB AC AD BA BC BD CA CB CD DA DB DC
combinations('ABCD', 2)                  | AB AC AD BC BD CD
combinations_with_replacement('ABCD', 2) | AA AB AC AD BB BC BD CC CD DD

How to configure log4j to only keep log files for the last seven days?

Use the setting log4j.appender.FILE.RollingPolicy.FileNamePattern, e.g. log4j.appender.FILE.RollingPolicy.FileNamePattern=F:/logs/filename.log.%d{dd}.gz for keeping logs one month before rolling over.

I didn't wait for one month to check but I tried with mm (i.e. minutes) and confirmed it overwrites, so I am assuming it will work for all patterns.

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

Get type name without full namespace

typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name

generating variable names on fly in python

bit long, it works i guess...

prices = [5, 12, 45]
names = []
for i, _ in enumerate(prices):
    names.append("price"+str(i+1))
dict = {}
for name, price in zip(names, prices):
    dict[name] = price
for item in dict:
    print(item, "=", dict[item])

What's the difference between & and && in MATLAB?

& is a logical elementwise operator, while && is a logical short-circuiting operator (which can only operate on scalars).

For example (pardon my syntax).

If..

A = [True True False True]
B = False
A & B = [False False False False]

..or..

B = True
A & B = [True True False True]

For &&, the right operand is only calculated if the left operand is true, and the result is a single boolean value.

x = (b ~= 0) && (a/b > 18.5)

Hope that's clear.

Multiple definition of ... linker error

Don't define variables in headers. Put declarations in header and definitions in one of the .c files.

In config.h

extern const char *names[];

In some .c file:

const char *names[] =
    {
        "brian", "stefan", "steve"
    };

If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.

How to execute an oracle stored procedure?

Both 'is' and 'as' are valid syntax. Output is disabled by default. Try a procedure that also enables output...

create or replace procedure temp_proc is
begin
  DBMS_OUTPUT.ENABLE(1000000);
  DBMS_OUTPUT.PUT_LINE('Test');
end;

...and call it in a PLSQL block...

begin
  temp_proc;
end;

...as SQL is non-procedural.

Correct way to delete cookies server-side

For GlassFish Jersey JAX-RS implementation I have resolved this issue by common method is describing all common parameters. At least three of parameters have to be equal: name(="name"), path(="/") and domain(=null) :

public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
    ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
    Date expiry = time.toInstant().toEpochMilli();
    NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
    return newCookie;
}

And use it the common way to set cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

and to delete the cookie:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

Getting error "The package appears to be corrupt" while installing apk file

None of the answer is working for me.

As the error message is package corrupt , I will have to run

  1. adb uninstall <package name>
  2. Run app again / use adb install

Difference between thread's context class loader and normal classloader

Adding to @David Roussel answer, classes may be loaded by multiple class loaders.

Lets understand how class loader works.

From javin paul blog in javarevisited :

enter image description here

enter image description here

ClassLoader follows three principles.

Delegation principle

A class is loaded in Java, when its needed. Suppose you have an application specific class called Abc.class, first request of loading this class will come to Application ClassLoader which will delegate to its parent Extension ClassLoader which further delegates to Primordial or Bootstrap class loader

  • Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java. Bootstrap class loader don't have any parents.

  • Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property

  • System or Application class loader and it is responsible for loading application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.

  • Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class.

NOTE: Except Bootstrap class loader, which is implemented in native language mostly in C, all Java class loaders are implemented using java.lang.ClassLoader.

Visibility Principle

According to visibility principle, Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.

Uniqueness Principle

According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

Convert a string date into datetime in Oracle

You can use a cast to char to see the date results

_x000D_
_x000D_
 select to_char(to_date('17-MAR-17 06.04.54','dd-MON-yy hh24:mi:ss'), 'mm/dd/yyyy hh24:mi:ss') from dual;
_x000D_
_x000D_
_x000D_

How to calculate DATE Difference in PostgreSQL?

CAST both fields to datatype DATE and you can use a minus:

(CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference

Test case:

SELECT  (CAST(MAX(joindate) AS date) - CAST(MIN(joindate) AS date)) as DateDifference
FROM 
    generate_series('2014-01-01'::timestamp, '2014-02-01'::timestamp, interval '1 hour') g(joindate);

Result: 31

Or create a function datediff():

CREATE OR REPLACE FUNCTION datediff(timestamp, timestamp) 
RETURNS int 
LANGUAGE sql 
AS
$$
    SELECT CAST($1 AS date) - CAST($2 AS date) as DateDifference
$$;

How do I read / convert an InputStream into a String in Java?

Another one, for all the Spring users:

import java.nio.charset.StandardCharsets;
import org.springframework.util.FileCopyUtils;

public String convertStreamToString(InputStream is) throws IOException { 
    return new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);
}

The utility methods in org.springframework.util.StreamUtils are similar to the ones in FileCopyUtils, but they leave the stream open when done.

Elegant way to report missing values in a data.frame

Another function that would help you look at missing data would be df_status from funModeling library

library(funModeling)

iris.2 is the iris dataset with some added NAs.You can replace this with your dataset.

df_status(iris.2)

This will give you the number and percentage of NAs in each column.

git remote add with other SSH port

For those of you editing the ./.git/config

[remote "external"]                                                                                                                                                                                                                                                            
  url = ssh://[email protected]:11720/aaa/bbb/ccc                                                                                                                                                                                                               
  fetch = +refs/heads/*:refs/remotes/external/* 

ASP.net using a form to insert data into an sql server table

Simple, make a simple asp page with the designer (just for the beginning) Lets say the body is something like this:

<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </div>
    <p>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </p>
    </form>
</body>

Great, now every asp object IS an object. So you can access it in the asp's CS code. The asp's CS code is triggered by events (mostly). The class will probably inherit from System.Web.UI.Page

If you go to the cs file of the asp page, you'll see a protected void Page_Load(object sender, EventArgs e) ... That's the load event, you can use that to populate data into your objects when the page loads.

Now, go to the button in your designer (Button1) and look at its properties, you can design it, or add events from there. Just change to the events view, and create a method for the event.

The button is a web control Button Add a Click event to the button call it Button1Click:

void Button1Click(Object sender,EventArgs e) { }

Now when you click the button, this method will be called. Because ASP is object oriented, you can think of the page as the actual class, and the objects will hold the actual current data.

So if for example you want to access the text in TextBox1 you just need to call that object in the C# code:

String firstBox = TextBox1.Text;

In the same way you can populate the objects when event occur.

Now that you have the data the user posted in the textboxes , you can use regular C# SQL connections to add the data to your database.

Docker-compose: node_modules not present in a volume after npm install succeeds

Installing node_modules in container to different from project folder, and setting NODE_PATH to your node_modules folder helps me (u need to rebuild container).

I'm using docker-compose. My project file structure:

-/myproject
--docker-compose.yml
--nodejs/
----Dockerfile

docker-compose.yml:

version: '2'
services:
  nodejs:
    image: myproject/nodejs
    build: ./nodejs/.
    volumes:
      - ./nodejs:/workdir
    ports:
      - "23005:3000"
    command: npm run server

Dockerfile in nodejs folder:

FROM node:argon
RUN mkdir /workdir
COPY ./package.json /workdir/.
RUN mkdir /data
RUN ln -s /workdir/package.json /data/.
WORKDIR /data
RUN npm install
ENV NODE_PATH /data/node_modules/
WORKDIR /workdir

Express: How to pass app-instance to routes from a different file?

For database separate out Data Access Service that will do all DB work with simple API and avoid shared state.

Separating routes.setup looks like overhead. I would prefer to place a configuration based routing instead. And configure routes in .json or with annotations.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How to import Google Web Font in CSS file?

  1. Just go to https://fonts.google.com/
  2. Add font by clicking +
  3. Go to selected font > Embed > @IMPORT > copy url and paste in your .css file above body tag.
  4. It's done.

how to save canvas as png image?

I used this solution to set the file name:

HTML:

<a href="#" id="downloader" onclick="download()" download="image.png">Download!</a>
<canvas id="canvas"></canvas>

JavaScript:

function download(){
    document.getElementById("downloader").download = "image.png";
    document.getElementById("downloader").href = document.getElementById("canvas").toDataURL("image/png").replace(/^data:image\/[^;]/, 'data:application/octet-stream');
}

How do I check if an element is hidden in jQuery?

if($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}

How do I parse a HTML page with Node.js

You can use the npm modules jsdom and htmlparser to create and parse a DOM in Node.JS.

Other options include:

  • BeautifulSoup for python
  • you can convert you html to xhtml and use XSLT
  • HTMLAgilityPack for .NET
  • CsQuery for .NET (my new favorite)
  • The spidermonkey and rhino JS engines have native E4X support. This may be useful, only if you convert your html to xhtml.

Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.

Can I run Keras model on gpu?

Yes you can run keras models on GPU. Few things you will have to check first.

  1. your system has GPU (Nvidia. As AMD doesn't work yet)
  2. You have installed the GPU version of tensorflow
  3. You have installed CUDA installation instructions
  4. Verify that tensorflow is running with GPU check if GPU is working

sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

for TF > v2.0

sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(log_device_placement=True))

(Thanks @nbro and @Ferro for pointing this out in the comments)

OR

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

output will be something like this:

[
  name: "/cpu:0"device_type: "CPU",
  name: "/gpu:0"device_type: "GPU"
]

Once all this is done your model will run on GPU:

To Check if keras(>=2.1.1) is using GPU:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

All the best.

Node.js for() loop returning the same values at each loop

  for(var i = 0; i < BoardMessages.length;i++){
        (function(j){
            console.log("Loading message %d".green, j);
            htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
        })(i);
  }

That should work; however, you should never create a function in a loop. Therefore,

  for(var i = 0; i < BoardMessages.length;i++){
        composeMessage(BoardMessages[i]);
  }

  function composeMessage(message){
      console.log("Loading message %d".green, message);
      htmlMessageboardString += MessageToHTMLString(message);
  }

System.Threading.Timer in C# it seems to be not working. It runs very fast every 3 second

 var span = TimeSpan.FromMinutes(2);
 var t = Task.Factory.StartNew(async delegate / () =>
   {
        this.SomeAsync();
        await Task.Delay(span, source.Token);
  }, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

source.Cancel(true/or not);

// or use ThreadPool(whit defaul options thread) like this
Task.Start(()=>{...}), source.Token)

if u like use some loop thread inside ...

public async void RunForestRun(CancellationToken token)
{
  var t = await Task.Factory.StartNew(async delegate
   {
       while (true)
       {
           await Task.Delay(TimeSpan.FromSeconds(1), token)
                 .ContinueWith(task => { Console.WriteLine("End delay"); });
           this.PrintConsole(1);
        }
    }, token) // drop thread options to default values;
}

// And somewhere there
source.Cancel();
//or
token.ThrowIfCancellationRequested(); // try/ catch block requred.

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Moshe's solution is great but the problem may still exist if you need to put the list inside a div. (read: CSS counter-reset on nested list)

This style could prevent that issue:

_x000D_
_x000D_
ol > li {_x000D_
    counter-increment: item;_x000D_
}_x000D_
_x000D_
ol > li:first-child {_x000D_
  counter-reset: item;_x000D_
}_x000D_
_x000D_
ol ol > li {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
ol ol > li:before {_x000D_
    content: counters(item, ".") ". ";_x000D_
    margin-left: -20px;_x000D_
}
_x000D_
<ol>_x000D_
  <li>list not nested in div</li>_x000D_
</ol>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<div>_x000D_
  <ol>_x000D_
  <li>nested in div</li>_x000D_
  <li>two_x000D_
    <ol>_x000D_
      <li>two.one</li>_x000D_
      <li>two.two</li>_x000D_
      <li>two.three</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
  <li>three_x000D_
    <ol>_x000D_
      <li>three.one</li>_x000D_
      <li>three.two_x000D_
        <ol>_x000D_
          <li>three.two.one</li>_x000D_
          <li>three.two.two</li>_x000D_
        </ol>_x000D_
      </li>_x000D_
    </ol>_x000D_
  </li>_x000D_
  <li>four</li>_x000D_
  </ol>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also set the counter-reset on li:before.

how to calculate percentage in python

I know I am late, but if you want to know the easiest way, you could do a code like this:

number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)

You can change up the number score, and right_questions. It will tell you the percent.

Tomcat Servlet: Error 404 - The requested resource is not available

this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.

Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

How to kill a while loop with a keystroke?

There is a solution that requires no non-standard modules and is 100% transportable

import thread

def input_thread(a_list):
    raw_input()
    a_list.append(True)

def do_stuff():
    a_list = []
    thread.start_new_thread(input_thread, (a_list,))
    while not a_list:
        stuff()

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

select a value where it doesn't exist in another table

SELECT ID 
  FROM A 
 WHERE NOT EXISTS( SELECT 1
                     FROM B
                    WHERE B.ID = A.ID
                 )

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

Get filename from input [type='file'] using jQuery

$("#filetosend").prop('files')[0]

Config Error: This configuration section cannot be used at this path

On Windows Server 2012 with IIS 8 I have solved this by enabling ASP.NET 4.5 feature:

enter image description here

and then following ken's answer.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

By the time script is executed, document element is not available yet, because script itself is in the head. While it's a valid solution to keep script in head and render on DOMContentLoaded event, it's even better to put your script at the very bottom of the body and render root component to a div before it like this:

<html>
<head>
</head>
<body>
  <div id="root"></div>
  <script src="/bundle.js"></script>
</body>
</html>

and in the bundle.js, call:

React.render(<App />, document.getElementById('root'));

You should always render to a nested div instead of body. Otherwise, all sorts of third-party code (Google Font Loader, browser plugins, whatever) can modify the body DOM node when React doesn't expect it, and cause weird errors that are very hard to trace and debug. Read more about this issue.

The nice thing about putting script at the bottom is that it won't block rendering until script load in case you add React server rendering to your project.


Update: (October 07, 2015 | v0.14)

React.render is deprecated, use ReactDOM.render instead.

Example:

import ReactDOM from 'react-dom';

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

SQL conditional SELECT

The noob way to do this:

SELECT field1, field2 FROM table WHERE field1 = TRUE OR field2 = TRUE

You can manage this information properly at the programming language only doing an if-else.

Example in ASP/JavaScript

// Code to retrieve the ADODB.Recordset
if (rs("field1")) {
   do_the_stuff_a();
}
if (rs("field2")) {
   do_the_stuff_b();
}
rs.MoveNext();

Javascript one line If...else...else if statement

  a === "a" ? do something
: a === "b" ? do something
: do something

How can I change the default width of a Twitter Bootstrap modal box?

If you're using Bootstrap 3, you need to change the modal-dialog div and not the modal div like it is shown in the accepted answer. Also, to keep the responsive nature of Bootstrap 3, it's important to write the override CSS using a media query so the modal will be full width on smaller devices.

See this JSFiddle to experiment with different widths.

HTML

<div class="modal fade">
    <div class="modal-dialog custom-class">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h3 class="modal-header-text">Text</h3>
            </div>
            <div class="modal-body">
                This is some text.
            </div>
            <div class="modal-footer">
                This is some text.
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

CSS

@media screen and (min-width: 768px) {
    .custom-class {
        width: 70%; /* either % (e.g. 60%) or px (400px) */
    }
}

How to use UIVisualEffectView to Blur Image?

You can also use the interface builder to create these effects easily for simple situations. Since the z-values of the views will depend on the order they are listed in the Document Outline, you can drag a UIVisualEffectView onto the document outline before the view you want to blur. This automatically creates a nested UIView, which is the contentView property of the given UIVisualEffectView. Nest things within this view that you want to appear on top of the blur.

XCode6 beta5

You can also easily take advantage of the vibrancy UIVisualEffect, which will automatically create another nested UIVisualEffectView in the document outline with vibrancy enabled by default. You can then add a label or text view to the nested UIView (again, the contentView property of the UIVisualEffectView), to achieve the same effect that the "> slide to unlock" UI element.

enter image description here

check all socket opened in linux OS

You can use netstat command

netstat --listen

To display open ports and established TCP connections,

netstat -vatn

To display only open UDP ports try the following command:

netstat -vaun

Subset a dataframe by multiple factor levels

Try this:

> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
    Code Value
1      A     1
2      B     2
1.1    A     1
1.2    A     1

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

MySQL Workbench not opening on Windows

Update 2020:

Unfortunately this is still happening:

  1. Download .NET 4.0 (My machine already had it.)
  2. Download Visual C++
  3. As the above solution states. Download the Mysql workbench installer.

I still don't know why, it would allow me to install without checking for dependencies. I have become accustomed to this kind of behavior when I am installing any application and to not see it is annoying. I suppose I should leave this personal opinions out of my solution but I have had to install this multiple times and have comes across some kind of dependency issue.

Best equivalent VisualStudio IDE for Mac to program .NET/C#

The question is quite old so I feel like I need to give a more up to date response to this question.

Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/

Virtualbox shared folder permissions

In my case the following was necessary:

sudo chgrp vboxsf /media/sf_sharedFolder

converting string to long in python

Well, longs can't hold anything but integers.

One option is to use a float: float('234.89')

The other option is to truncate or round. Converting from a float to a long will truncate for you: long(float('234.89'))

>>> long(float('1.1'))
1L
>>> long(float('1.9'))
1L
>>> long(round(float('1.1')))
1L
>>> long(round(float('1.9')))
2L

How do you query for "is not null" in Mongo?

the Query Will be

db.mycollection.find({"IMAGE URL":{"$exists":"true"}})

it will return all documents having "IMAGE URL" as a key ...........

Loading resources using getClass().getResource()

getResource by example:

package szb.testGetResource;
public class TestGetResource {
    private void testIt() {
        System.out.println("test1: "+TestGetResource.class.getResource("test.css"));
        System.out.println("test2: "+getClass().getResource("test.css"));
    }
    public static void main(String[] args) {
        new TestGetResource().testIt();
    }
}

enter image description here

output:

test1: file:/home/szb/projects/test/bin/szb/testGetResource/test.css
test2: file:/home/szb/projects/test/bin/szb/testGetResource/test.css

java SSL and cert keystore

First of all, there're two kinds of keystores.

Individual and General

The application will use the one indicated in the startup or the default of the system.

It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.

They are encrypted too

In short, the path will be like:

$JAVA_HOME/lib/security/cacerts for the "general one", who has all the CA for the Authorities and is quite important.

Python strip() multiple characters?

For example string s="(U+007c)"

To remove only the parentheses from s, try the below one:

import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)

push_back vs emplace_back

One more example for lists:

// constructs the elements in place.                                                
emplace_back("element");

// creates a new object and then copies (or moves) that object.
push_back(ExplicitDataType{"element"});

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

How to dispatch a Redux action with a timeout?

I would recommend also taking a look at the SAM pattern.

The SAM pattern advocates for including a "next-action-predicate" where (automatic) actions such as "notifications disappear automatically after 5 seconds" are triggered once the model has been updated (SAM model ~ reducer state + store).

The pattern advocates for sequencing actions and model mutations one at a time, because the "control state" of the model "controls" which actions are enabled and/or automatically executed by the next-action predicate. You simply cannot predict (in general) what state the system will be prior to processing an action and hence whether your next expected action will be allowed/possible.

So for instance the code,

export function showNotificationWithTimeout(dispatch, text) {
  const id = nextNotificationId++
  dispatch(showNotification(id, text))

  setTimeout(() => {
    dispatch(hideNotification(id))
  }, 5000)
}

would not be allowed with SAM, because the fact that a hideNotification action can be dispatched is dependent on the model successfully accepting the value "showNotication: true". There could be other parts of the model that prevents it from accepting it and therefore, there would be no reason to trigger the hideNotification action.

I would highly recommend that implement a proper next-action predicate after the store updates and the new control state of the model can be known. That's the safest way to implement the behavior you are looking for.

You can join us on Gitter if you'd like. There is also a SAM getting started guide available here.

Force encode from US-ASCII to UTF-8 (iconv)

Inspired a lot by Mathieu's answer and Marcelo's answer:

I face the need to see file -i myfile.htm to show UTF-8 instead of US ASCII (yes, I know it is a subset of UTF-8).

So here is a one liner inspired from previous answers that will convert on Linux all *.htm file from US ASCII to UTF-8 so file -i will show you UTF-8. You can change *.htm (two places in the command below) to fit your need.

mkdir backup 2>/dev/null; for f in $(file -i *.htm | grep -i us-ascii | cut -d ':' -f 1); do iconv -f "us-ascii" -t "utf-16" $f > $f.tmp; iconv -f "utf-16le" -t "utf-8" $f.tmp > $f.utf8; cp $fic backup/; mv $f.utf8 $f; rm $f.tmp; done; file -i *.htm

Should IBOutlets be strong or weak under ARC?

It looks like something has changed over the years and now Apple recommends to use strong in general. The evidence on their WWDC session is in session 407 - Implementing UI Designs in Interface Builder and starts at 32:30. My note from what he says is (almost, if not exactly, quoting him):

  • outlet connections in general should be strong especially if we connect a subview or constraint that is not always retained by the view hierarchy

  • weak outlet connection might be needed when creating custom views that has some reference to something back up in the view hierarchy and in general it is not recommended

In other wards it should be always strong now as long as some of our custom view doesn't create a retain cycle with some of the view up in the view hierarchy

EDIT :

Some may ask the question. Does keeping it with a strong reference doesn't create a retain cycle as the root view controller and the owning view keeps the reference to it? Or why that changed happened? I think the answer is earlier in this talk when they describe how the nibs are created from the xib. There is a separate nib created for a VC and for the view. I think this might be the reason why they change the recommendations. Still it would be nice to get a deeper explanation from Apple.

Angular2: How to load data before rendering the component?

A nice solution that I've found is to do on UI something like:

<div *ngIf="isDataLoaded">
 ...Your page...
</div

Only when: isDataLoaded is true the page is rendered.

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Another scenario that can cause this exception is with DataBinding, that is when you use something like this in your layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="model"
            type="point.to.your.model"/>
    </data>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@{model.someIntegerVariable}"/>

</layout>

Notice that the variable I'm using is an Integer and I'm assigning it to the text field of the TextView. Since the TextView already has a method with signature of setText(int) it will use this method instead of using the setText(String) and cast the value. Thus the TextView thinks of your input number as a resource value which obviously is not valid.

Solution is to cast your int value to string like this

android:text="@{String.valueOf(model.someIntegerVariable)}"

write a shell script to ssh to a remote machine and execute commands

There are a number of ways to handle this.

My favorite way is to install http://pamsshagentauth.sourceforge.net/ on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what's a couple more files?)

With your ssh agent forwarded, you can now log in to every system without a password.

And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user's) rights as needed.

You don't need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.

You should also look into packages like Capistrano. Definitely look around that site; it has an introduction to remote scripting.

Individual script lines might look something like this:

ssh remote-system-name command arguments ... # so, for exmaple,
ssh target.mycorp.net sudo puppet apply

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

This library adds a desiredAccuracy and maxWait option to geolocation calls, which means it will keep trying to get a position until the accuracy is within a specified range.

How to make a flat list out of list of lists?

A funny solution

import pandas as pd
list(pd.DataFrame({'lists':l})['lists'].explode())


[1, 2, 3, 4, 5, 6, 7, 8, 9]

How to export library to Jar in Android Studio?

Since Android Studio V1.0 the jar file is available inside the following project link:

debug ver: "your_app"\build\intermediates\bundles\debug\classes.jar

release ver: "your_app"\build\intermediates\bundles\release\classes.jar

The JAR file is created on the build procedure, In Android Studio GUI it's from Build->Make Project and from CMD line it's "gradlew build".

Free tool to Create/Edit PNG Images?

The GIMP (GNU Image Manipulation Program). It's free, open source and runs on Windows and Linux (and maybe Mac?).

How to get URL of current page in PHP

 $uri = $_SERVER['REQUEST_URI'];

This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.

If you need the actual file name, you might want to try either $_SERVER['PHP_SELF'], the magic constant __FILE__, or $_SERVER['SCRIPT_FILENAME']. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.

$_SERVER['PHP_SELF'] gives you the file name relative to the root of the website.

 $relative_path = $_SERVER['PHP_SELF'];
 $complete_path = __FILE__;
 $complete_path = $_SERVER['SCRIPT_FILENAME'];

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:

BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib

MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)

How to store arbitrary data for some HTML tags

Using jquery,

to store: $('#element_id').data('extra_tag', 'extra_info');

to retrieve: $('#element_id').data('extra_tag');

how to use the Box-Cox power transformation in R

According to the Box-cox transformation formula in the paper Box,George E. P.; Cox,D.R.(1964). "An analysis of transformations", I think mlegge's post might need to be slightly edited.The transformed y should be (y^(lambda)-1)/lambda instead of y^(lambda). (Actually, y^(lambda) is called Tukey transformation, which is another distinct transformation formula.)
So, the code should be:

(trans <- bc$x[which.max(bc$y)])
[1] 0.4242424
# re-run with transformation
mnew <- lm(((y^trans-1)/trans) ~ x) # Instead of mnew <- lm(y^trans ~ x) 

More information

Please correct me if I misunderstood it.

Multiple glibc libraries on a single host

This question is old, the other answers are old. "Employed Russian"s answer is very good and informative, but it only works if you have the source code. If you don't, the alternatives back then were very tricky. Fortunately nowadays we have a simple solution to this problem (as commented in one of his replies), using patchelf. All you have to do is:

$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 --set-rpath /path/to/newglibc/ myapp

And after that, you can just execute your file:

$ ./myapp

No need to chroot or manually edit binaries, thankfully. But remember to backup your binary before patching it, if you're not sure what you're doing, because it modifies your binary file. After you patch it, you can't restore the old path to interpreter/rpath. If it doesn't work, you'll have to keep patching it until you find the path that will actually work... Well, it doesn't have to be a trial-and-error process. For example, in OP's example, he needed GLIBC_2.3, so you can easily find which lib provides that version using strings:

$ strings /lib/i686/libc.so.6 | grep GLIBC_2.3
$ strings /path/to/newglib/libc.so.6 | grep GLIBC_2.3

In theory, the first grep would come empty because the system libc doesn't have the version he wants, and the 2nd one should output GLIBC_2.3 because it has the version myapp is using, so we know we can patchelf our binary using that path. If you get a segmentation fault, read the note at the end.

When you try to run a binary in linux, the binary tries to load the linker, then the libraries, and they should all be in the path and/or in the right place. If your problem is with the linker and you want to find out which path your binary is looking for, you can find out with this command:

$ readelf -l myapp | grep interpreter
  [Requesting program interpreter: /lib/ld-linux.so.2]                                                                                                                                                                                   

If your problem is with the libs, commands that will give you the libs being used are:

$ readelf -d myapp | grep Shared
$ ldd myapp 

This will list the libs that your binary needs, but you probably already know the problematic ones, since they are already yielding errors as in OP's case.

"patchelf" works for many different problems that you may encounter while trying to run a program, related to these 2 problems. For example, if you get: ELF file OS ABI invalid, it may be fixed by setting a new loader (the --set-interpreter part of the command) as I explain here. Another example is for the problem of getting No such file or directory when you run a file that is there and executable, as exemplified here. In that particular case, OP was missing a link to the loader, but maybe in your case you don't have root access and can't create the link. Setting a new interpreter would solve your problem.

Thanks Employed Russian and Michael Pankov for the insight and solution!


Note for segmentation fault: you might be in the case where myapp uses several libs, and most of them are ok but some are not; then you patchelf it to a new dir, and you get segmentation fault. When you patchelf your binary, you change the path of several libs, even if some were originally in a different path. Take a look at my example below:

$ ldd myapp
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by ./myapp)
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./myapp)
        linux-vdso.so.1 =>  (0x00007fffb167c000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9a9aad2000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9a9a8ce000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9a9a6af000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f9a9a3ab000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9a99fe6000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f9a9adeb000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9a99dcf000)

Note that most libs are in /lib/x86_64-linux-gnu/ but the problematic one (libstdc++.so.6) is on /usr/lib/x86_64-linux-gnu. After I patchelf'ed myapp to point to /path/to/mylibs, I got segmentation fault. For some reason, the libs are not totally compatible with the binary. Since myapp didn't complain about the original libs, I copied them from /lib/x86_64-linux-gnu/ to /path/to/mylibs2, and I also copied libstdc++.so.6 from /path/to/mylibs there. Then I patchelf'ed it to /path/to/mylibs2, and myapp works now. If your binary uses different libs, and you have different versions, it might happen that you can't fix your situation. :( But if it's possible, mixing libs might be the way. It's not ideal, but maybe it will work. Good luck!

Is there functionality to generate a random character in Java?

My propose for generating random string with mixed case like: "DthJwMvsTyu".
This algorithm based on ASCII codes of letters when its codes a-z (97 to 122) and A-Z (65 to 90) differs in 5th bit (2^5 or 1 << 5 or 32).

random.nextInt(2): result is 0 or 1.

random.nextInt(2) << 5: result is 0 or 32.

Upper A is 65 and lower a is 97. Difference is only on 5th bit (32) so for generating random char we do binary OR '|' random charCaseBit (0 or 32) and random code from A to Z (65 to 90).

public String fastestRandomStringWithMixedCase(int length) {
    Random random = new Random();
    final int alphabetLength = 'Z' - 'A' + 1;
    StringBuilder result = new StringBuilder(length);
    while (result.length() < length) {
        final char charCaseBit = (char) (random.nextInt(2) << 5);
        result.append((char) (charCaseBit | ('A' + random.nextInt(alphabetLength))));
    }
    return result.toString();
}

Should URL be case sensitive?

Consider the following:

https://www.example.com/createuser.php?name=Paul%20McCartney

In this hypothetical example, an HTML form - using the GET method - sends the "name" parameter to a PHP script that creates a new user account.

And the point I'm making with this example is that this GET parameter needs to be case-sensitive to preserve the capitalisation of "McCartney" (or, as another example, to preserve "Walter d'Isney", as there are other ways for names to break the usual capitalisation rules).

It's cases like these which guides the W3C recommendation that scheme and host are case insensitive, but everything after that is potentially case sensitive - and is left up to the server. Forcing case insensitivity by standard would make the above example incapable of preserving the case of user input passed as a GET query parameter.

But what I'd say is that though this is necessarily the letter of the law to accommodate such cases, the spirit of the law is that, where case is irrelevant, behave in a case insensitive way. The standards, though, can't tell you where case is irrelevant because, like the examples I've given, it's a context-dependent thing.

(e.g. an account username is probably best forced to case insensitivity - as "User123" and "user123" being different accounts could prove confusing - even if their real name, as above, is best left case sensitive.)

Sometimes it's relevant, most times it isn't. But it has to be left up to the server / web developer to decide these things - and can't be prescribed by standard - as only at that level could the context be known.

The scheme and host are case insensitive (which shows the standard's preference for case insensitivity, where it can be universally prescribed). The rest is left up to you to decide, as you understand the context better. But, as has been discussed, you probably should, in the spirit of the law, default to case insensitivity unless you have a good reason not to.

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

How to put labels over geom_bar in R with ggplot2

To plot text on a ggplot you use the geom_text. But I find it helpful to summarise the data first using ddply

dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)

Since the data is pre-summarized, you need to remember to change add the stat="identity" parameter to geom_bar:

ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
    geom_text(aes(label=y), vjust=0) +
    opts(axis.text.x=theme_blank(),
        axis.ticks=theme_blank(),
        axis.title.x=theme_blank(),
        legend.title=theme_blank(),
        axis.title.y=theme_blank()
)

enter image description here

Test if a vector contains a given element

I will group the options based on output. Assume the following vector for all the examples.

v <- c('z', 'a','b','a','e')

For checking presence:

%in%

> 'a' %in% v
[1] TRUE

any()

> any('a'==v)
[1] TRUE

is.element()

> is.element('a', v)
[1] TRUE

For finding first occurance:

match()

> match('a', v)
[1] 2

For finding all occurances as vector of indices:

which()

> which('a' == v)
[1] 2 4

For finding all occurances as logical vector:

==

> 'a' == v
[1] FALSE  TRUE FALSE  TRUE FALSE

Edit: Removing grep() and grepl() from the list for reason mentioned in comments

How to use a variable from a cursor in the select statement of another cursor in pl/sql

Use alter session set current_schema = <username>, in your case as an execute immediate.

See Oracle's documentation for further information.

In your case, that would probably boil down to (untested)

DECLARE

   CURSOR client_cur IS
     SELECT  distinct username 
       from all_users 
      where length(username) = 3;

   -- client cursor 
   CURSOR emails_cur IS
   SELECT id, name 
     FROM org;

BEGIN

   FOR client IN client_cur LOOP

   -- ****
      execute immediate 
     'alter session set current_schema = ' || client.username;
   -- ****

      FOR email_rec in client_cur LOOP

         dbms_output.put_line(
             'Org id is ' || email_rec.id || 
             ' org nam '  || email_rec.name);

      END LOOP;

  END LOOP;
END;
/

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

Hibernate tries to insert data that violate underlying database integrity contraints.

There's probably misconfiguration in hibernate persistent classes and/or mapping configuration (*.hbm.xml or annotations in persitent classes).

Maybe a property of the bean you want to save is not type-compatible with its related field in database (could explain the constraint [numbering] part).

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

UIImageView aspect fit and center

Swift

yourImageView.contentMode = .center

You can use the following options to position your image:

  • scaleToFill
  • scaleAspectFit // contents scaled to fit with fixed aspect. remainder is transparent
  • redraw // redraw on bounds change (calls -setNeedsDisplay)
  • center // contents remain same size. positioned adjusted.
  • top
  • bottom
  • left
  • right
  • topLeft
  • topRight
  • bottomLeft
  • bottomRight

How to copy text programmatically in my Android app?

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
if (clipboard == null || clip == null)
    return;
clipboard.setPrimaryClip(clip);

And import import android.content.ClipboardManager;

In a bootstrap responsive page how to center a div

CSS:

html,
body {
    height: 100%;
}

.container {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

HTML:

<div class="container">
  <div>
    example
  </div>
</div>

Example fiddle

Postfix is installed but how do I test it?

To check whether postfix is running or not

sudo postfix status

If it is not running, start it.

sudo postfix start

Then telnet to localhost port 25 to test the email id

ehlo localhost
mail from: root@localhost
rcpt to: your_email_id
data
Subject: My first mail on Postfix

Hi,
Are you there?
regards,
Admin
.

Do not forget the . at the end, which indicates end of line

Get enum values as List of String in Java 8

You can do (pre-Java 8):

List<Enum> enumValues = Arrays.asList(Enum.values());

or

List<Enum> enumValues = new ArrayList<Enum>(EnumSet.allOf(Enum.class));

Using Java 8 features, you can map each constant to its name:

List<String> enumNames = Stream.of(Enum.values())
                               .map(Enum::name)
                               .collect(Collectors.toList());

CSS background-image-opacity?

Try this trick .. use css shadow with (inset) option and make the deep 200px for example

Code:

box-shadow: inset 0px 0px 277px 3px #4c3f37;

.

Also for all browsers:

-moz-box-shadow: inset 0px 0px 47px 3px #4c3f37;
-webkit-box-shadow: inset 0px 0px 47px 3px #4c3f37;
box-shadow: inset 0px 0px 277px 3px #4c3f37;

and increase number to make fill your box :)

Enjoy!

Remove decimal values using SQL query

As I understand your question, You have one table with column as datatype decimal(18,9). And the column contains the data as follows:-

12.00
15.00
18.00
20.00

Now if you want to show record on UI without decimal value means like (12,15,18,20) then there are two options:-

  1. Either cast this column as int in Select Clause
  2. or may be you want to update this column value like (12,15,18,20).

To apply, First very simple just use the cast in select clause

select CAST(count AS INT) from tablename;

But if you want to update your column data with int value then you have to update you column datatype

and to do that

ALTER TABLE tablename ALTER COLUMN columnname decimal(9,0)

Then execute this

UPDATE tablename
   SET count = CAST(columnname AS INT)

How to solve '...is a 'type', which is not valid in the given context'? (C#)

You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();

Redirecting a page using Javascript, like PHP's Header->Location

You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)

You can use window.location to change your current page.

$('.entry a:first').click(function() {
    window.location = "http://google.ca";
});

What does the colon (:) operator do?

You usually see it in the ternary assignment operator;

Syntax

variable =  `condition ? result 1 : result 2;`

example:

boolean isNegative = number > 0 ? false : true;

which is "equivalent" in nature to the if else

if(number > 0){
    isNegative = false;
}
else{
    isNegative = true;
}

Other than examples given by different posters,

you can also use : to signify a label for a block which you can use in conjunction with continue and break..

for example:

public void someFunction(){
     //an infinite loop
     goBackHere: { //label
          for(int i = 0; i < 10 ;i++){
               if(i == 9 ) continue goBackHere;
          }
     }
}

Use RSA private key to generate public key?

My answer below is a bit lengthy, but hopefully it provides some details that are missing in previous answers. I'll start with some related statements and finally answer the initial question.

To encrypt something using RSA algorithm you need modulus and encryption (public) exponent pair (n, e). That's your public key. To decrypt something using RSA algorithm you need modulus and decryption (private) exponent pair (n, d). That's your private key.

To encrypt something using RSA public key you treat your plaintext as a number and raise it to the power of e modulus n:

ciphertext = ( plaintext^e ) mod n

To decrypt something using RSA private key you treat your ciphertext as a number and raise it to the power of d modulus n:

plaintext = ( ciphertext^d ) mod n

To generate private (d,n) key using openssl you can use the following command:

openssl genrsa -out private.pem 1024

To generate public (e,n) key from the private key using openssl you can use the following command:

openssl rsa -in private.pem -out public.pem -pubout

To dissect the contents of the private.pem private RSA key generated by the openssl command above run the following (output truncated to labels here):

openssl rsa -in private.pem -text -noout | less

modulus         - n
privateExponent - d
publicExponent  - e
prime1          - p
prime2          - q
exponent1       - d mod (p-1)
exponent2       - d mod (q-1)
coefficient     - (q^-1) mod p

Shouldn't private key consist of (n, d) pair only? Why are there 6 extra components? It contains e (public exponent) so that public RSA key can be generated/extracted/derived from the private.pem private RSA key. The rest 5 components are there to speed up the decryption process. It turns out that by pre-computing and storing those 5 values it is possible to speed the RSA decryption by the factor of 4. Decryption will work without those 5 components, but it can be done faster if you have them handy. The speeding up algorithm is based on the Chinese Remainder Theorem.

Yes, private.pem RSA private key actually contains all of those 8 values; none of them are generated on the fly when you run the previous command. Try running the following commands and compare output:

# Convert the key from PEM to DER (binary) format
openssl rsa -in private.pem -outform der -out private.der

# Print private.der private key contents as binary stream
xxd -p private.der

# Now compare the output of the above command with output 
# of the earlier openssl command that outputs private key
# components. If you stare at both outputs long enough
# you should be able to confirm that all components are
# indeed lurking somewhere in the binary stream
openssl rsa -in private.pem -text -noout | less

This structure of the RSA private key is recommended by the PKCS#1 v1.5 as an alternative (second) representation. PKCS#1 v2.0 standard excludes e and d exponents from the alternative representation altogether. PKCS#1 v2.1 and v2.2 propose further changes to the alternative representation, by optionally including more CRT-related components.

To see the contents of the public.pem public RSA key run the following (output truncated to labels here):

openssl rsa -in public.pem -text -pubin -noout

Modulus             - n
Exponent (public)   - e

No surprises here. It's just (n, e) pair, as promised.

Now finally answering the initial question: As was shown above private RSA key generated using openssl contains components of both public and private keys and some more. When you generate/extract/derive public key from the private key, openssl copies two of those components (e,n) into a separate file which becomes your public key.

What is this spring.jpa.open-in-view=true property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I find I have started having this issue with Lion + Xcode 4.2. I have also experienced the issue in Xcode 4.3.

I have tried all the suggestions but none of them have worked other than a full reboot.

Here is how you determine if you require a reboot quickly.

List out all your Zombie processes:

ps -el | grep 'Z'

If you see your app listed as a Zombie process you will need to reboot your machine. The error message states "This generally means that another instance of this process was already running or is hung in the debugger". Well, Xcode is detecting this Zombie process which you can't kill. The only way you can then fix it is with a system reboot. :(

EDIT, 20120823: I have some better knowledge of Zombie processes so I wanted to update this answer. A Zombie process is created when a parent process does not call wait() (wait for process to change state) on a terminating child process. You can't run 'kill' directly on a Zombie process but if you kill the parent process, the zombie child process will be 'reaped' and removed from the process table.

I haven't seen this issue in a long while so haven't inspected to see what the parent process is in this scenario. The alternative to killing the parent process is to reboot your system. :)

Laravel migration default value

Put the default value in single quote and it will work as intended. An example of migration:

$table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->string('country');
            $table->tinyInteger('status')->default('1');
            $table->timestamps();

EDIT : in your case ->default('100.0');

How to write and read a file with a HashMap?

HashMap implements Serializable so you can use normal serialization to write hashmap to file

Here is the link for Java - Serialization example

What's the difference between deadlock and livelock?

All the content and examples here are from

Operating Systems: Internals and Design Principles
William Stallings
8º Edition

Deadlock: A situation in which two or more processes are unable to proceed because each is waiting for one the others to do something.

For example, consider two processes, P1 and P2, and two resources, R1 and R2. Suppose that each process needs access to both resources to perform part of its function. Then it is possible to have the following situation: the OS assigns R1 to P2, and R2 to P1. Each process is waiting for one of the two resources. Neither will release the resource that it already owns until it has acquired the other resource and performed the function requiring both resources. The two processes are deadlocked

Livelock: A situation in which two or more processes continuously change their states in response to changes in the other process(es) without doing any useful work:

Starvation: A situation in which a runnable process is overlooked indefinitely by the scheduler; although it is able to proceed, it is never chosen.

Suppose that three processes (P1, P2, P3) each require periodic access to resource R. Consider the situation in which P1 is in possession of the resource, and both P2 and P3 are delayed, waiting for that resource. When P1 exits its critical section, either P2 or P3 should be allowed access to R. Assume that the OS grants access to P3 and that P1 again requires access before P3 completes its critical section. If the OS grants access to P1 after P3 has finished, and subsequently alternately grants access to P1 and P3, then P2 may indefinitely be denied access to the resource, even though there is no deadlock situation.

APPENDIX A - TOPICS IN CONCURRENCY

Deadlock Example

If both processes set their flags to true before either has executed the while statement, then each will think that the other has entered its critical section, causing deadlock.

/* PROCESS 0 */
flag[0] = true;            // <- get lock 0
while (flag[1])            // <- is lock 1 free?
    /* do nothing */;      // <- no? so I wait 1 second, for example
                           // and test again.
                           // on more sophisticated setups we can ask
                           // to be woken when lock 1 is freed
/* critical section*/;     // <- do what we need (this will never happen)
flag[0] = false;           // <- releasing our lock

 /* PROCESS 1 */
flag[1] = true;
while (flag[0])
    /* do nothing */;
/* critical section*/;
flag[1] = false;

Livelock Example

/* PROCESS 0 */
flag[0] = true;          // <- get lock 0
while (flag[1]){         
    flag[0] = false;     // <- instead of sleeping, we do useless work
                         //    needed by the lock mechanism
    /*delay */;          // <- wait for a second
    flag[0] = true;      // <- and restart useless work again.
}
/*critical section*/;    // <- do what we need (this will never happen)
flag[0] = false; 

/* PROCESS 1 */
flag[1] = true;
while (flag[0]) {
    flag[1] = false;
    /*delay */;
    flag[1] = true;
}
/* critical section*/;
flag[1] = false;

[...] consider the following sequence of events:

  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.
  • P0 checks flag[1].
  • P1 checks flag[0].
  • P0 sets flag[0] to false.
  • P1 sets flag[1] to false.
  • P0 sets flag[0] to true.
  • P1 sets flag[1] to true.

This sequence could be extended indefinitely, and neither process could enter its critical section. Strictly speaking, this is not deadlock, because any alteration in the relative speed of the two processes will break this cycle and allow one to enter the critical section. This condition is referred to as livelock. Recall that deadlock occurs when a set of processes wishes to enter their critical sections but no process can succeed. With livelock, there are possible sequences of executions that succeed, but it is also possible to describe one or more execution sequences in which no process ever enters its critical section.

Not content from the book anymore.

And what about spinlocks?

Spinlock is a technique to avoid the cost of the OS lock mechanism. Typically you would do:

try
{
   lock = beginLock();
   doSomething();
}
finally
{
   endLock();
}

A problem start to appear when beginLock() costs much more than doSomething(). In very exagerated terms, imagine what happens when the beginLock costs 1 second, but doSomething cost just 1 millisecond.

In this case if you waited 1 millisecond, you would avoid being hindered for 1 second.

Why the beginLock would cost so much? If the lock is free is does not cost a lot (see https://stackoverflow.com/a/49712993/5397116), but if the lock is not free the OS will "freeze" your thread, setup a mechanism to wake you when the lock is freed, and then wake you again in the future.

All of this is much more expensive than some loops checking the lock. That is why sometimes is better to do a "spinlock".

For example:

void beginSpinLock(lock)
{
   if(lock) loopFor(1 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   if(lock) loopFor(2 milliseconds);
   else 
   {
     lock = true;
     return;
   }

   // important is that the part above never 
   // cause the thread to sleep.
   // It is "burning" the time slice of this thread.
   // Hopefully for good.

   // some implementations fallback to OS lock mechanism
   // after a few tries
   if(lock) return beginLock(lock);
   else 
   {
     lock = true;
     return;
   }
}

If your implementation is not careful, you can fall on livelock, spending all CPU on the lock mechanism.

Also see:

https://preshing.com/20120226/roll-your-own-lightweight-mutex/
Is my spin lock implementation correct and optimal?

Summary:

Deadlock: situation where nobody progress, doing nothing (sleeping, waiting etc..). CPU usage will be low;

Livelock: situation where nobody progress, but CPU is spent on the lock mechanism and not on your calculation;

Starvation: situation where one procress never gets the chance to run; by pure bad luck or by some of its property (low priority, for example);

Spinlock: technique of avoiding the cost waiting the lock to be freed.

Oracle : how to subtract two dates and get minutes of the result

For those who want to substrat two timestamps (instead of dates), there is a similar solution:

SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 1440 AS minutesInBetween
FROM ...

or

SELECT ( CAST( date2 AS DATE ) - CAST( date1 AS DATE ) ) * 86400 AS secondsInBetween
FROM ...

Manage toolbar's navigation and back button from fragment in android

First you add the Navigation back button

   getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

Then, add the Method in your HostActivity.

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==android.R.id.home)
    {
        super.onBackPressed();
        Toast.makeText(this, "OnBAckPressed Works", Toast.LENGTH_SHORT).show();
    }

    return super.onOptionsItemSelected(item);
}

Try this, definitely work.

how to get multiple checkbox value using jquery

$('input:checked').map(function(i, e) {return e.value}).toArray();

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

Format y axis as percent

Based on the answer of @erwanp, you can use the formatted string literals of Python 3,

x = '2'
percentage = f'{x}%' # 2%

inside the FuncFormatter() and combined with a lambda expression.

All wrapped:

ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f'{y}%'))

Cannot find pkg-config error

for me, (OSX) the problem was solved doing this:

brew install pkg-config

How to set UTF-8 encoding for a PHP file

You have to specify what encoding the data is. Either in meta or in headers

header('Content-Type: text/plain; charset=utf-8');

How to cut a string after a specific character in unix

You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

Parameter Expansion

...

${parameter#word}

Remove Smallest Prefix Pattern.
The word is expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

In other words, you can write

$var="${var#*:}"

which will remove anything matching *: from $var (i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ## in place of #.

This is all assuming that the part to remove does not contain : (true for IPv4 addresses, but not for IPv6 addresses)

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-one: Use a foreign key to the referenced table:

student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
                                                        # "link back" if you need

You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating to the same row in the referenced table (student).

One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:

teachers: teacher_id, first_name, last_name # the "one" side
classes:  class_id, class_name, teacher_id  # the "many" side

Many-to-many: Use a junction table (example):

student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id     # the junction table

Example queries:

 -- Getting all students for a class:

    SELECT s.student_id, last_name
      FROM student_classes sc 
INNER JOIN students s ON s.student_id = sc.student_id
     WHERE sc.class_id = X

 -- Getting all classes for a student: 

    SELECT c.class_id, name
      FROM student_classes sc 
INNER JOIN classes c ON c.class_id = sc.class_id
     WHERE sc.student_id = Y

How to change the floating label color of TextInputLayout

how do I change the floating label text color?

With the Material Components library you can customize the TextInputLayout the hint text color using (it requires the version 1.1.0)

  • In the layout:

  • app:hintTextColor attribute : the color of the label when it is collapsed and the text field is active

  • android:textColorHint attribute: the color of the label in all other text field states (such as resting and disabled)

<com.google.android.material.textfield.TextInputLayout
     app:hintTextColor="@color/mycolor"
     android:textColorHint="@color/text_input_hint_selector"
     .../>
  • extending a material style Widget.MaterialComponents.TextInputLayout.*:
<style name="MyFilledBox" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
    <item name="hintTextColor">@color/mycolor</item>
    <item name="android:textColorHint">@color/text_input_hint_selector</item>
</style>

enter image description hereenter image description here

The default selector for android:textColorHint is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:alpha="0.38" android:color="?attr/colorOnSurface" android:state_enabled="false"/>
  <item android:alpha="0.6" android:color="?attr/colorOnSurface"/>
</selector>

MySQL InnoDB not releasing disk space after deleting data rows from table

Year back i also faced same problem on mysql5.7 version and ibdata1 occupied 150 Gb. so i added undo tablespaces

Take Mysqldump backup
Stop mysql service
Remove all data from data dir
Add below undo tablespace parameter in current my.cnf

 #undo tablespace
  innodb_undo_directory =  /var/lib/mysql/
  innodb_rollback_segments = 128 
  innodb_undo_tablespaces = 3
  innodb_undo_logs = 128  
  innodb_max_undo_log_size=1G
  innodb_undo_log_truncate = ON

Start mysql service
store mysqldump backup

Problem resolved !!

Drawing rotated text on a HTML5 canvas

Here's an HTML5 alternative to homebrew: http://www.rgraph.net/ You might be able to reverse engineer their methods....

You might also consider something like Flot (http://code.google.com/p/flot/) or GCharts: (http://www.maxb.net/scripts/jgcharts/include/demo/#1) It's not quite as cool, but fully backwards compatible and scary easy to implement.

How to make my layout able to scroll down?

If you even did not get scroll after doing what is written above .....

Set the android:layout_height="250dp"or you can say xdp where x can be any numerical value.

window.location (JS) vs header() (PHP) for redirection

A better way to set the location in JS is via:

window.location.href = 'https://stackoverflow.com';

Whether to use PHP or JS to manage the redirection depends on what your code is doing and how. But if you're in a position to use PHP; that is, if you're going to be using PHP to send some JS code back to the browser that simply tells the browser to go somewhere else, then logic suggests that you should cut out the middle man and tell the browser directly via PHP.

Windows Scheduled task succeeds but returns result 0x1

I was running a PowerShell script into the task scheduller but i forgot to enable the execution-policy to unrestricted, in an elevated PowerShell console:

Set-ExecutionPolicy Unrestricted

After that, the error disappeared (0x1).

Support for the experimental syntax 'classProperties' isn't currently enabled

Solution for webpack project

I just solve this problem by adding @babel/plugin-proposal-class-properties into webpack config plugin. The module section of my webpack.config.js looks like this

module: {
    rules: [
        {
            test: path.join(__dirname, '.'),
            exclude: /(node_modules)/,
            loader: 'babel-loader',
            options: {
                presets: ['@babel/preset-env',
                          '@babel/react',{
                          'plugins': ['@babel/plugin-proposal-class-properties']}]
            }
        }
    ]
}

Serializing PHP object to JSON

Try using this, this worked fine for me.

json_encode(unserialize(serialize($array)));

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

Calculate the display width of a string in Java

It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.

I have tested this in a web servlet and it does calculate the text width.

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

...

String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());

Add the necessary values to these dimensions to create any required margin.

Setting up Vim for Python

For those arriving around summer 2013, I believe some of this thread is outdated.

I followed this howto which recommends Vundle over Pathogen. After one days use I found installing plugins trivial.

The klen/python-mode plugin deserves special mention. It provides pyflakes and pylint amongst other features.

I have just started using Valloric/YouCompleteMe and I love it. It has C-lang auto-complete and python also works great thanks to jedi integration. It may well replace jedi-vim as per this discussion /davidhalter/jedi-vim/issues/119

Finally browsing the /carlhuda/janus plugins supplied is a good guide to useful scripts you might not know you are looking for such as NerdTree, vim-fugitive, syntastic, powerline, ack.vim, snipmate...

All the above '{}/{}' are found on github you can find them easily with Google.

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

How to obtain image size using standard Python class (without using external library)?

If you happen to have ImageMagick installed, then you can use 'identify'. For example, you can call it like this:

path = "//folder/image.jpg"
dim = subprocess.Popen(["identify","-format","\"%w,%h\"",path], stdout=subprocess.PIPE).communicate()[0]
(width, height) = [ int(x) for x in re.sub('[\t\r\n"]', '', dim).split(',') ]

TSQL Default Minimum DateTime

As far as I am aware no function exists to return this, you will have to hard set it.

Attempting to cast from values such as 0 to get a minimum date will default to 01-01-1900.

As suggested previously best left set to NULL (and use ISNULL when reading if you need to), or if you are worried about setting it correctly you could even set a trigger on the table to set your modified date on edits.

If you have your heart set on getting the minimum possible date then:

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT '1753-01-01'
)

Injecting @Autowired private field during testing

The accepted answer (use MockitoJUnitRunner and @InjectMocks) is great. But if you want something a little more lightweight (no special JUnit runner), and less "magical" (more transparent) especially for occasional use, you could just set the private fields directly using introspection.

If you use Spring, you already have a utility class for this : org.springframework.test.util.ReflectionTestUtils

The use is quite straightforward :

ReflectionTestUtils.setField(myLauncher, "myService", myService);

The first argument is your target bean, the second is the name of the (usually private) field, and the last is the value to inject.

If you don't use Spring, it is quite trivial to implement such a utility method. Here is the code I used before I found this Spring class :

public static void setPrivateField(Object target, String fieldName, Object value){
        try{
            Field privateField = target.getClass().getDeclaredField(fieldName);
            privateField.setAccessible(true);
            privateField.set(target, value);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

Where does SVN client store user authentication data?

Which version do you use?

Here is the documentation on credential caching, for the latest (1.6 as of writing).

On Windows, the Subversion client stores passwords in the %APPDATA%/Subversion/auth/ directory. On Windows 2000 and later, the standard Windows cryptography services are used to encrypt the password on disk. Because the encryption key is managed by Windows and is tied to the user's own login credentials, only the user can decrypt the cached password. (Note that if the user's Windows account password is reset by an administrator, all of the cached passwords become undecipherable. The Subversion client will behave as though they don't exist, prompting for passwords when required.)

Also, be aware that a few changes occurred in version 1.6 regarding password storage.

Finish an activity from another activity

That you can do, but I think you should not break the normal flow of activity. If you want to finish you activity then you can simply send a broadcast from your activity B to activity A.

Create a broadcast receiver before starting your activity B:

BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equals("finish_activity")) {
            finish();
            // DO WHATEVER YOU WANT.
        }
    }
};
registerReceiver(broadcastReceiver, new IntentFilter("finish_activity"));

Send broadcast from activity B to activity A when you want to finish activity A from B

Intent intent = new Intent("finish_activity");
sendBroadcast(intent);

I hope it will work for you...

How do I get the size of a java.sql.ResultSet?

Do a SELECT COUNT(*) FROM ... query instead.

OR

int size =0;
if (rs != null) 
{
  rs.last();    // moves cursor to the last row
  size = rs.getRow(); // get row id 
}

In either of the case, you won't have to loop over the entire data.

multiple axis in matplotlib with different scales

Bootstrapping something fast to chart multiple y-axes sharing an x-axis using @joe-kington's answer: enter image description here

# d = Pandas Dataframe, 
# ys = [ [cols in the same y], [cols in the same y], [cols in the same y], .. ] 
def chart(d,ys):

    from itertools import cycle
    fig, ax = plt.subplots()

    axes = [ax]
    for y in ys[1:]:
        # Twin the x-axis twice to make independent y-axes.
        axes.append(ax.twinx())

    extra_ys =  len(axes[2:])

    # Make some space on the right side for the extra y-axes.
    if extra_ys>0:
        temp = 0.85
        if extra_ys<=2:
            temp = 0.75
        elif extra_ys<=4:
            temp = 0.6
        if extra_ys>5:
            print 'you are being ridiculous'
        fig.subplots_adjust(right=temp)
        right_additive = (0.98-temp)/float(extra_ys)
    # Move the last y-axis spine over to the right by x% of the width of the axes
    i = 1.
    for ax in axes[2:]:
        ax.spines['right'].set_position(('axes', 1.+right_additive*i))
        ax.set_frame_on(True)
        ax.patch.set_visible(False)
        ax.yaxis.set_major_formatter(matplotlib.ticker.OldScalarFormatter())
        i +=1.
    # To make the border of the right-most axis visible, we need to turn the frame
    # on. This hides the other plots, however, so we need to turn its fill off.

    cols = []
    lines = []
    line_styles = cycle(['-','-','-', '--', '-.', ':', '.', ',', 'o', 'v', '^', '<', '>',
               '1', '2', '3', '4', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd', '|', '_'])
    colors = cycle(matplotlib.rcParams['axes.color_cycle'])
    for ax,y in zip(axes,ys):
        ls=line_styles.next()
        if len(y)==1:
            col = y[0]
            cols.append(col)
            color = colors.next()
            lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
            ax.set_ylabel(col,color=color)
            #ax.tick_params(axis='y', colors=color)
            ax.spines['right'].set_color(color)
        else:
            for col in y:
                color = colors.next()
                lines.append(ax.plot(d[col],linestyle =ls,label = col,color=color))
                cols.append(col)
            ax.set_ylabel(', '.join(y))
            #ax.tick_params(axis='y')
    axes[0].set_xlabel(d.index.name)
    lns = lines[0]
    for l in lines[1:]:
        lns +=l
    labs = [l.get_label() for l in lns]
    axes[0].legend(lns, labs, loc=0)

    plt.show()

How can I use external JARs in an Android project?

Copying the .jar file into the Android project's folder isn't always possible.
Especially if it's an output of another project in your workspace, and it keeps getting updated.

To solve this you'll have to add the jar as a linked file to your project, instead of importing it (which will copy it locally).

In the UI choose:

Project -> Import -> File System -> yourjar.jar -> (Options area) Advanced -> Create link in workspace.

The link is save in the .project file:

<linkedResources>
    <link>
        <name>yourjar.jar</name>
        <type>1</type>
        <locationURI>PARENT-5-PROJECT_LOC/bin/android_ndk10d_armeabi-v7a/yourjar.jar</locationURI>
    </link>
</linkedResources>

PARENT-5-PROJECT_LOC means relative to the project file, 5 directories up (../../../../../).

Then add it to the libraries:
Project -> Properties -> Java Build Path -> Libraries -> Add Jar -> yourjar.jar

In the same window choose the Order and Export tab and mark your jar so it will be added to the apk.

What are named pipes?

Unix and Windows both have things called "Named pipes", but they behave differently. On Unix, a named pipe is a one-way street which typically has just one reader and one writer - the writer writes, and the reader reads, you get it?

On Windows, the thing called a "Named pipe" is an IPC object more like a TCP socket - things can flow both ways and there is some metadata (You can obtain the credentials of the thing on the other end etc).

Unix named pipes appear as a special file in the filesystem and can be accessed with normal file IO commands including the shell. Windows ones don't, and need to be opened with a special system call (after which they behave mostly like a normal win32 handle).

Even more confusing, Unix has something called a "Unix socket" or AF_UNIX socket, which works more like (but not completely like) a win32 "named pipe", being bidirectional.

How do you do dynamic / dependent drop downs in Google Sheets?

You can start with a google sheet set up with a main page and drop down source page like shown below.

You can set up the first column drop down through the normal Data > Validations menu prompts.

Main Page

Main Page with the drop down for the first column already populated.

Drop Down Source Page

Source page for all of the sub-categories needed

After that, you need to set up a script with the name onEdit. (If you don't use that name, the getActiveRange() will do nothing but return cell A1)

And use the code provided here:

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  var myRange = SpreadsheetApp.getActiveRange();
  var dvSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Categories");
  var option = new Array();
  var startCol = 0;

  if(sheet.getName() == "Front Page" && myRange.getColumn() == 1 && myRange.getRow() > 1){
    if(myRange.getValue() == "Category 1"){
      startCol = 1;
    } else if(myRange.getValue() == "Category 2"){
      startCol = 2;
    } else if(myRange.getValue() == "Category 3"){
      startCol = 3;
    } else if(myRange.getValue() == "Category 4"){
      startCol = 4;
    } else {
      startCol = 10
    }

  if(startCol > 0 && startCol < 10){
    option = dvSheet.getSheetValues(3,startCol,10,1);
    var dv = SpreadsheetApp.newDataValidation();
    dv.setAllowInvalid(false);  
    //dv.setHelpText("Some help text here");
    dv.requireValueInList(option, true);
    sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).setDataValidation(dv.build());
   }

  if(startCol == 10){
    sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).clearDataValidations();
  } 
  }
}

After that, set up a trigger in the script editor screen by going to Edit > Current Project Triggers. This will bring up a window to have you select various drop downs to eventually end up at this:

Trigger set up

You should be good to go after that!

AngularJS - add HTML element to dom in directive without jQuery

You could use something like this

var el = document.createElement("svg");
el.style.width="600px";
el.style.height="100px";
....
iElement[0].appendChild(el)

"Could not get any response" response when using postman with subdomain

For me the issue was that the Content-Length was too big. I placed the content of the body in NotePad++ and counted the characters and put that figure in PostMan and then it worked.

I know it does not directly answer why the op's sub-domain was not working but it might help out someone.

Set background image according to screen resolution

Delete your "body background image code" then paste this code:

html { 
    background: url(../img/background.jpg) no-repeat center center fixed #000; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Calculate number of hours between 2 dates in PHP

Carbon could also be a nice way to go.

From their website:

A simple PHP API extension for DateTime. http://carbon.nesbot.com/

Example:

use Carbon\Carbon;

//...

$day1 = Carbon::createFromFormat('Y-m-d H:i:s', '2006-04-12 12:30:00');
$day2 = Carbon::createFromFormat('Y-m-d H:i:s', '2006-04-14 11:30:00');

echo $day1->diffInHours($day2); // 47

//...

Carbon extends the DateTime class to inherit methods including diff(). It adds nice sugars like diffInHours, diffInMintutes, diffInSeconds e.t.c.

How to change maven java home

Just set JAVA_HOME env property.

Moving up one directory in Python

Although this is not exactly what OP meant as this is not super simple, however, when running scripts from Notepad++ the os.getcwd() method doesn't work as expected. This is what I would do:

import os

# get real current directory (determined by the file location)
curDir, _ = os.path.split(os.path.abspath(__file__))

print(curDir) # print current directory

Define a function like this:

def dir_up(path,n): # here 'path' is your path, 'n' is number of dirs up you want to go
    for _ in range(n):
        path = dir_up(path.rpartition("\\")[0], 0) # second argument equal '0' ensures that 
                                                        # the function iterates proper number of times
    return(path)

The use of this function is fairly simple - all you need is your path and number of directories up.

print(dir_up(curDir,3)) # print 3 directories above the current one

The only minus is that it doesn't stop on drive letter, it just will show you empty string.

Remote desktop connection protocol error 0x112f

If the server accessible with RPC (basically, if you can access a shared folder on it), you could free some memory and thus let the RDP service work properly. The following windows native commands can be used:

To get the list of memory consuming tasks:

tasklist /S <remote_server> /V /FI "MEMUSAGE gt 10000"

To kill a task by its name:

taskkill /S <remote_server> /IM <process_image_name> /F

To show the list of desktop sessions:

qwinsta.exe /SERVER:<remote_server>

To close an old abandoned desktop session:

logoff <session_id> /SERVER:<remote_server> 

After some memory is freed, the RDP should start working.

What is a "bundle" in an Android application

A Bundle is very much like a Java Map object that maps String keys to values. It's used to pass information between activities and other application components. It's also used by the framework to capture and restore state information.

The reason Android doesn't use plain old Map objects for this is that Map is too flexible; it can contain objects (such as, say, I/O streams) that cannot be serialized. The Bundle API restricts the types of objects that can be added to a bundle in such a way that the bundle's contents are guaranteed to be serializable. The Android framework relies on this property.

I suggest that you read the documentation on Application Fundamentals. This explains, among other things, what bundles and intents are and what they are used for.

java.io.FileNotFoundException: (Access is denied)

You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

How to apply a function to two columns of Pandas dataframe

A interesting question! my answer as below:

import pandas as pd

def sublst(row):
    return lst[row['J1']:row['J2']]

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(sublst,axis=1)
print df

Output:

  ID  J1  J2
0  1   0   1
1  2   2   4
2  3   3   5
  ID  J1  J2      J3
0  1   0   1     [a]
1  2   2   4  [c, d]
2  3   3   5  [d, e]

I changed the column name to ID,J1,J2,J3 to ensure ID < J1 < J2 < J3, so the column display in right sequence.

One more brief version:

import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(lambda row:lst[row['J1']:row['J2']],axis=1)
print df

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));