Programs & Examples On #Cobol

COBOL (COmmon Business Oriented Language) was the product of a US Department of Defense initiative to develop a standard and portable programming language for business applications. COBOL celebrated its 50th birthday in 2009. It is generally believed that new COBOL development is in decline but a commercial commitment remains to keep the language relevant in today’s computing landscape.

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

how to get value of selected item in autocomplete

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
    $('#tags').on('blur', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

What is the worst programming language you ever worked with?

Any language can be the worst in a right hands. And improper teamwork makes it even worse. I mean, if it's not fun enough to shot in your own foot, you can always try shooting some coworkers feet. So far the best language I've seen to do so is C++. You can really hurt colleagues brain with it.

Compare two files and write it to "match" and "nomatch" files

I had used JCL about 2 years back so cannot write a code for you but here is the idea;

  1. Have 2 steps
  2. First step will have ICETOOl where you can write the matching records to matched file.
  3. Second you can write a file for mismatched by using SORT/ICETOOl or by just file operations.

again i apologize for solution without code, but i am out of touch by 2 yrs+

Dealing with HTTP content in HTTPS pages

It would be best to just have the http content on https

make: *** [ ] Error 1 error

In my case there was a static variable which was not initialized. When I initialized it, the error was removed. I don't know the logic behind it but worked for me. I know its a little late but other people with similar problem might get some help.

What Language is Used To Develop Using Unity

Unity supports:
1. UnityScript(Is known as Javascript but includes more functionality for the Unity game engine. I think this could be very easy to learn)
2. Boo (No experience)
3. C# (I prefer this as it is useful to learn and you will be able to use this outside of unity as well. I also think it is easy to get used to)

How do I insert non breaking space character   in a JSF page?

If your using the RichFaces library you can also use the tag rich:spacer which will add an "invisible" image with a given length and height. Usually much easier and prettier than to add tons of nbsp;.

Where you want your space to show you simply add:

<rich:spacer height="1" width="2" />

Strange PostgreSQL "value too long for type character varying(500)"

We had this same issue. We solved it adding 'length' to entity attribute definition:

@Column(columnDefinition="text", length=10485760)
private String configFileXml = ""; 

Open file dialog box in JavaScript

AFAIK you still need an <input type="file"> element, then you can use some of the stuff from quirksmode to style it up

Replace Fragment inside a ViewPager

In your onCreateView method, container is actually a ViewPager instance.

So, just calling

ViewPager vpViewPager = (ViewPager) container;
vpViewPager.setCurrentItem(1);

will change current fragment in your ViewPager.

Difference between break and continue statement

A break statement results in the termination of the statement to which it applies (switch, for, do, or while).

A continue statement is used to end the current loop iteration and return control to the loop statement.

Why is $$ returning the same id as the parent process?

Try getppid() if you want your C program to print your shell's PID.

Best way to convert an ArrayList to a string

This is quite an old conversation by now and apache commons are now using a StringBuilder internally: http://commons.apache.org/lang/api/src-html/org/apache/commons/lang/StringUtils.html#line.3045

This will as we know improve performance, but if performance is critical then the method used might be somewhat inefficient. Whereas the interface is flexible and will allow for consistent behaviour across different Collection types it is somewhat inefficient for Lists, which is the type of Collection in the original question.

I base this in that we are incurring some overhead which we would avoid by simply iterating through the elements in a traditional for loop. Instead there are some additional things happening behind the scenes checking for concurrent modifications, method calls etc. The enhanced for loop will on the other hand result in the same overhead since the iterator is used on the Iterable object (the List).

Accept function as parameter in PHP

PHP VERSION >= 5.3.0

Example 1: basic

function test($test_param, $my_function) {
    return $my_function($test_param);
}

test("param", function($param) {
    echo $param;
}); //will echo "param"

Example 2: std object

$obj = new stdClass();
$obj->test = function ($test_param, $my_function) {
    return $my_function($test_param);
};

$test = $obj->test;
$test("param", function($param) {
    echo $param;
});

Example 3: non static class call

class obj{
    public function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

$obj = new obj();
$obj->test("param", function($param) {
    echo $param;
});

Example 4: static class call

class obj {
    public static function test($test_param, $my_function) {
        return $my_function($test_param);
    }
}

obj::test("param", function($param) {
    echo $param;
});

How to edit hosts file via CMD?

Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.

Examples of using

hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost

...and many others...

Help

Usage:
    hosts - run hosts command interpreter
    hosts <command> <params> - execute hosts command

Commands:
    add  <host> <aliases> <addr> # <comment>   - add new host
    set  <host|mask> <addr> # <comment>        - set ip and comment for host
    rem  <host|mask>   - remove host
    on   <host|mask>   - enable host
    off  <host|mask>   - disable host
    view [all] <mask>  - display enabled and visible, or all hosts
    hide <host|mask>   - hide host from 'hosts view'
    show <host|mask>   - show host in 'hosts view'
    print      - display raw hosts file
    format     - format host rows
    clean      - format and remove all comments
    rollback   - rollback last operation
    backup     - backup hosts file
    restore    - restore hosts file from backup
    recreate   - empty hosts file
    open       - open hosts file in notepad

Download

https://code.google.com/p/hostscmd/downloads/list

React-Router open Link in new tab

We can use the following options:-

 // first option is:-
    <Link to="myRoute" params={myParams} target="_blank">

 // second option is:-
    var href = this.props.history.createHref('myRoute', myParams);
    <a href={href} target="_blank">

 //third option is:-
    var href = '/myRoute/' + myParams.foo + '/' + myParams.bar;
    <a href={href} target="_blank">

We can use either of three option to open in new tab by react routing.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

With CSS:

selector { cursor: none; }

An example:

_x000D_
_x000D_
<div class="nocursor">_x000D_
   Some stuff_x000D_
</div>_x000D_
<style type="text/css">_x000D_
    .nocursor { cursor:none; }_x000D_
</style>
_x000D_
_x000D_
_x000D_

To set this on an element in Javascript, you can use the style property:

<div id="nocursor"><!-- some stuff --></div>
<script type="text/javascript">
    document.getElementById('nocursor').style.cursor = 'none';
</script>

If you want to set this on the whole body:

<script type="text/javascript">
    document.body.style.cursor = 'none';
</script>

Make sure you really want to hide the cursor, though. It can really annoy people.

How do I sort a Set to a List in Java?

@Jeremy Stein I wanted to implement same code. As well I wanted to sort the set to list, So instead of using Set I converted set values into List and sort that list by it's one the variable. This code helped me,

set.stream().sorted(Comparator.comparing(ModelClassName::sortingVariableName)).collect(Collectors.toList());

How to access session variables from any class in ASP.NET?

The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

isset in jQuery?

function el(id) {
  return document.getElementById(id);
}

if (el('one') || el('two') || el('three')) { 
  alert('yes');

} else if (el('four')) {
  alert('no');
}

Close Window from ViewModel

You can create new Event handler in the ViewModel like this.

public event EventHandler RequestClose;

    protected void OnRequestClose()
    {
        if (RequestClose != null)
            RequestClose(this, EventArgs.Empty);
    }

Then Define RelayCommand for ExitCommand.

private RelayCommand _CloseCommand;
    public ICommand CloseCommand
    {
        get
        {
            if(this._CloseCommand==null)
                this._CloseCommand=new RelayCommand(CloseClick);
            return this._CloseCommand;
        }
    }

    private void CloseClick(object obj)
    {
        OnRequestClose();
    }

Then In XAML file set

<Button Command="{Binding CloseCommand}" />

Set the DataContext in the xaml.cs File and Subscribe to the event we created.

public partial class MainWindow : Window
{
    private ViewModel mainViewModel = null;
    public MainWindow()
    {
        InitializeComponent();
        mainViewModel = new ViewModel();
        this.DataContext = mainViewModel;
        mainViewModel.RequestClose += delegate(object sender, EventArgs args) { this.Close(); };
    }
}

How can I add or update a query string parameter?

Based on the answer @ellemayo gave, I came up with the following solution that allows for disabling of the hash tag if desired:

function updateQueryString(key, value, options) {
    if (!options) options = {};

    var url = options.url || location.href;
    var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;

    hash = url.split('#');
    url = hash[0];
    if (re.test(url)) {
        if (typeof value !== 'undefined' && value !== null) {
            url = url.replace(re, '$1' + key + "=" + value + '$2$3');
        } else {
            url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
        }
    } else if (typeof value !== 'undefined' && value !== null) {
        var separator = url.indexOf('?') !== -1 ? '&' : '?';
        url = url + separator + key + '=' + value;
    }

    if ((typeof options.hash === 'undefined' || options.hash) &&
        typeof hash[1] !== 'undefined' && hash[1] !== null)
        url += '#' + hash[1];
    return url;
}

Call it like this:

updateQueryString('foo', 'bar', {
    url: 'http://my.example.com#hash',
    hash: false
});

Results in:

http://my.example.com?foo=bar

jQuery make global variable

You can avoid declaration of global variables by adding them directly to the global object:

(function(global) {

  ...

  global.varName = someValue;

  ...

}(this));

A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.

You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.

Using Regular Expressions to Extract a Value in Java

Allain basically has the java code, so you can use that. However, his expression only matches if your numbers are only preceded by a stream of word characters.

"(\\d+)"

should be able to find the first string of digits. You don't need to specify what's before it, if you're sure that it's going to be the first string of digits. Likewise, there is no use to specify what's after it, unless you want that. If you just want the number, and are sure that it will be the first string of one or more digits then that's all you need.

If you expect it to be offset by spaces, it will make it even more distinct to specify

"\\s+(\\d+)\\s+"

might be better.

If you need all three parts, this will do:

"(\\D+)(\\d+)(.*)"

EDIT The Expressions given by Allain and Jack suggest that you need to specify some subset of non-digits in order to capture digits. If you tell the regex engine you're looking for \d then it's going to ignore everything before the digits. If J or A's expression fits your pattern, then the whole match equals the input string. And there's no reason to specify it. It probably slows a clean match down, if it isn't totally ignored.

In Windows cmd, how do I prompt for user input and use the result in another command?

@echo off
:start
set /p var1="Enter first number: "
pause

Polynomial time and exponential time

O(n^2) is polynomial time. The polynomial is f(n) = n^2. On the other hand, O(2^n) is exponential time, where the exponential function implied is f(n) = 2^n. The difference is whether the function of n places n in the base of an exponentiation, or in the exponent itself.

Any exponential growth function will grow significantly faster (long term) than any polynomial function, so the distinction is relevant to the efficiency of an algorithm, especially for large values of n.

Hibernate Query By Example and Projections

I do not really think so, what I can find is the word "this." causes the hibernate not to include any restrictions in its query, which means it got all the records lists. About the hibernate bug that was reported, I can see it's reported as fixed but I totally failed to download the Patch.

Get a Windows Forms control by name in C#

You can do the following:

private ToolStripMenuItem getToolStripMenuItemByName(string nameParam)
   {
      foreach (Control ctn in this.Controls)
         {
            if (ctn is ToolStripMenuItem)
               {
                   if (ctn.Name = nameParam)
                      {
                         return ctn;
                      }
                }
         }
         return null;
    }

How to start Activity in adapter?

Simple way to start activity in Adopter's button onClickListener:

Intent myIntent = new Intent(view.getContext(),Event_Member_list.class);                    myIntent.putExtra("intVariableName", eventsList.get(position).getEvent_id());
                view.getContext().startActivity(myIntent);

Storing integer values as constants in Enum manner in java

The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).

In almost all cases I suggest using an EnumMap instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).

 private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
 pageIndexes.put(Page.SIGN_CREATE, 1);
 //etc., ...

 int createIndex = pageIndexes.get(Page.SIGN_CREATE);

It's typically incredibly efficient, too.

Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.

Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap instead of ordinal indexing.

Object array initialization without default constructor

You can use placement-new like this:

class Car
{
    int _no;
public:
    Car(int no) : _no(no)
    {
    }
};

int main()
{
    void *raw_memory = operator new[](NUM_CARS * sizeof(Car));
    Car *ptr = static_cast<Car *>(raw_memory);
    for (int i = 0; i < NUM_CARS; ++i) {
        new(&ptr[i]) Car(i);
    }

    // destruct in inverse order    
    for (int i = NUM_CARS - 1; i >= 0; --i) {
        ptr[i].~Car();
    }
    operator delete[](raw_memory);

    return 0;
}

Reference from More Effective C++ - Scott Meyers:
Item 4 - Avoid gratuitous default constructors

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

ASP.NET Background image

body {
    background-image: url('../images/background.jpg');
    background-repeat: no-repeat;
    background-size: cover; /* will auto resize to fill the screen */
}

font awesome icon in select option

I recommend for you to use Jquery plugin selectBoxIt selectBoxIt

It is nice and simple, and you can change the arrow of drop down menu.

How to reference a method in javadoc?

The general format, from the @link section of the javadoc documentation, is:

{@link package.class#member label}

Examples

Method in the same class:

/** See also {@link #myMethod(String)}. */
void foo() { ... }

Method in a different class, either in the same package or imported:

/** See also {@link MyOtherClass#myMethod(String)}. */
void foo() { ... }

Method in a different package and not imported:

/** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
void foo() { ... }

Label linked to method, in plain text rather than code font:

/** See also this {@linkplain #myMethod(String) implementation}. */
void foo() { ... }

A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz(). But these labels can be fragile during refactoring -- see "Labels" below.

/**
 * A convenience method, equivalent to 
 * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
 * @return baz
 */
public Baz fooBarBaz()

Labels

Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.

Therefore, provide a label only if you want different text than the default.

For example, you might link from human language to code:

/** You can also {@linkplain #getFoo() get the current foo}. */
void setFoo( Foo foo ) { ... }

Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.

Type erasure and #member

If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:

int bar( Collection<Integer> receiver ) { ... }

/** See also {@link #bar(Collection)}. */
void foo() { ... }

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

When should I use a trailing slash in my URL?

From an SEO perspective, choosing whether or not to include a trailing slash at the end of a URL is irrelevant. These days, it is common to see examples of both on the web. A site will not be penalized either way, nor will this choice affect your website's search engine ranking or other SEO considerations.

Just choose a URL naming convention you prefer, and include a canonical meta tag in the <head> section of each webpage.

Search engines may consider a single webpage as two separate duplicate URLS when they encounter it with and without the trailing slash, ie example.com/about-us/ and example.com/about-us.

It is best practice to include a canonical meta tag on each page because you cannot control how other sites link to your URLs.

The canonical tag looks like this: <link rel="canonical" href="https://example.com/about-us" />. Using a canonical meta tag ensures that search engines only count each of your URLs once, regardless of whether other websites include a trailing slash when they link to your site.

Capturing TAB key in text box

I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.

A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?

Algorithm to generate all possible permutations of a list?

As WhirlWind said, you start at the beginning.

You swap cursor with each remaining value, including cursor itself, these are all new instances (I used an int[] and array.clone() in the example).

Then perform permutations on all these different lists, making sure the cursor is one to the right.

When there are no more remaining values (cursor is at the end), print the list. This is the stop condition.

public void permutate(int[] list, int pointer) {
    if (pointer == list.length) {
        //stop-condition: print or process number
        return;
    }
    for (int i = pointer; i < list.length; i++) {
        int[] permutation = (int[])list.clone();.
        permutation[pointer] = list[i];
        permutation[i] = list[pointer];
        permutate(permutation, pointer + 1);
    }
}

New to MongoDB Can not run command mongo

If you're using Windows 7/ 7+.

Here is something you can try.

Check if the installation is proper in CONTROL PANEL of your computer.

Now goto the directory and where you've install the MongoDB. Ideally, it would be in

C:\Program Files\MongoDB\Server\3.6\bin

Then either in the command prompt or in the IDE's terminal. Navigate to the above path ( Ideally your save file) and type

mongod --dbpath

It should work alright!

Android MediaPlayer Stop and Play

You should use only one mediaplayer object

    public class PlayaudioActivity extends Activity {

        private MediaPlayer mp;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button b = (Button) findViewById(R.id.button1);
            Button b2 = (Button) findViewById(R.id.button2);
            final TextView t = (TextView) findViewById(R.id.textView1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
                    mp.start();
                }

            });

            b2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
                    mp.start();
                }
            });
        }

        private void stopPlaying() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
           }
        }
    }

Why I can't access remote Jupyter Notebook server?

If you are still having trouble and you are running something like EC2 AWS instance, it may just be a case of opening the port through the AWS console.

see this answer

jQuery.getJSON - Access-Control-Allow-Origin Issue

You may well want to use JSON-P instead (see below). First a quick explanation.

The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).

To get the JSON data you're requesting, you basically have three options:

  1. If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)

  2. Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:

    {"weather": "Dreary start but soon brightening into a fine summer day."}
    

    Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:

    jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
    

    That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).

  3. Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:

    A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).

    B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.

    C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.

    D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.

    In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):

    // Find out what the request is asking for
    corsOrigin = get_request_header("Origin")
    corsMethod = get_request_header("Access-Control-Request-Method")
    corsHeaders = get_request_header("Access-Control-Request-Headers")
    if corsOrigin is null or "null" {
        // Requests from a `file://` path seem to come through without an
        // origin or with "null" (literally) as the origin.
        // In my case, for testing, I wanted to allow those and so I output
        // "*", but you may want to go another way.
        corsOrigin = "*"
    }
    
    // Decide whether to accept that request with those headers
    // If so:
    
    // Respond with headers saying what's allowed (here we're just echoing what they
    // asked for, except we may be using "*" [all] instead of the actual origin for
    // the "Access-Control-Allow-Origin" one)
    set_response_header("Access-Control-Allow-Origin", corsOrigin)
    set_response_header("Access-Control-Allow-Methods", corsMethod)
    set_response_header("Access-Control-Allow-Headers", corsHeaders)
    if the HTTP request method is "OPTIONS" {
        // Done, no body in response to OPTIONS
        stop
    }
    // Process the GET or POST here; output the body of the response
    

    Again stressing that this is pseudo-code.

Cmake is not able to find Python-libraries

Even after adding -DPYTHON_INCLUDE_DIR and -DPYTHON_LIBRARY as suggested above, I was still facing the error Could NOT find PythonInterp. What solved it was adding -DPYTHON_EXECUTABLE:FILEPATH= to cmake as suggested in https://github.com/pybind/pybind11/issues/99#issuecomment-182071479:

cmake .. \
-DPYTHON_INCLUDE_DIR=$(python -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())")  \
-DPYTHON_LIBRARY=$(python -c "import distutils.sysconfig as sysconfig; print(sysconfig.get_config_var('LIBDIR'))") \
-DPYTHON_EXECUTABLE:FILEPATH=`which python`

How to add a button to UINavigationBar?

Sample code to set the rightbutton on a NavigationBar.

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" 
    style:UIBarButtonItemStyleDone target:nil action:nil];
UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"Title"];
item.rightBarButtonItem = rightButton;
item.hidesBackButton = YES;
[bar pushNavigationItem:item animated:NO];

But normally you would have a NavigationController, enabling you to write:

UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
    style:UIBarButtonItemStyleDone target:nil action:nil];
self.navigationItem.rightBarButtonItem = rightButton;

Generic List - moving an item within the list

This is how I implemented a move element extension method. It handles moving before/after and to the extremes for elements pretty well.

public static void MoveElement<T>(this IList<T> list, int fromIndex, int toIndex)
{
  if (!fromIndex.InRange(0, list.Count - 1))
  {
    throw new ArgumentException("From index is invalid");
  }
  if (!toIndex.InRange(0, list.Count - 1))
  {
    throw new ArgumentException("To index is invalid");
  }

  if (fromIndex == toIndex) return;

  var element = list[fromIndex];

  if (fromIndex > toIndex)
  {
    list.RemoveAt(fromIndex);
    list.Insert(toIndex, element);
  }
  else
  {
    list.Insert(toIndex + 1, element);
    list.RemoveAt(fromIndex);
  }
}

Javascript Cookie with no expiration date

Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.

Removing the remembered login and password list in SQL Server Management Studio

Another answer here also mentions since 2012 you can remove Remove cached login via How to remove cached server names from the Connect to Server dialog?. Just confirmed this delete in MRU list works fine in 2016 and 2017.

SQL Server Management Studio 2017 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\14.0\SqlStudio.bin

SQL Server Management Studio 2016 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\13.0\SqlStudio.bin

SQL Server Management Studio 2014 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\12.0\SqlStudio.bin

SQL Server Management Studio 2012 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\11.0\SqlStudio.bin

SQL Server Management Studio 2008 delete the file C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell\SqlStudio.bin

SQL Server Management Studio 2005 delete the file – same as above answer but the Vista path. C:\Users\%username%\AppData\Roaming\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

These are profile paths for Vista / 7 / 8.

EDIT:

Note, AppData is a hidden folder. You need to show hidden folders in explorer.

EDIT: You can simply press delete from the Server / User name drop down (confirmed to be working for SSMS v18.0). Original source from https://blog.sqlauthority.com/2013/04/17/sql-server-remove-cached-login-from-ssms-connect-dialog-sql-in-sixty-seconds-049/ which mentioned that this feature is available since 2012!

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

I think we should sent in this format

var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});

Its already mentioned in Pass array to mvc Action via AJAX

It worked for me

Hide keyboard in react-native

Use ScrollView instead of View and set the keyboardShouldPersistTaps attribute to false.

<ScrollView style={styles.container} keyboardShouldPersistTaps={false}>
    <TextInput
        placeholder="Post Title"
        onChange={(event) => this.updateTitle(event.nativeEvent.text)}
        style={styles.default}/>
 </ScrollView>

What is a good way to handle exceptions when trying to read a file in python?

How about this:

try:
    f = open(fname, 'rb')
except OSError:
    print "Could not open/read file:", fname
    sys.exit()

with f:
    reader = csv.reader(f)
    for row in reader:
        pass #do stuff here

How to present popover properly in iOS 8

Okay, A housemate took a look at it and figured it out:

 func addCategory() {

    var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
    var nav = UINavigationController(rootViewController: popoverContent)
    nav.modalPresentationStyle = UIModalPresentationStyle.Popover
    var popover = nav.popoverPresentationController
    popoverContent.preferredContentSize = CGSizeMake(500,600)
    popover.delegate = self
    popover.sourceView = self.view
    popover.sourceRect = CGRectMake(100,100,0,0)

    self.presentViewController(nav, animated: true, completion: nil)

}

That's the way.

You don't talk to the popover itself anymore, you talk to the view controller inside of it to set the content size, by calling the property preferredContentSize

Set value to currency in <input type="number" />

The browser only allows numerical inputs when the type is set to "number". Details here.

You can use the type="text" and filter out any other than numerical input using JavaScript like descripted here

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

How to import set of icons into Android Studio project

just like Gregory Seront said here:

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

but if your not getting the images from a generator site (maybe your UX team provides them), just make sure your folders are named drawable-hdpi, drawable-mdpi, etc. then in mac select all folders by holding shift and then copy them (DO NOT DRAG). Paste the folders into the res folder. android will take care of the rest and copy all drawables into the correct folder.

Post parameter is always null

In my case decorating the parameter class with the [JsonObject(MemberSerialization.OptOut)] attribute from Newtonsoft did the trick.

For example:

[HttpPost]
[Route("MyRoute")]
public IHttpActionResult DoWork(MyClass args)
{
   ...
}

[JsonObject(MemberSerialization.OptOut)]
public Class MyClass
{
    ...
}

What is Cache-Control: private?

Cache-Control: private

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache, such as a proxy server.

From RFC2616 section 14.9.1

How do I replace text inside a div element?

Use innerText if you can't assume structure - Use Text#data to update existing text Performance Test

Why rgb and not cmy?

the 3 additive colors are in fact red, green, and blue. printers use cmyk (cyan, magenta, yellow, and black).

and as http://en.wikipedia.org/wiki/Additive_color explains: if you use RYB as your primary colors, how do you make green? since yellow is made from equal amounts of red and green.

How can I escape double quotes in XML attributes values?

From the XML specification:

To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as "&apos;", and the double-quote character (") as "&quot;".

How can I set a website image that will show as preview on Facebook?

If you're using Weebly, start by viewing the published site and right-clicking the image to Copy Image Address. Then in Weebly, go to Edit Site, Pages, click the page you wish to use, SEO Settings, under Header Code enter the code from Shef's answer:

<meta property="og:image" content="/uploads/..." />

just replacing /uploads/... with the copied image address. Click Publish to apply the change.

You can skip the part of Shef's answer about namespace, because that's already set by default in Weebly.

HTTP URL Address Encoding in Java

I had the same problem. Solved this by unsing:

android.net.Uri.encode(urlString, ":/");

It encodes the string but skips ":" and "/".

AndroidStudio gradle proxy

For an NTLM Authentication Proxy:

File -> Settings -> Project Settings -> Gradle -> Global Gradle Settings -> Gradle VM Options

-Dhttp.proxyHost=myProxyAddr -Dhttp.proxyPort=myProxyPort -Dhttp.proxyUser=myUsername -Dhttp.proxyPassword=myPasswd -Dhttp.auth.ntlm.domain=myDomainName

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

You might looking for the placeholder attribute which will display a grey text in the input field while empty.

From Mozilla Developer Network:

A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.

However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )

And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/

Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/

Python integer division yields float

The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.

Python maps operators like +, -, * and / to special functions, such that e.g. a + b is equivalent to

a.__add__(b)

Regarding division in Python 2, there is by default only / which maps to __div__ and the result is dependent on the input types (e.g. int, float).

Python 2.2 introduced the __future__ feature division, which changed the division semantics the following way (TL;DR of PEP 238):

  • / maps to __truediv__ which must "return a reasonable approximation of the mathematical result of the division" (quote from PEP 238)
  • // maps to __floordiv__, which should return the floored result of /

With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__ in Python's object model.

If you want to use the same code in Python 2 and Python 3 use

from __future__ import division

and stick to the PEP 238 semantics of / and //.

What is the 'override' keyword in C++ used for?

The override keyword serves two purposes:

  1. It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
  2. The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

To explain the latter:

class base
{
  public:
    virtual int foo(float x) = 0; 
};


class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}

class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for "changing the type". Without override, at most the compiler would give a warning for "you are hiding virtual method by same name".

How to convert Set to Array?

if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?

Indeed, there are several ways to convert a Set to an Array:

using Array.from

let array = Array.from(mySet);

Simply spreading the Set out in an array

let array = [...mySet];

The old fashion way, iterating and pushing to a new array (Sets do have forEach)

let array = [];
mySet.forEach(v => array.push(v));

Previously, using the non-standard, and now deprecated array comprehension syntax:

let array = [v for (v of mySet)];

Difference between parameter and argument

Arguments and parameters are different in that parameters are used to different values in the program and The arguments are passed the same value in the program so they are used in c++. But no difference in c. It is the same for arguments and parameters in c.

How does the @property decorator work in Python?

This following:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, _x_set, _x_del, 
                    "I'm the 'x' property.")

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, doc="I'm the 'x' property.")
    x = x.setter(_x_set)
    x = x.deleter(_x_del)

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x
    x = property(_x_get, doc="I'm the 'x' property.")

    def _x_set(self, value):
        self._x = value
    x = x.setter(_x_set)

    def _x_del(self):
        del self._x
    x = x.deleter(_x_del)

Which is the same as :

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

How to find all occurrences of a substring?

def find_index(string, let):
    enumerated = [place  for place, letter in enumerate(string) if letter == let]
    return enumerated

for example :

find_index("hey doode find d", "d") 

returns:

[4, 7, 13, 15]

Testing Private method using mockito

I don't really understand your need to test the private method. The root problem is that your public method has void as return type, and hence you are not able to test your public method. Hence you are forced to test your private method. Is my guess correct??

A few possible solutions (AFAIK):

  1. Mocking your private methods, but still you won't be "actually" testing your methods.

  2. Verify the state of object used in the method. MOSTLY methods either do some processing of the input values and return an output, or change the state of the objects. Testing the objects for the desired state can also be employed.

    public class A{
    
    SomeClass classObj = null;
    
    public void publicMethod(){
       privateMethod();
    }
    
    private void privateMethod(){
         classObj = new SomeClass();
    }
    
    }
    

    [Here you can test for the private method, by checking the state change of the classObj from null to not null.]

  3. Refactor your code a little (Hope this is not a legacy code). My funda of writing a method is that, one should always return something (a int/ a boolean). The returned value MAY or MAY NOT be used by the implementation, but it will SURELY BE used by the test

    code.

    public class A
    { 
        public int method(boolean b)
        {
              int nReturn = 0;
              if (b == true)
                   nReturn = method1();
              else
                   nReturn = method2();
        }
    
        private int method1() {}
    
        private int method2() {}
    
    }
    

How do I run SSH commands on remote system using Java?

Below is the easiest way to SSh in java. Download any of the file in the below link and extract, then add the jar file from the extracted file and add to your build path of the project http://www.ganymed.ethz.ch/ssh2/ and use the below method

public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{
        System.out.println("inside the ssh function");
        try
        {
            Connection conn = new Connection(serverIp);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");        
            ch.ethz.ssh2.Session sess = conn.openSession();
            sess.execCommand(command);  
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            System.out.println("the output of the command is");
            while (true)
            {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            System.out.println("ExitCode: " + sess.getExitStatus());
            sess.close();
            conn.close();
        }
        catch (IOException e)
        {
            e.printStackTrace(System.err);

        }
    }

jQuery .slideRight effect

Another solution is by using .animate() and appropriate CSS.

e.g.

   $('#mydiv').animate({ marginLeft: "100%"} , 4000);

JS Fiddle

Reporting Services Remove Time from DateTime in Expression

My solution for a Date/Time parameter:

=CDate(Today())

The trick is to convert back to a DateTime as recommend Perhentian.

When to use IMG vs. CSS background-image?

Use background images only when necessary e.g. containers with image that tiles.

One of the major PROS by using IMAGES is that it is better for SEO.

SELECT where row value contains string MySQL

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

but it's not suggested. use PDO

Convert DataSet to List

Add a new class named as "Helper" and change the property of the class to "public static"

public static class Helper
{
    public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
    {
        try
        {
            List<T> list = new List<T>();

            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();

                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch
        {
            return null;
        }
    }
}

and access this class in your code behind as like below

 DataTable dtt = dsCallList.Tables[0];
 List<CallAssignment> lstCallAssignement = dtt.DataTableToList<CallAssignment>();

Is there a Google Chrome-only CSS hack?

Sure is:

@media screen and (-webkit-min-device-pixel-ratio:0)
{ 
    #element { properties:value; } 
}

And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/

Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.

Also, these hacks may not be future proof.

How do I install PyCrypto on Windows?

Step 1: Install Visual C++ 2010 Express from here.

(Do not install Microsoft Visual Studio 2010 Service Pack 1 )

Step 2: Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.

Step 3: Install offline version of Windows SDK for Visual Studio 2010 (v7.1) from here. This is required for 64bit extensions. Windows has builtin mounting for ISOs like Pismo.

Step 4: You need to install the ISO file with Pismo File Mount Audit Package. Download Pismo from here

Step 5: Right click the downloaded ISO file and choose mount with Pismo. Thereafter, install the Setup\SDKSetup.exe instead of setup.exe.

Step 6a: Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 by changing directory to C:\Program Files (x86)\Microsoft Visual Studio version\VC\ on the command prompt. Type command on the command prompt: cd C:\Program Files (x86)\Microsoft Visual Studio version\VC\r

Step 6b: To configure this Command Prompt window for 64-bit command-line builds that target x86 platforms, at the command prompt, enter: vcvarsall x86 Click here for more options.

Step 7: At the command prompt, install the PyCrypto by typing: C:\Python3X>pip install -U your_wh_file

How to include quotes in a string

You can also declare a constant and use it each time. neat and avoids confusion:

const string myStrQuote = "\"";

jQuery equivalent to Prototype array.last()

If u use the prototype on arrays like:

Array.prototype.last = function() {return this[this.length-1];}

using forloops will do this.

var a = [0,1,2];
out --> 0
out --> 1
out --> 2
out --> last

ValueError : I/O operation on closed file

I had this problem when I was using an undefined variable inside the with open(...) as f:. I removed (or I defined outside) the undefined variable and the problem disappeared.

Convert dd-mm-yyyy string to date

Using moment.js example:

var from = '11-04-2017' // OR $("#datepicker").val();
var milliseconds = moment(from, "DD-MM-YYYY").format('x');
var f = new Date(milliseconds)

JSON.parse vs. eval()

Not all browsers have native JSON support so there will be times where you need to use eval() to the JSON string. Use JSON parser from http://json.org as that handles everything a lot easier for you.

Eval() is an evil but against some browsers its a necessary evil but where you can avoid it, do so!!!!!

Force download a pdf link using javascript/ajax/jquery

If htaccess is an option this will make all PDF links download instead of opening in browser

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

Posting array from form

You can use the built-in function:

extract($_POST);

it will create a variable for each entry in $_POST.

How can I specify the default JVM arguments for programs I run from eclipse?

Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:

-Xmx512m -ea -Djava.awt.headless=true

How to access a value defined in the application.properties file in Spring Boot

You can use the @Value to load variables from the application.properties if you will use this value in one place, but if you need a more centralized way to load this variables @ConfigurationProperties is a better approach.

Additionally you can load variables and cast it automatically if you need different data types to perform your validations and business logic.

application.properties
custom-app.enable-mocks = false

@Value("${custom-app.enable-mocks}")
private boolean enableMocks;

How to set proxy for wget?

After trying many tutorials to configure my Ubuntu 16.04 LTS behind a authenticated proxy, it worked with these steps:

Edit /etc/wgetrc:

$ sudo nano /etc/wgetrc

Uncomment these lines:

#https_proxy = http://proxy.yoyodyne.com:18023/
#http_proxy = http://proxy.yoyodyne.com:18023/
#ftp_proxy = http://proxy.yoyodyne.com:18023/
#use_proxy = on

Change http://proxy.yoyodyne.com:18023/ to http://username:password@domain:port/

IMPORTANT: If it still doesn't work, check if your password has special characters, such as #, @, ... If this is the case, escape them (for example, replace passw@rd with passw%40rd).

How to stop an unstoppable zombie job on Jenkins without restarting the server?

I use the Monitoring Plugin for this task. After the installation of the plugin

  1. Go to Manage Jenkins > Monitoring of Hudson/Jenkins master
  2. Expand the Details of Threads, the small blue link on the right side
  3. Search for the Job Name that is hung

    The Thread's name will start like this

    Executor #2 for master : executing <your-job-name> #<build-number>

  4. Click the red, round button on the very right in the table of the line your desired job has

Finding the 'type' of an input element

If you are using jQuery you can easily check the type of any element.

    function(elementID){    
    var type = $(elementId).attr('type');
    if(type == "text") //inputBox
     console.log("input text" + $(elementId).val().size());
   }

similarly you can check the other types and take appropriate action.

Utilizing multi core for tar+gzip/bzip compression/decompression

You can use the shortcut -I for tar's --use-compress-program switch, and invoke pbzip2 for bzip2 compression on multiple cores:

tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 DIRECTORY_TO_COMPRESS/

Create session factory in Hibernate 4

In earlier versions session factory was created as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be like:

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());

How to write a multiline Jinja statement

According to the documentation: https://jinja.palletsprojects.com/en/2.10.x/templates/#line-statements you may use multi-line statements as long as the code has parens/brackets around it. Example:

{% if ( (foo == 'foo' or bar == 'bar') and 
        (fooo == 'fooo' or baar == 'baar') ) %}
    <li>some text</li>
{% endif %}

Edit: Using line_statement_prefix = '#'* the code would look like this:

# if ( (foo == 'foo' or bar == 'bar') and 
       (fooo == 'fooo' or baar == 'baar') )
    <li>some text</li>
# endif

*Here's an example of how you'd specify the line_statement_prefix in the Environment:

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']),
    line_statement_prefix='#'
)

Or using Flask:

from flask import Flask
app = Flask(__name__, instance_relative_config=True, static_folder='static')
app.jinja_env.filters['zip'] = zip
app.jinja_env.line_statement_prefix = '#'

How to send image to PHP file using Ajax?

Jquery code which contains simple ajax :

   $("#product").on("input", function(event) {
      var data=$("#nameform").serialize();
    $.post("./__partails/search-productbyCat.php",data,function(e){
       $(".result").empty().append(e);

     });


    });

Html elements you can use any element:

     <form id="nameform">
     <input type="text" name="product" id="product">
     </form>

php Code:

  $pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
  $Catagoryf=$_POST['product'];

 $pricef=$_POST['price'];
  $colorf=$_POST['color'];

  $stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
  $stmtcat->execute(array($Catagoryf));

  while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
  $iddb=$result['ID'];
     $namedb=$result['Name'];
    $pricedb=$result['Price'];
     $colordb=$result['Color'];

   echo "<tr>";
   echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>'; 
   echo "<td><pre>$pricedb</pre></td>";
   echo "<td><pre>    $colordb</pre>";
   echo "</tr>";

The easy way

How to go back to previous page if back button is pressed in WebView?

here is a code with confirm exit:

@Override
    public void onBackPressed()
    {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Exit!")
            .setMessage("Are you sure you want to close?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();    
                }

            })
            .setNegativeButton("No", null)
            .show();    
        }   
    }

Refresh or force redraw the fragment

I do not think there is a method for that. The fragment rebuilds it's UI on onCreateView()... but that happens when the fragment is created or recreated.

You'll have to implement your own updateUI method or where you will specify what elements and how they should update. It's rather a good practice, since you need to do that when the fragment is created anyway.

However if this is not enough you could do something like replacing fragment with the same one forcing it to call onCreateView()

FragmentTransaction tr = getFragmentManager().beginTransaction();
tr.replace(R.id.your_fragment_container, yourFragmentInstance);
tr.commit()

NOTE

To refresh ListView you need to call notifyDataSetChanged() on the ListView's adapter.

Are lists thread-safe?

To clarify a point in Thomas' excellent answer, it should be mentioned that append() is thread safe.

This is because there is no concern that data being read will be in the same place once we go to write to it. The append() operation does not read data, it only writes data to the list.

How to count the number of true elements in a NumPy bool array

boolarr.sum(axis=1 or axis=0)

axis = 1 will output number of trues in a row and axis = 0 will count number of trues in columns so

boolarr[[true,true,true],[false,false,true]]
print(boolarr.sum(axis=1))

will be (3,1)

AngularJs: How to set radio button checked based on model

Ended up just using the built-in angular attribute ng-checked="model"

Background color not showing in print preview

I used purgatory101's answer but had trouble keeping all colours (icons, backgrounds, text colours etc...), especially that CSS stylesheets cannot be used with libraries which dynamically change DOM element's colours. Therefore here is a script that changes element's styles (background-colour and colour) before printing and clears styles once printing is done. It is useful to avoid writing a lot of CSS in a @media print stylesheet as it works whatever the page structure.

There is a part of the script that is specially made to keep FontAwesome icons color (or any element that uses a :before selector to insert coloured content).

JSFiddle showing the script in action

Compatibility: works in Chrome, I did not test other browsers.

function setColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var eltBackground = $(elements[i]).css('background-color');
    var eltColor = $(elements[i]).css('color');

    var elementStyle = elements[i].style;
    if (eltBackground) {
      elementStyle.oldBackgroundColor = {
        value: elementStyle.backgroundColor,
        importance: elementStyle.getPropertyPriority('background-color'),
      };
      elementStyle.setProperty('background-color', eltBackground, 'important');
    }
    if (eltColor) {
      elementStyle.oldColor = {
        value: elementStyle.color,
        importance: elementStyle.getPropertyPriority('color'),
      };
      elementStyle.setProperty('color', eltColor, 'important');
    }
  }
}

function resetColors(selector) {
  var elements = $(selector);
  for (var i = 0; i < elements.length; i++) {
    var elementStyle = elements[i].style;

    if (elementStyle.oldBackgroundColor) {
      elementStyle.setProperty('background-color', elementStyle.oldBackgroundColor.value, elementStyle.oldBackgroundColor.importance);
      delete elementStyle.oldBackgroundColor;
    } else {
      elementStyle.setProperty('background-color', '', '');
    }
    if (elementStyle.oldColor) {
      elementStyle.setProperty('color', elementStyle.oldColor.value, elementStyle.oldColor.importance);
      delete elementStyle.oldColor;
    } else {
      elementStyle.setProperty('color', '', '');
    }
  }
}

function setIconColors(icons) {
  var css = '';
  $(icons).each(function (k, elt) {
    var selector = $(elt)
      .parents()
      .map(function () { return this.tagName; })
      .get()
      .reverse()
      .concat([this.nodeName])
      .join('>');

    var id = $(elt).attr('id');
    if (id) {
      selector += '#' + id;
    }

    var classNames = $(elt).attr('class');
    if (classNames) {
      selector += '.' + $.trim(classNames).replace(/\s/gi, '.');
    }

    css += selector + ':before { color: ' + $(elt).css('color') + ' !important; }';
  });
  $('head').append('<style id="print-icons-style">' + css + '</style>');
}

function resetIconColors() {
  $('#print-icons-style').remove();
}

And then modify the window.print function to make it set the styles before printing and resetting them after.

window._originalPrint = window.print;
window.print = function() {
  setColors('body *');
  setIconColors('body .fa');
  window._originalPrint();
  setTimeout(function () {
    resetColors('body *');
    resetIconColors();
  }, 100);
}

The part that finds icons paths to create CSS for :before elements is a copy from this SO answer

How to keep :active css style after click a button

In the Divi Theme Documentation, it says that the theme comes with access to 'ePanel' which also has an 'Integration' section.

You should be able to add this code:

<script>
 $( ".et-pb-icon" ).click(function() {
 $( this ).toggleClass( "active" );
 });
</script>

into the the box that says 'Add code to the head of your blog' under the 'Integration' tab, which should get the jQuery working.

Then, you should be able to style your class to what ever you need.

How do you switch pages in Xamarin.Forms?

If you do not want to go the previous page i.e. do not let the user go back to the login screen once authorization is done, then you can use;

 App.Current.MainPage = new HomePage();

If you want to enable back functionality, just use

Navigation.PushModalAsync(new HomePage())

How can I set the current working directory to the directory of the script in Bash?

The accepted answer works well for scripts that have not been symlinked elsewhere, such as into $PATH.

#!/bin/bash
cd "$(dirname "$0")"

However if the script is run via a symlink,

ln -sv ~/project/script.sh ~/bin/; 
~/bin/script.sh

This will cd into the ~/bin/ directory and not the ~/project/ directory, which will probably break your script if the purpose of the cd is to include dependencies relative to ~/project/

The symlink safe answer is below:

#!/bin/bash
cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"

readlink -f is required to resolve the absolute path of the potentially symlinked file.

The quotes are required to support filepaths that could potentially contain whitespace (bad practice, but its not safe to assume this won't be the case)

static linking only some libraries

There is also -l:libstatic1.a (minus l colon) variant of -l option in gcc which can be used to link static library (Thanks to https://stackoverflow.com/a/20728782). Is it documented? Not in the official documentation of gcc (which is not exact for shared libs too): https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html

-llibrary
-l library 

Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.) ... The only difference between using an -l option and specifying a file name is that -l surrounds library with ‘lib’ and ‘.a’ and searches several directories.

The binutils ld doc describes it. The -lname option will do search for libname.so then for libname.a adding lib prefix and .so (if enabled at the moment) or .a suffix. But -l:name option will only search exactly for the name specified: https://sourceware.org/binutils/docs/ld/Options.html

-l namespec
--library=namespec

Add the archive or object file specified by namespec to the list of files to link. This option may be used any number of times. If namespec is of the form :filename, ld will search the library path for a file called filename, otherwise it will search the library path for a file called libnamespec.a.

On systems which support shared libraries, ld may also search for files other than libnamespec.a. Specifically, on ELF and SunOS systems, ld will search a directory for a library called libnamespec.so before searching for one called libnamespec.a. (By convention, a .so extension indicates a shared library.) Note that this behavior does not apply to :filename, which always specifies a file called filename.

The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again.

See the -( option for a way to force the linker to search archives multiple times.

You may list the same archive multiple times on the command line.

This type of archive searching is standard for Unix linkers. However, if you are using ld on AIX, note that it is different from the behaviour of the AIX linker.

The variant -l:namespec is documented since 2.18 version of binutils (2007): https://sourceware.org/binutils/docs-2.18/ld/Options.html

How to hide a View programmatically?

Kotlin Solution

view.isVisible = true
view.isInvisible = true
view.isGone = true

// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone

Kotlin Extension Solution

If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:

// Example
view.hide()

fun View?.show() {
    if (this == null) return
    if (!isVisible) isVisible = true
}

fun View?.hide() {
    if (this == null) return
    if (!isInvisible) isInvisible = true
}

fun View?.gone() {
    if (this == null) return
    if (!isGone) isGone = true
}

To make conditional visibility simple, also add these:

fun View?.show(visible: Boolean) {
    if (visible) show() else gone()
}

fun View?.hide(hide: Boolean) {
    if (hide) hide() else show()
}

fun View?.gone(gone: Boolean = true) {
    if (gone) gone() else show()
}

How do I run a Python script from C#?

If you're willing to use IronPython, you can execute scripts directly in C#:

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;

private static void doPython()
{
    ScriptEngine engine = Python.CreateEngine();
    engine.ExecuteFile(@"test.py");
}

Get IronPython here.

Split function in oracle to comma separated values with automatic sequence

This function returns the nth part of input string MYSTRING. Second input parameter is separator ie., SEPARATOR_OF_SUBSTR and the third parameter is Nth Part which is required.

Note: MYSTRING should end with the separator.

create or replace FUNCTION PK_GET_NTH_PART(MYSTRING VARCHAR2,SEPARATOR_OF_SUBSTR VARCHAR2,NTH_PART NUMBER)
RETURN VARCHAR2
IS
NTH_SUBSTR VARCHAR2(500);
POS1 NUMBER(4);
POS2 NUMBER(4);
BEGIN
IF NTH_PART=1 THEN
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, 1)  INTO POS1 FROM DUAL; 
SELECT SUBSTR(MYSTRING,0,POS1-1) INTO NTH_SUBSTR FROM DUAL;
ELSE
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART-1) INTO  POS1 FROM DUAL; 
SELECT REGEXP_INSTR(MYSTRING,SEPARATOR_OF_SUBSTR, 1, NTH_PART)  INTO POS2 FROM DUAL; 
SELECT SUBSTR(MYSTRING,POS1+1,(POS2-POS1-1)) INTO NTH_SUBSTR FROM DUAL;
END IF;
RETURN NTH_SUBSTR;
END;

Hope this helps some body, you can use this function like this in a loop to get all the values separated:

SELECT REGEXP_COUNT(MYSTRING, '~', 1, 'i') INTO NO_OF_RECORDS FROM DUAL;
WHILE NO_OF_RECORDS>0
LOOP
    PK_RECORD    :=PK_GET_NTH_PART(MYSTRING,'~',NO_OF_RECORDS);
    -- do some thing
    NO_OF_RECORDS  :=NO_OF_RECORDS-1;
END LOOP;

Here NO_OF_RECORDS,PK_RECORD are temp variables.

Hope this helps.

Find records from one table which don't exist in another

There's several different ways of doing this, with varying efficiency, depending on how good your query optimiser is, and the relative size of your two tables:

This is the shortest statement, and may be quickest if your phone book is very short:

SELECT  *
FROM    Call
WHERE   phone_number NOT IN (SELECT phone_number FROM Phone_book)

alternatively (thanks to Alterlife)

SELECT *
FROM   Call
WHERE  NOT EXISTS
  (SELECT *
   FROM   Phone_book
   WHERE  Phone_book.phone_number = Call.phone_number)

or (thanks to WOPR)

SELECT * 
FROM   Call
LEFT OUTER JOIN Phone_Book
  ON (Call.phone_number = Phone_book.phone_number)
  WHERE Phone_book.phone_number IS NULL

(ignoring that, as others have said, it's normally best to select just the columns you want, not '*')

PHP Using RegEx to get substring of a string

<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>

How to use responsive background image in css3 in bootstrap

For full image background, check this:

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

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

How to search in an array with preg_match?

You can use array_walk to apply your preg_match function to each element of the array.

http://us3.php.net/array_walk

Including dependencies in a jar with Maven

Putting Maven aside, you can put JAR libraries inside the Main Jar but you will need to use your own classloader.

Check this project: One-JAR link text

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

Gradle failed to resolve library in Android Studio

Try this

  1. Clean project
  2. Invalidate cache and restart studio
  3. Check android SDK path is proper
  4. Check is there any error in any of your resource file

How to run Gradle from the command line on Mac bash

Also, if you don't have the gradlew file in your current directory:

You can install gradle with homebrew with the following command:

$ brew install gradle

As mentioned in this answer. Then, you are not going to need to include it in your path (homebrew will take care of that) and you can just run (from any directory):

$ gradle test 

Save text file UTF-8 encoded with VBA

The traditional way to transform a string to a UTF-8 string is as follows:

StrConv("hello world",vbFromUnicode)

So put simply:

Dim fnum As Integer
fnum = FreeFile
Open "myfile.txt" For Output As fnum
Print #fnum, StrConv("special characters: äöüß", vbFromUnicode)
Close fnum

No special COM objects required

How to make an input type=button act like a hyperlink and redirect using a get request?

I think that is your need.

a href="#" onclick="document.forms[0].submit();return false;"

Getting A File's Mime Type In Java

I was just wondering how most people fetch a mime type from a file in Java?

I've published my SimpleMagic Java package which allows content-type (mime-type) determination from files and byte arrays. It is designed to read and run the Unix file(1) command magic files that are a part of most ~Unix OS configurations.

I tried Apache Tika but it is huge with tons of dependencies, URLConnection doesn't use the bytes of the files, and MimetypesFileTypeMap also just looks at files names.

With SimpleMagic you can do something like:

// create a magic utility using the internal magic file
ContentInfoUtil util = new ContentInfoUtil();
// if you want to use a different config file(s), you can load them by hand:
// ContentInfoUtil util = new ContentInfoUtil("/etc/magic");
...
ContentInfo info = util.findMatch("/tmp/upload.tmp");
// or
ContentInfo info = util.findMatch(inputStream);
// or
ContentInfo info = util.findMatch(contentByteArray);

// null if no match
if (info != null) {
   String mimeType = info.getMimeType();
}

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature

PHP order array by date?

Use usort:

usort($array, function($a1, $a2) {
   $v1 = strtotime($a1['date']);
   $v2 = strtotime($a2['date']);
   return $v1 - $v2; // $v2 - $v1 to reverse direction
});

UIView bottom border?

If you use constraints (and so don't have the frame sizes) then you can add a border view with the required constraints

// MARK: - Add a border to one side of a view

public enum BorderSide {
    case top, bottom, left, right
}

extension UIView {
    public func addBorder(side: BorderSide, color: UIColor, width: CGFloat) {
        let border = UIView()
        border.translatesAutoresizingMaskIntoConstraints = false
        border.backgroundColor = color
        self.addSubview(border)

        let topConstraint = topAnchor.constraint(equalTo: border.topAnchor)
        let rightConstraint = trailingAnchor.constraint(equalTo: border.trailingAnchor)
        let bottomConstraint = bottomAnchor.constraint(equalTo: border.bottomAnchor)
        let leftConstraint = leadingAnchor.constraint(equalTo: border.leadingAnchor)
        let heightConstraint = border.heightAnchor.constraint(equalToConstant: width)
        let widthConstraint = border.widthAnchor.constraint(equalToConstant: width)


        switch side {
        case .top:
            NSLayoutConstraint.activate([leftConstraint, topConstraint, rightConstraint, heightConstraint])
        case .right:
            NSLayoutConstraint.activate([topConstraint, rightConstraint, bottomConstraint, widthConstraint])
        case .bottom:
            NSLayoutConstraint.activate([rightConstraint, bottomConstraint, leftConstraint, heightConstraint])
        case .left:
            NSLayoutConstraint.activate([bottomConstraint, leftConstraint, topConstraint, widthConstraint])
        }
    }
}

Then set it something like the below

myButton.addBorder(side: .left, color: UIColor.lightGray, width: 1)

(inspired by this answer)

How to check if an app is installed from a web-page on an iPhone?

The date solution is much better than others, I had to increment the time on 50 like that this is a Tweeter example:

//on click or your event handler..
var twMessage = "Your Message to share";
var now = new Date().valueOf();
setTimeout(function () {
   if (new Date().valueOf() - now > 100) return;
   var twitterUrl = "https://twitter.com/share?text="+twMessage;
   window.open(twitterUrl, '_blank');
}, 50);
window.location = "twitter://post?message="+twMessage;

the only problem on Mobile IOS Safari is when you don't have the app installed on device, and so Safari show an alert that autodismiss when the new url is opened, anyway is a good solution for now!

Android Studio Emulator and "Process finished with exit code 0"

I had this problem and it took me nearly 2 days to resolve...

I had moved my SDK location, due to the system drive being full, and it seems that someone, somewhere at Android Studio central has hard-coded the path to the HaxM driver installer. As my HamX driver was out of date, the emulator wouldn't start.

Solution: navigate to [your sdk location]\extras\intel\Hardware_Accelerated_Execution_Manager and run the intelhaxm-android.exe installer to update yourself to the latest driver.

TypeScript - Append HTML to container element in Angular 2

With the new angular class Renderer2

constructor(private renderer:Renderer2) {}

  @ViewChild('one', { static: false }) d1: ElementRef;

  ngAfterViewInit() {
    const d2 = this.renderer.createElement('div');
    const text = this.renderer.createText('two');
    this.renderer.appendChild(d2, text);
    this.renderer.appendChild(this.d1.nativeElement, d2);
  }

How to check whether java is installed on the computer

1)Open the command prompt or terminal based on your OS.

2)Then type java --version in the terminal.

3) If java is installed successfullly it will show the respective version .

Android: keep Service running when app is killed

You can use android:stopWithTask="false"in manifest as bellow, This means even if user kills app by removing it from tasklist, your service won't stop.

 <service android:name=".service.StickyService"
                  android:stopWithTask="false"/>

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

I just had to do import Foundation!

I was using Kitura for Swift server side and kept forgetting this!

What are the differences between C, C# and C++ in terms of real-world applications?

C is the core language that most closely resembles and directly translates into CPU machine code. CPUs follow instructions that move, add, logically combine, compare, jump, push and pop. C does exactly this using much easier syntax. If you study the disassembly, you can learn to write C code that is just as fast and compact as assembly. It is my preferred language on 8 bit micro controllers with limited memory. If you write a large PC program in C you will get into trouble because of its limited organization. That is where object oriented programming becomes powerful. The ability of C++ and C# classes to contain data and functions together enforces organization which in turn allows more complex operability over C. C++ was essential for quick processing in the past when CPUs only had one core. I am beginning to learn C# now. Its class only structure appears to enforce a higher degree of organization than C++ which should ultimately lead to faster development and promote code sharing. C# is not interpreted like VB. It is partially compiled at development time and then further translated at run time to become more platform friendly.

Select SQL Server database size

EXEC sp_spaceused @oneresultset = 1 show in 1 row all of the result

if you execute just 'EXEC sp_spaceused' you will see two rows Work in SQL Server Management Studio v17.9

How to install easy_install in Python 2.7.1 on Windows 7

I know this isn't a direct answer to your question but it does offer one solution to your problem. Python 2.7.9 includes PIP and SetupTools, if you update to this version you will have one solution to your problem.

How to use onClick with divs in React.js

This also works:

I just changed with this.state.color==='white'?'black':'white'.

You can also pick the color from drop-down values and update in place of 'black';

(CodePen)

Adding sheets to end of workbook in Excel (normal method not working?)

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 

Print string and variable contents on the same line in R

You can use paste with print

print(paste0("Current working dir: ", wd))

or cat

cat("Current working dir: ", wd)

How to detect when WIFI Connection has been established in Android?

1) I tried Broadcast Receiver approach as well even though I know CONNECTIVITY_ACTION/CONNECTIVITY_CHANGE is deprecated in API 28 and not recommended. Also bound to using explicit register, it listens as long as app is running.

2) I also tried Firebase Dispatcher which works but not beyond app killed.

3) Recommended way found is WorkManager to guarantee execution beyond process killed and internally using registerNetworkRequest()

The biggest evidence in favor of #3 approach is referred by Android doc itself. Especially for apps in the background.

Also here

In Android 7.0 we're removing three commonly-used implicit broadcasts — CONNECTIVITY_ACTION, ACTION_NEW_PICTURE, and ACTION_NEW_VIDEO — since those can wake the background processes of multiple apps at once and strain memory and battery. If your app is receiving these, take advantage of the Android 7.0 to migrate to JobScheduler and related APIs instead.

So far it works fine for us using Periodic WorkManager request.

Update: I ended up writing 2 series medium post about it.

Keyboard shortcut to comment lines in Sublime Text 3

This is a keyboard internationalisation issue.

On a standard US QWERTY keyboard, as used in Australia where Sublime Text is made, / is readily available: US QWERTY keyboard

This is not the case with many other keyboards. Take for example the German QWERTZ keyboard. One needs to hit SHIFT+7 to get a /. This is why commenting does not work properly on these keyboards. German QWERTZ keyboard

Changing the user keybindings to those listed below, will work for the German QWERTZ keyboard.

{ "keys": ["ctrl+7"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+7"], "command": "toggle_comment", "args": { "block": true } }

If the problems are occurring with still a different keyboard layout, change the keybindings accordingly.

How can I wrap or break long text/word in a fixed width span?

You can use the CSS property word-wrap:break-word;, which will break words if they are too long for your span width.

_x000D_
_x000D_
span { _x000D_
    display:block;_x000D_
    width:150px;_x000D_
    word-wrap:break-word;_x000D_
}
_x000D_
<span>VeryLongLongLongLongLongLongLongLongLongLongLongLongExample</span>
_x000D_
_x000D_
_x000D_

Warning about `$HTTP_RAW_POST_DATA` being deprecated

I experienced the same issue on nginx server (DigitalOcean) - all I had to do is to log in as root and modify the file /etc/php5/fpm/php.ini.

To find the line with the always_populate_raw_post_data I first run grep:

grep -n 'always_populate_raw_post_data' php.ini

That returned the line 704

704:;always_populate_raw_post_data = -1

Then simply open php.ini on that line with vi editor:

vi +704 php.ini

Remove the semi colon to uncomment it and save the file :wq

Lastly reboot the server and the error went away.

React-router urls don't work when refreshing or writing manually

Using express on the backend and React on the frontend ( without react-create-app) with reach/router, the correct reach/router route react component is shown and the menu link is set to the active style when hitting enter in the address bar e.g http://localhost:8050/pages. Please checkout below, or straight to my repo https://github.com/nickjohngray/staticbackeditor, all the code is there.

Webpack:

Setup proxy. This allows any calls from port 3000 ( React) to call the server including the call to get index.html or anything in the address bar when the enter key is hit. it also allows calls to the API route, to get JSON data

like await axios.post('/api/login', {email, pwd})

devServer: {
    port: 3000,
    open: true,
    proxy: {
      '/': 'http://localhost:8050',
    }
  }

Setup express routes

app.get('*', (req, res) => {
    console.log('sending index.html')
    res.sendFile(path.resolve('dist', 'index.html'))

});

This will match any request from react, it just returns the index.html page, which is in my dist folder this page, of course, has a more single-page react app. ( note any other routes should appear above this, in my case these are my API routes )

React Routes

<Router>
    <Home path="/" />
    <Pages path="pages"/>
    <ErrorPage path="error"/>
    <Products path="products"/>
    <NotFound default />
</Router>

These routes are defined in my Layout component that will load the corresponding component when the path matches.

React Layout constructor

 constructor(props) {
        super(props);


        this.props.changeURL({URL: globalHistory.location.pathname});
}

the Layout constructor is called as soon as it loads. In here I call my redux action changeURL that my menu listens to so it can highlight the correct menu item, like below:

Menu code

<nav>
    {this.state.links.map( (link) =>
    <Link className={this.getActiveLinkClassName(link.path) } to={link.path}> 
      {link.name}
    </Link>)}            
</nav>

What does HTTP/1.1 302 mean exactly?

This question was asked a long ago, while the RFC 2616 was still hanging around. Some answers to this question are based in such document, which is no longer relevant nowadays. Quoting Mark Nottingham who, at the time of writing, co-chairs the IETF HTTP and QUIC Working Groups:

Don’t use RFC2616. Delete it from your hard drives, bookmarks, and burn (or responsibly recycle) any copies that are printed out.

The old RFC 2616 has been supplanted by the following documents that, together, define the HTTP/1.1 protocol:

So I aim to provide an answer based in the RFC 7231 which is the current reference for HTTP/1.1 status codes.

The 302 status code

A response with 302 is a common way of performing URL redirection. Along with the 302 status code, the response should include a Location header with a different URI. Such header will be parsed by the user agent and then perform the redirection:


Redirection example


Web browsers may change from POST to GET in the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

This is how the 302 status code is defined in the RFC 7231:

6.4.3. 302 Found

The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests.

The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server's response payload usually contains a short hypertext note with a hyperlink to the different URI(s).

Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.

According to MDN web docs from Mozilla, a typical use case for 302 is:

The Web page is temporarily not available for reasons that have not been unforeseen. That way, search engines don't update their links.

Other status codes for redirection

The RFC 7231 defines the following status codes for redirection:

  • 301 (Moved Permanently)
  • 302 (Found)
  • 307 (Temporary Redirect)

The RFC 7238 was created to define another status code for redirection:

  • 308 (Permanent Redirect)

Refer to this answer for further details.

SQL not a single-group group function

If you want downloads number for each customer, use:

select ssn
     , sum(time)
  from downloads
 group by ssn

If you want just one record -- for a customer with highest number of downloads -- use:

select *
  from (
        select ssn
             , sum(time)
          from downloads
         group by ssn
         order by sum(time) desc
       )
 where rownum = 1

However if you want to see all customers with the same number of downloads, which share the highest position, use:

select *
  from (
        select ssn
             , sum(time)
             , dense_rank() over (order by sum(time) desc) r
          from downloads
         group by ssn
       )
 where r = 1

Writing a dictionary to a csv file with one line for every 'key: value'

Can you just do:

for key in mydict.keys():
    f.write(str(key) + ":" + str(mydict[key]) + ",");

So that you can have

key_1: value_1, key_2: value_2

Pandas: ValueError: cannot convert float NaN to integer

ValueError: cannot convert float NaN to integer

From v0.24, you actually can. Pandas introduces Nullable Integer Data Types which allows integers to coexist with NaNs.

Given a series of whole float numbers with missing data,

s = pd.Series([1.0, 2.0, np.nan, 4.0])
s

0    1.0
1    2.0
2    NaN
3    4.0
dtype: float64

s.dtype
# dtype('float64')

You can convert it to a nullable int type (choose from one of Int16, Int32, or Int64) with,

s2 = s.astype('Int32') # note the 'I' is uppercase
s2

0      1
1      2
2    NaN
3      4
dtype: Int32

s2.dtype
# Int32Dtype()

Your column needs to have whole numbers for the cast to happen. Anything else will raise a TypeError:

s = pd.Series([1.1, 2.0, np.nan, 4.0])

s.astype('Int32')
# TypeError: cannot safely cast non-equivalent float64 to int32

MySQL - How to select rows where value is in array?

Use the FIND_IN_SET function:

SELECT t.*
  FROM YOUR_TABLE t
 WHERE FIND_IN_SET(3, t.ids) > 0

How do you change Background for a Button MouseOver in WPF?

A slight more difficult answer that uses ControlTemplate and has an animation effect (adapted from https://docs.microsoft.com/en-us/dotnet/framework/wpf/controls/customizing-the-appearance-of-an-existing-control)

In your resource dictionary define a control template for your button like this one:

<ControlTemplate TargetType="Button" x:Key="testButtonTemplate2">
    <Border Name="RootElement">
        <Border.Background>
            <SolidColorBrush x:Name="BorderBrush" Color="Black"/>
        </Border.Background>

        <Grid Margin="4" >
            <Grid.Background>
                <SolidColorBrush x:Name="ButtonBackground" Color="Aquamarine"/>
            </Grid.Background>
            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="4,5,4,4"/>
        </Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="ButtonBackground" Storyboard.TargetProperty="Color" To="Red"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Border>
</ControlTemplate>

in your XAML you can use the template above for your button as below:

Define your button

<Button Template="{StaticResource testButtonTemplate2}" 
HorizontalAlignment="Center" VerticalAlignment="Center" 
Foreground="White">My button</Button>

Hope it helps

Add line break to ::after or ::before pseudo-element content

The content property states:

Authors may include newlines in the generated content by writing the "\A" escape sequence in one of the strings after the 'content' property. This inserted line break is still subject to the 'white-space' property. See "Strings" and "Characters and case" for more information on the "\A" escape sequence.

So you can use:

#headerAgentInfoDetailsPhone:after {
  content:"Office: XXXXX \A Mobile: YYYYY ";
  white-space: pre; /* or pre-wrap */
}

http://jsfiddle.net/XkNxs/

When escaping arbitrary strings, however, it's advisable to use \00000a instead of \A, because any number or [a-f] character followed by the new line may give unpredictable results:

function addTextToStyle(id, text) {
  return `#${id}::after { content: "${text.replace(/"/g, '\\"').replace(/\n/g, '\\00000a')} }"`;
}

Why does Eclipse complain about @Override on interface methods?

Use Eclipse to search and replace (remove) all instances of "@Override". Then add back the non-interface overrides using "Clean Up".

Steps:

  1. Select the projects or folders containing your source files.
  2. Go to "Search > Search..." (Ctrl-H) to bring up the Search dialog.
  3. Go to the "File Search" tab.
  4. Enter "@Override" in "Containing text" and "*.java" in "File name patterns". Click "Replace...", then "OK", to remove all instances of "@Override".
  5. Go to "Window > Preferences > Java > Code Style > Clean Up" and create a new profile.
  6. Edit the profile, and uncheck everything except "Missing Code > Add missing Annotations > @Override". Make sure "Implementations of interface methods" is unchecked.
  7. Select the projects or folders containing your source files.
  8. Select "Source > Clean Up..." (Alt+Shift+s, then u), then "Finish" to add back the non-interface overrides.

What is the Java equivalent of PHP var_dump?

It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString method. So here you need to override toString() in your Person class and return the desired state.

There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString() writing shortcut.

Prompt for user input in PowerShell

Read-Host is a simple option for getting string input from a user.

$name = Read-Host 'What is your username?'

To hide passwords you can use:

$pass = Read-Host 'What is your password?' -AsSecureString

To convert the password to plain text:

[Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))

As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].

To access information without invoking a method, leave the parentheses off:

PS> $Host.UI.Prompt

MemberType          : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
                    ompt(string caption, string message, System.Collections.Ob
                    jectModel.Collection[System.Management.Automation.Host.Fie
                    ldDescription] descriptions)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Collections.Generic.Dictionary[string,psobject] Pro
                    mpt(string caption, string message, System.Collections.Obj
                    ectModel.Collection[System.Management.Automation.Host.Fiel
                    dDescription] descriptions)
Name                : Prompt
IsInstance          : True

$Host.UI.Prompt.OverloadDefinitions will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>).

How to make a div have a fixed size?

you can give it a max-height and max-width in your .css

.fontpixel{max-width:200px; max-height:200px;}

in addition to your height and width properties

Can we make unsigned byte in Java

Adamski provided the best answer, but it is not quite complete, so read his reply, as it explains the details I'm not.

If you have a system function that requires an unsigned byte to be passed to it, you can pass a signed byte as it will automatically treat it as an unsigned byte.

So if a system function requires four bytes, for example, 192 168 0 1 as unsigned bytes you can pass -64 -88 0 1, and the function will still work, because the act of passing them to the function will un-sign them.

However you are unlikely to have this problem as system functions are hidden behind classes for cross-platform compatibility, though some of the java.io read methods return unsighed bytes as an int.

If you want to see this working, try writing signed bytes to a file and read them back as unsigned bytes.

"Expected an indented block" error?

I also experienced that for example:

This code doesnt work and get the intended block error.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
return self.title

However, when i press tab before typing return self.title statement, the code works.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
    return self.title

Hope, this will help others.

What's the difference between "git reset" and "git checkout"?

The two commands (reset and checkout) are completely different.

checkout X IS NOT reset --hard X

If X is a branch name, checkout X will change the current branch while reset --hard X will not.

How to monitor the memory usage of Node.js?

node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js

Two values from one input in python?

if we want to two inputs in a single line so, the code is are as follows enter code here

x,y=input().split(" ")

print(x,y)

after giving value as input we have to give spaces between them because of split(" ") function or method.

but these values are of string type if to perform some arithmetic operations we have to convert the type of x,y are as follows int(x),int(y)

we can do this also with the help of list in python.enter code here

list1=list(map(int,input().split()))
print(list1)

this list gives the elements in int type

How to switch between python 2.7 to python 3 from command line?

They are 3 ways you can achieve this using the py command (py-launcher) in python 3, virtual environment or configuring your default python system path. For illustration purpose, you may see tutorial https://www.youtube.com/watch?v=ynDlb0n27cw&t=38s

Open link in new tab or window

set the target attribute of your <a> element to "_tab"

EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp

EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window
framename   Opens the linked document in a named frame

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I added the following VM Options and it worked for me:

-Dcom.sun.management.jmxremote= 
-Dcom.sun.management.jmxremote.port=1099 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

return string with first match Regex

You shouldn't be using .findall() at all - .search() is what you want. It finds the leftmost match, which is what you want (or returns None if no match exists).

m = re.search(pattern, text)
result = m.group(0) if m else ""

Whether you want to put that in a function is up to you. It's unusual to want to return an empty string if no match is found, which is why nothing like that is built in. It's impossible to get confused about whether .search() on its own finds a match (it returns None if it didn't, or an SRE_Match object if it did).

Maximum value for long integer

Direct answer to title question:

Integers are unlimited in size and have no maximum value in Python.

Answer which addresses stated underlying use case:

According to your comment of what you're trying to do, you are currently thinking something along the lines of

minval = MAXINT;
for (i = 1; i < num_elems; i++)
    if a[i] < a[i-1]
        minval = a[i];

That's not how to think in Python. A better translation to Python (but still not the best) would be

minval = a[0]  # Just use the first value
for i in range(1, len(a)):
    minval = min(a[i], a[i - 1])

Note that the above doesn't use MAXINT at all. That part of the solution applies to any programming language: You don't need to know the highest possible value just to find the smallest value in a collection.

But anyway, what you really do in Python is just

minval = min(a)

That is, you don't write a loop at all. The built-in min() function gets the minimum of the whole collection.

ORA-28000: the account is locked error getting frequently

Login to SQL Plus client on the oracle database server machine.

enter user-name: system

enter password: password [Only if, if you have not changed your default password while DB installation]

press enter. after which, you will be seeing the connection status.

Now,

SQL> ALTER USER [USER_NAME] ACCOUNT UNLOCK;

press enter.

you will be seeing message: user altered.

Now try login with the user name on db client[sqldeveloper].

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

If your maven project is a multi-module project, check if some of the modules are ignored by intellij.

  1. Click on View -> Tool Windows -> Maven Projects, and check if some modules are ignored(Ignored modules are in grey, e.g. gs-multi-module in the following image).

enter image description here

  1. Right click on the ignored module and choose Unignore Projects.

enter image description here

Then wait for intellij to finish indexing, after which it will work.

What does a lazy val do?

scala> lazy val lazyEight = {
     |   println("I am lazy !")
     |   8
     | }
lazyEight: Int = <lazy>

scala> lazyEight
I am lazy !
res1: Int = 8
  • All vals are initialized during object construction
  • Use lazy keyword to defer initialization until first usage
  • Attention: Lazy vals are not final and therefore might show performance drawbacks

SQL Server Script to create a new user

Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.

Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:

CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO

Here is how you create a User with db_owner privileges using the Login you just declared:

Use YourDatabase;
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
    CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
    EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO

Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).

However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.

UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.

How to convert a string to utf-8 in Python

If I understand you correctly, you have a utf-8 encoded byte-string in your code.

Converting a byte-string to a unicode string is known as decoding (unicode -> byte-string is encoding).

You do that by using the unicode function or the decode method. Either:

unicodestr = unicode(bytestr, encoding)
unicodestr = unicode(bytestr, "utf-8")

Or:

unicodestr = bytestr.decode(encoding)
unicodestr = bytestr.decode("utf-8")

How to Display Selected Item in Bootstrap Button Dropdown Title

I was able to slightly improve Jai's answer to work in the case of you having more than one button dropdown with a pretty good presentation that works with bootstrap 3:

Code for The Button

<div class="btn-group">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    Option: <span class="selection">Option 1</span><span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="#">Option 1</a></li>
    <li><a href="#">Option 2</a></li>
    <li><a href="#">Option 3</a></li>
  </ul>
</div>

JQuery Snippet

$(".dropdown-menu li a").click(function(){

  $(this).parents(".btn-group").find('.selection').text($(this).text());
  $(this).parents(".btn-group").find('.selection').val($(this).text());

});

I also added a 5px margin-right to the "selection" class.

OpenCV NoneType object has no attribute shape

It means that somewhere a function which should return a image just returned None and therefore has no shape attribute. Try "print img" to check if your image is None or an actual numpy object.

How do you run a script on login in *nix?

If you are on OSX, then it's ~/.profile

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

Updating PartialView mvc 4

Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.

So, in JS:

$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");

In Controller:

var model = _newPoints;
return PartialView(model);

In View

<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)

Change a Git remote HEAD to point to something besides master

Simple just log into your GitHub account and on the far right side in the navigation menu choose Settings, in the Settings Tab choose Default Branch and return back to main page of your repository that did the trick for me.

PHP: Update multiple MySQL fields in single query

Comma separate the values:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

Filter items which array contains any of given values

Whilst this an old question, I ran into this problem myself recently and some of the answers here are now deprecated (as the comments point out). So for the benefit of others who may have stumbled here:

A term query can be used to find the exact term specified in the reverse index:

{
  "query": {
   "term" : { "tags" : "a" }
} 

From the documenation https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html

Alternatively you can use a terms query, which will match all documents with any of the items specified in the given array:

{
  "query": {
   "terms" : { "tags" : ["a", "c"]}
} 

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-terms-query.html

One gotcha to be aware of (which caught me out) - how you define the document also makes a difference. If the field you're searching in has been indexed as a text type then Elasticsearch will perform a full text search (i.e using an analyzed string).

If you've indexed the field as a keyword then a keyword search using a 'non-analyzed' string is performed. This can have a massive practical impact as Analyzed strings are pre-processed (lowercased, punctuation dropped etc.) See (https://www.elastic.co/guide/en/elasticsearch/guide/master/term-vs-full-text.html)

To avoid these issues, the string field has split into two new types: text, which should be used for full-text search, and keyword, which should be used for keyword search. (https://www.elastic.co/blog/strings-are-dead-long-live-strings)

Is mathematics necessary for programming?

Maths is as much about a way of thinking as it is about the skills themselves. And even that lies on several levels. Someone else noted that the analytical and abstraction skills common to maths are valuable to programming and that is one level. I would also argue that there is another level which contains precise analogues that carry from one to the other - for example the set theory behind relational databases, which is all hidden by the SQL semantics.

Very often the "best" - by which I mean most performant and concise - solutions are those which have a bit of maths behind them. If you start to think about your data-oriented programming problems as matrix manipulation, which many are, you can often find novel solutions form the world of maths.

Obviously it is not necessary to be a maths expert in order to program, anyone can be taught, but it is one of the skills that is worth having - and looking for in recruits.

Using LIKE operator with stored procedure parameters

...
WHERE ...
      AND (@Location is null OR (Location like '%' + @Location + '%'))
      AND (@Date is null OR (Date = @Date))

This way it is more obvious the parameter is not used when null.

java.lang.NoClassDefFoundError: Could not initialize class XXX

NoClassDefFoundError doesn't give much of a clue as to what went wrong inside the static block. It is good practice to always have a block like this inside of static { ... } initialization code:

static {
  try {

    ... your init code here

  } catch (Throwable t) {
    LOG.error("Failure during static initialization", t);
    throw t;
  }
}

How to convert string to integer in C#

class MyMath
{
    public dynamic Sum(dynamic x, dynamic y)
    {
        return (x+y);
    }
}

class Demo
{
    static void Main(string[] args)
    {
        MyMath d = new MyMath();
        Console.WriteLine(d.Sum(23.2, 32.2));
    }
}

Perform a Shapiro-Wilk Normality Test

You failed to specify the exact columns (data) to test for normality. Use this instead

shapiro.test(heisenberg$HWWIchg)

Submit a form using jQuery

you could use it like this :

  $('#formId').submit();

OR

document.formName.submit();

CSS ''background-color" attribute not working on checkbox inside <div>

After so much trouble i got it.

.purple_checkbox:after {
  content: " ";
  background-color: #5C2799;
  display: inline-block;
  visibility: visible;
}

.purple_checkbox:checked:after {
  content: "\2714";
  box-shadow: 0px 2px 4px rgba(155, 155, 155, 0.15);
  border-radius: 3px;
  height: 12px;
  display: block;
  width: 12px;
  text-align: center;
  font-size: 9px;
  color: white;
}

It will be like this when checked with this code. enter image description here

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

nchar requires more space than nvarchar.

eg,

A nchar(100) will always store 100 characters even if you only enter 5, the remaining 95 chars will be padded with spaces. Storing 5 characters in a nvarchar(100) will save 5 characters.

How to push to History in React Router v4?

I struggled with the same topic. I'm using react-router-dom 5, Redux 4 and BrowserRouter. I prefer function based components and hooks.

You define your component like this

import { useHistory } from "react-router-dom";
import { useDispatch } from "react-redux";

const Component = () => {
  ...
  const history = useHistory();
  dispatch(myActionCreator(otherValues, history));
};

And your action creator is following

const myActionCreator = (otherValues, history) => async (dispatch) => {
  ...
  history.push("/path");
}

You can of course have simpler action creator if async is not needed

How do I upgrade to Python 3.6 with conda?

In the past, I have found it quite difficult to try to upgrade in-place.

Note: my use-case for Anaconda is as an all-in-one Python environment. I don't bother with separate virtual environments. If you're using conda to create environments, this may be destructive because conda creates environments with hard-links inside your Anaconda/envs directory.

So if you use environments, you may first want to export your environments. After activating your environment, do something like:

conda env export > environment.yml

After backing up your environments (if necessary), you may remove your old Anaconda (it's very simple to uninstall Anaconda):

$ rm -rf ~/anaconda3/

and replace it by downloading the new Anaconda, e.g. Linux, 64 bit:

$ cd ~/Downloads
$ wget https://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh 

(see here for a more recent one),

and then executing it:

$ bash Anaconda3-4.3.0-Linux-x86_64.sh 

How do you check current view controller class in Swift?

For types you can use is and if it is your own viewcontroller class then you need to use isKindOfClass like:

let vcOnTop = self.embeddedNav.viewControllers[self.embeddedNav.viewControllers.count-1]
            if vcOnTop.isKindOfClass(VcShowDirections){
                return
            }

Temporarily change current working directory in bash to run a command

You can run the cd and the executable in a subshell by enclosing the command line in a pair of parentheses:

(cd SOME_PATH && exec_some_command)

Demo:

$ pwd
/home/abhijit
$ (cd /tmp && pwd)  # directory changed in the subshell
/tmp 
$ pwd               # parent shell's pwd is still the same
/home/abhijit

Virtual member call in a constructor

When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class (see Eric Lippert's blog for details as to why this is).

Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.

When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called.

This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.

React Router with optional path parameter

If you are looking to do an exact match, use the following syntax: (param)?.

Eg.

<Route path={`my/(exact)?/path`} component={MyComponent} />

The nice thing about this is that you'll have props.match to play with, and you don't need to worry about checking the value of the optional parameter:

{ props: { match: { "0": "exact" } } }

JAVA_HOME and PATH are set but java -version still shows the old one

Updating the ~/.profile or ~/.bash_profile does not work sometimes. I just deleted JDK 6 and sourced .bash_profile.

Try running this:

sudo rm -rd jdk1.6.0_* #it may not let you delete without sudo

Then, modify/add your JAVA_HOME and PATH variables.

source ~/.bash_profile #assuming you've updated $JAVA_HOME and $PATH

When to use a linked list over an array/array list?

Linked lists are preferable over arrays when:

  1. you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is absolutely critical)

  2. you don't know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big

  3. you don't need random access to any elements

  4. you want to be able to insert items in the middle of the list (such as a priority queue)

Arrays are preferable when:

  1. you need indexed/random access to elements

  2. you know the number of elements in the array ahead of time so that you can allocate the correct amount of memory for the array

  3. you need speed when iterating through all the elements in sequence. You can use pointer math on the array to access each element, whereas you need to lookup the node based on the pointer for each element in linked list, which may result in page faults which may result in performance hits.

  4. memory is a concern. Filled arrays take up less memory than linked lists. Each element in the array is just the data. Each linked list node requires the data as well as one (or more) pointers to the other elements in the linked list.

Array Lists (like those in .Net) give you the benefits of arrays, but dynamically allocate resources for you so that you don't need to worry too much about list size and you can delete items at any index without any effort or re-shuffling elements around. Performance-wise, arraylists are slower than raw arrays.

Oracle get previous day records

SELECT field,datetime_field 
FROM database
WHERE datetime_field > (CURRENT_DATE - 1)

Its been some time that I worked on Oracle. But, I think this should work.