Programs & Examples On #Pysqlite

A DB-API2 compliant module in Python for interacting with a SQLite relational database.

Python SQLite: database is locked

Easy solution: check once if you have opened the database in another window or in another terminal. That also locks your database. In my case, I closed all the other terminals that were locking the database (a terminal tab in Pycharm). Check each tab of the terminals of your IDE as well if there is a terminal that left the database open. exit() all the terminals should work unlocking the database.

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

How to do a redirect to another route with react-router?

For the simple answer, you can use Link component from react-router, instead of button. There is ways to change the route in JS, but seems you don't need that here.

<span className="input-group-btn">
  <Link to="/login" />Click to login</Link>
</span>

To do it programmatically in 1.0.x, you do like this, inside your clickHandler function:

this.history.pushState(null, 'login');

Taken from upgrade doc here

You should have this.history placed on your route handler component by react-router. If it child component beneath that mentioned in routes definition, you may need pass that down further

Is it possible to Turn page programmatically in UIPageViewController?

Here's another code example for a single paged view. Implementation for viewControllerAtIndex is omitted here, it should return the correct view controller for the given index.

- (void)changePage:(UIPageViewControllerNavigationDirection)direction {
    NSUInteger pageIndex = ((FooViewController *) [_pageViewController.viewControllers objectAtIndex:0]).pageIndex;

    if (direction == UIPageViewControllerNavigationDirectionForward) {
        pageIndex++;
    }
    else {
        pageIndex--;
    }

    FooViewController *viewController = [self viewControllerAtIndex:pageIndex];

    if (viewController == nil) {
        return;
    }

    [_pageViewController setViewControllers:@[viewController]
                                  direction:direction
                                   animated:YES
                                 completion:nil];
}

Pages can be changed by calling

[self changePage:UIPageViewControllerNavigationDirectionReverse];
[self changePage:UIPageViewControllerNavigationDirectionForward];

Concatenate text files with Windows command line, dropping leading lines

more +2 file2.txt > temp
type temp file1.txt > out.txt

or you can use copy. See copy /? for more.

copy /b temp+file1.txt  out.txt

transform object to array with lodash

Object to Array

Of all the answers I think this one is the best:

let arr = Object.entries(obj).map(([key, val]) => ({ key, ...val }))

that transforms:

{
  a: { p: 1, q: 2},
  b: { p: 3, q: 4}
}

to:

[
  { key: 'a', p: 1, q: 2 }, 
  { key: 'b', p: 3, q: 4 }
]

Array to Object

To transform back:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { ...val }; return obj; }, {})

To transform back keeping the key in the value:

let obj = arr.reduce((obj, { key, ...val }) => { obj[key] = { key, ...val }; return obj; }, {})

Will give:

{
  a: { key: 'a', p: 1, q: 2 },
  b: { key: 'b', p: 3, q: 4 }
}

For the last example you can also use lodash _.keyBy(arr, 'key') or _.keyBy(arr, i => i.key).

MySQL Event Scheduler on a specific time everyday

Try this

CREATE EVENT event1
ON SCHEDULE EVERY '1' DAY
STARTS '2012-04-17 13:00:00' -- should be in the future
DO
-- your statements
END

What is the difference between HTTP status code 200 (cache) vs status code 304?

The items with code "200 (cache)" were fulfilled directly from your browser cache, meaning that the original requests for the items were returned with headers indicating that the browser could cache them (e.g. future-dated Expires or Cache-Control: max-age headers), and that at the time you triggered the new request, those cached objects were still stored in local cache and had not yet expired.

304s, on the other hand, are the response of the server after the browser has checked if a file was modified since the last version it had cached (the answer being "no").

For most optimal web performance, you're best off setting a far-future Expires: or Cache-Control: max-age header for all assets, and then when an asset needs to be changed, changing the actual filename of the asset or appending a version string to requests for that asset. This eliminates the need for any request to be made unless the asset has definitely changed from the version in cache (no need for that 304 response). Google has more details on correct use of long-term caching.

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

Argument of type 'X' is not assignable to parameter of type 'X'

For what it worth, if anyone has this problem only in VSCode, just restart VSCode and it should fix it. Sometimes, Intellisense seems to mess up with imports or types.

Related to Typescript: Argument of type 'RegExpMatchArray' is not assignable to parameter of type 'string'

slideToggle JQuery right to left

You can try this:

$('.show_hide').click(function () {
    $(".slidingDiv").toggle("'slide', {direction: 'right' }, 1000");
});

HTML span align center not working?

On top of all the other explanations, I believe you're using equal "=" sign, instead of colon ":":

<span style="border:1px solid red;text-align=center">

It should be:

<span style="border:1px solid red;text-align:center">

Check if a file exists with wildcard in shell script

IMHO it's better to use find always when testing for files, globs or directories. The stumbling block in doing so is find's exit status: 0 if all paths were traversed successfully, >0 otherwise. The expression you passed to find creates no echo in its exit code.

The following example tests if a directory has entries:

$ mkdir A
$ touch A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty'
not empty

When A has no files grep fails:

$ rm A/b
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . || echo 'empty'
empty

When A does not exist grep fails again because find only prints to stderr:

$ rmdir A
$ find A -maxdepth 0 -not -empty -print | head -n1 | grep -q . && echo 'not empty' || echo 'empty'
find: 'A': No such file or directory
empty

Replace -not -empty by any other find expression, but be careful if you -exec a command that prints to stdout. You may want to grep for a more specific expression in such cases.

This approach works nicely in shell scripts. The originally question was to look for the glob xorg-x11-fonts*:

if find -maxdepth 0 -name 'xorg-x11-fonts*' -print | head -n1 | grep -q .
then
    : the glob matched
else
    : ...not
fi

Note that the else-branched is reached if xorg-x11-fonts* had not matched, or find encountered an error. To distinguish the case use $?.

Logging best practices

What frameworks do you use?

We use a mix of the logging application block, and a custom logging helper that works around the .Net framework bits. The LAB is configured to output fairly extensive log files included seperate general trace files for service method entry/exit and specific error files for unexpected issues. The configuration includes date/time, thread, pId etc. for debug assistance as well as the full exception detail and stack (in the case of an unexpected exception).

The custom logging helper makes use of the Trace.Correlation and is particularly handy in the context of logging in WF. For example we have a state machine that invokes a series of sequential workflows. At each of these invoke activities we log the start (using StartLogicalOperation) and then at the end we stop the logical operation with a gereric return event handler.

This has proven useful a few times when attempting to debug failures in complex business sequences as it allows us to determine things like If/Else branch decisions etc. more quickly based on the activity execution sequence.

What log outputs do you use?

We use text files and XML files. Text files are configured through the app block but we've got XML outputs as well from our WF service. This enables us to capture the runtime events (persistence etc.) as well as generic business type exceptions. The text files are rolling logs that are rolled by day and size (I believe total size of 1MB is a rollover point).

What tools to you use for viewing the logs?

We are using Notepad and WCF Service Trace Viewer depending on which output group we're looking at. The WCF Service Trace Viewer is really really handy if you've got your output setup correctly and can make reading the output much simpler. That said, if I know roughly where the error is anyway - just reading a well annotated text file is good as well.

The logs are sent to a single directory which is then split into sub-dirs based on the source service. The root dir is exposed via a website which has it's access controlled by a support user group. This allows us to take a look at production logs without having to put in requests and go through lengthy red tape processes for production data.

How to copy sheets to another workbook using vba?

Assuming all your macros are in modules, maybe this link will help. After copying the workbook, just iterate over each module and delete it

Jquery Setting Value of Input Field

$('.formData').attr('value','YOUR_VALUE')

Naming returned columns in Pandas aggregate function?

With the inspiration of @Joel Ostblom

For those who already have a workable dictionary for merely aggregation, you can use/modify the following code for the newer version aggregation, separating aggregation and renaming part. Please be aware of the nested dictionary if there are more than 1 item.

def agg_translate_agg_rename(input_agg_dict):
    agg_dict = {}
    rename_dict = {}
    for k, v in input_agg_dict.items():
        if len(v) == 1:
            agg_dict[k] = list(v.values())[0]
            rename_dict[k] = list(v.keys())[0]
        else:
            updated_index = 1
            for nested_dict_k, nested_dict_v in v.items():
                modified_key = k + "_" + str(updated_index)
                agg_dict[modified_key] = nested_dict_v
                rename_dict[modified_key] = nested_dict_k
                updated_index += 1
    return agg_dict, rename_dict

one_dict = {"column1": {"foo": 'sum'}, "column2": {"mean": 'mean', "std": 'std'}}
agg, rename = agg_translator_aa(one_dict)

We get

agg = {'column1': 'sum', 'column2_1': 'mean', 'column2_2': 'std'}
rename = {'column1': 'foo', 'column2_1': 'mean', 'column2_2': 'std'}

Please let me know if there is a smarter way to do it. Thanks.

Setting environment variable in react-native?

React native does not have the concept of global variables. It enforces modular scope strictly, in order to promote component modularity and reusability.

Sometimes, though, you need components to be aware of their environment. In this case it's very simple to define an Environment module which components can then call to get environment variables, for example:

environment.js

var _Environments = {
    production:  {BASE_URL: '', API_KEY: ''},
    staging:     {BASE_URL: '', API_KEY: ''},
    development: {BASE_URL: '', API_KEY: ''},
}

function getEnvironment() {
    // Insert logic here to get the current platform (e.g. staging, production, etc)
    var platform = getPlatform()

    // ...now return the correct environment
    return _Environments[platform]
}

var Environment = getEnvironment()
module.exports = Environment

my-component.js

var Environment = require('./environment.js')

...somewhere in your code...
var url = Environment.BASE_URL

This creates a singleton environment which can be accessed from anywhere inside the scope of your app. You have to explicitly require(...) the module from any components that use Environment variables, but that is a good thing.

Change User Agent in UIWebView

Try this in the AppDelegate.m

+ (void)initialize 

{

    // Set user agent (the only problem is that we can’t modify the User-Agent later in the program)

    // iOS 5.1

    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:@”Mozilla/5.0 (iPad; CPU OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B176 Safari/7534.48.3”, @”UserAgent”, nil];


    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

}

How to know if other threads have finished?

Here's a solution that is simple, short, easy to understand, and works perfectly for me. I needed to draw to the screen when another thread ends; but couldn't because the main thread has control of the screen. So:

(1) I created the global variable: boolean end1 = false; The thread sets it to true when ending. That is picked up in the mainthread by "postDelayed" loop, where it is responded to.

(2) My thread contains:

void myThread() {
    end1 = false;
    new CountDownTimer(((60000, 1000) { // milliseconds for onFinish, onTick
        public void onFinish()
        {
            // do stuff here once at end of time.
            end1 = true; // signal that the thread has ended.
        }
        public void onTick(long millisUntilFinished)
        {
          // do stuff here repeatedly.
        }
    }.start();

}

(3) Fortunately, "postDelayed" runs in the main thread, so that's where in check the other thread once each second. When the other thread ends, this can begin whatever we want to do next.

Handler h1 = new Handler();

private void checkThread() {
   h1.postDelayed(new Runnable() {
      public void run() {
         if (end1)
            // resond to the second thread ending here.
         else
            h1.postDelayed(this, 1000);
      }
   }, 1000);
}

(4) Finally, start the whole thing running somewhere in your code by calling:

void startThread()
{
   myThread();
   checkThread();
}

Remove leading comma from a string

this will remove the trailing commas and spaces

var str = ",'first string','more','even more'";
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');

How to get the absolute path to the public_html folder?

something I found today, after reading this question and continuing on my googlesurf:

https://docs.joomla.org/How_to_find_your_absolute_path

<?php
$path = getcwd();
echo "This Is Your Absolute Path: ";
echo $path;
?>

works for me

Multiple inputs on one line

Yes, you can input multiple items from cin, using exactly the syntax you describe. The result is essentially identical to:

cin >> a;
cin >> b;
cin >> c;

This is due to a technique called "operator chaining".

Each call to operator>>(istream&, T) (where T is some arbitrary type) returns a reference to its first argument. So cin >> a returns cin, which can be used as (cin>>a)>>b and so forth.

Note that each call to operator>>(istream&, T) first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.

PHPExcel - creating multiple sheets by iteration

You can write different sheets as follows

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("creater");
$objPHPExcel->getProperties()->setLastModifiedBy("Middle field");
$objPHPExcel->getProperties()->setSubject("Subject");
$objWorkSheet = $objPHPExcel->createSheet();
$work_sheet_count=3;//number of sheets you want to create
$work_sheet=0;
while($work_sheet<=$work_sheet_count){ 
     if($work_sheet==0){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 1')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==1){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 2')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==2){
         $objWorkSheet = $objPHPExcel->createSheet($work_sheet_count);
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 3')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     $work_sheet++;
}

$filename='file-name'.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cach

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

How to error handle 1004 Error with WorksheetFunction.VLookup?

Instead of WorksheetFunction.Vlookup, you can use Application.Vlookup. If you set a Variant equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum in this case - with IsError:

Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant

'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
    MsgBox "no match"
Else
    MsgBox cellNum
End If
End Sub

The Application versions of the VLOOKUP and MATCH functions allow you to test for errors without raising the error. If you use the WorksheetFunction version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application functions, you can avoid that mess.

The above could be further simplified using the IIF function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:

cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)

Consider those methods instead of On Error ... statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo and Resume statements.

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

This should should work: =IF(A1=1, B1)

The 3rd argument stating the value of the cell if the condition is not met is optional.

CSS checkbox input styling

With CSS 2 you can do this:

input[type='checkbox'] { ... }

This should be pretty widely supported by now. See support for browsers

How to clear form after submit in Angular 2?

Here is how I do it in Angular 7.3

// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {

    form.reset();

    Object.keys(form.controls).forEach(key => {
      form.get(key).setErrors(null) ;
    });
}

There was no need to call form.clearValidators()

Git - how delete file from remote repository

The easiest thing to do is to move the file from your local directory temporarily, then commit changes to your remote repo. Then add it back to your local repo, make sure to update .gitignore so it doesn't commit to remote again

What is the equivalent of 'describe table' in SQL Server?

In addition to above questions, if we have table in DB like db_name.dbo.table_name, we may use following steps

  1. Connect with DB

    USE db_name;

  2. Use EXEC sp_help and don't forget to put table name as 'dbo.tablename' if you have dbo as schema.

    exec sp_help 'dbo.table_name'

This should work!

What is the purpose of Looper and how to use it?

Android Looper is a wrapper to attach MessageQueue to Thread and it manages Queue processing. It looks very cryptic in Android documentation and many times we may face Looper related UI access issues. If we don't understand the basics it becomes very tough to handle.

Here is an article which explains Looper life cycle, how to use it and usage of Looper in Handler

enter image description here

Looper = Thread + MessageQueue

Using NSLog for debugging

Try this piece of code:

NSString *digit = [[sender titlelabel] text];
NSLog(@"%@", digit);

The message means that you have incorrect syntax for using the digit variable. If you're not sending it any message - you don't need any brackets.

Allow only numeric value in textbox using Javascript

@Shane, you could code break anytime, any user could press and hold any text key like (hhhhhhhhh) and your could should allow to leave that value intact.

For safer side, use this:

$("#testInput").keypress(function(event){

instead of:

$("#testInput").keyup(function(event){

I hope this will help for someone.

Raising a number to a power in Java

Your calculation is likely the culprit. Try using:

bmi = weight / Math.pow(height / 100.0, 2.0);

Because both height and 100 are integers, you were likely getting the wrong answer when dividing. However, 100.0 is a double. I suggest you make weight a double as well. Also, the ^ operator is not for powers. Use the Math.pow() method instead.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Call Javascript onchange event by programmatically changing textbox value

Onchange is only fired when user enters something by keyboard. A possible workarround could be to first focus the textfield and then change it.

But why not fetch the event when the user clicks on a date? There already must be some javascript.

Div Size Automatically size of content

I faced the same issue and I resolved it by using: max-width: fit-content;

How can I compare two lists in python and return matches

Not the most efficient one, but by far the most obvious way to do it is:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}

if order is significant you can do it with list comprehensions like this:

>>> [i for i, j in zip(a, b) if i == j]
[5]

(only works for equal-sized lists, which order-significance implies).

How to define the css :hover state in a jQuery selector?

I know this has an accepted answer but if anyone comes upon this, my solution may help.

I found this question because I have a use-case where I wanted to turn off the :hover state for elements individually. Since there is no way to do this in the DOM, another good way to do it is to define a class in CSS that overrides the hover state.

For instance, the css:

.nohover:hover {
    color: black !important;
}

Then with jQuery:

$("#elm").addClass("nohover");

With this method, you can override as many DOM elements as you would like without binding tons of onHover events.

CSS3 opacity gradient?

You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.

CSS:

p {
    color: red;
    -webkit-mask-image: -webkit-gradient(linear, left top, left bottom, 
    from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}

The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)

See a demo with a solid background, but you can change this to whatever you want.

DEMO

Notice also that all the usual image properties are available for mask-image

_x000D_
_x000D_
p  {_x000D_
  color: red;_x000D_
  font-size: 30px;_x000D_
  -webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
  -webkit-mask-size: 100% 50%;_x000D_
  -webkit-mask-repeat: no-repeat;_x000D_
  -webkit-mask-position: left top, left bottom;_x000D_
  }_x000D_
_x000D_
div {_x000D_
    background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.

The idea is to use

mix-blend-mode: hard-light;

that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency

_x000D_
_x000D_
div {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
  color: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
  width: 200px;_x000D_
  mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
  left: 0px;_x000D_
  top: 0px;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(transparent, gray);_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
_x000D_
_x000D_

passing 2 $index values within nested ng-repeat

Just use ng-repeat="(sectionIndex, section) in sections"

and that will be useable on the next level ng-repeat down.

<ul ng-repeat="(sectionIndex, section) in sections">
    <li  class="section_title {{section.active}}" >
        {{section.name}}
    </li>
    <ul>
        <li ng-repeat="tutorial in section.tutorials">
            {{tutorial.name}}, Your section index is {{sectionIndex}}
        </li>
    </ul>
</ul>

How to POST raw whole JSON in the body of a Retrofit request?

In Retrofit2, When you want to send your parameters in raw you must use Scalars.

first add this in your gradle:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'

Your Interface

public interface ApiInterface {

    String URL_BASE = "http://10.157.102.22/rest/";

    @Headers("Content-Type: application/json")
    @POST("login")
    Call<User> getUser(@Body String body);

}

Activity

   public class SampleActivity extends AppCompatActivity implements Callback<User> {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiInterface.URL_BASE)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ApiInterface apiInterface = retrofit.create(ApiInterface.class);


        // prepare call in Retrofit 2.0
        try {
            JSONObject paramObject = new JSONObject();
            paramObject.put("email", "[email protected]");
            paramObject.put("pass", "4384984938943");

            Call<User> userCall = apiInterface.getUser(paramObject.toString());
            userCall.enqueue(this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onResponse(Call<User> call, Response<User> response) {
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
    }
}

How to update ruby on linux (ubuntu)?

the above is not bad, however its kinda different for 11.10

sudo apt-get install ruby1.9 rubygems1.9

that will install ruby 1.9

when linking, you just use ls /usr/bin | grep ruby it should output ruby1.9.1

so then you sudo ln -sf /usr/bin/ruby1.9.1 /usr/bin/ruby and your off to the races.

How to load data from a text file in a PostgreSQL database?

The slightly modified version of COPY below worked better for me, where I specify the CSV format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT.

COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );

Is there a library function for Root mean square error (RMSE) in python?

What is RMSE? Also known as MSE, RMD, or RMS. What problem does it solve?

If you understand RMSE: (Root mean squared error), MSE: (Mean Squared Error) RMD (Root mean squared deviation) and RMS: (Root Mean Squared), then asking for a library to calculate this for you is unnecessary over-engineering. All these metrics are a single line of python code at most 2 inches long. The three metrics rmse, mse, rmd, and rms are at their core conceptually identical.

RMSE answers the question: "How similar, on average, are the numbers in list1 to list2?". The two lists must be the same size. I want to "wash out the noise between any two given elements, wash out the size of the data collected, and get a single number feel for change over time".

Intuition and ELI5 for RMSE:

Imagine you are learning to throw darts at a dart board. Every day you practice for one hour. You want to figure out if you are getting better or getting worse. So every day you make 10 throws and measure the distance between the bullseye and where your dart hit.

You make a list of those numbers list1. Use the root mean squared error between the distances at day 1 and a list2 containing all zeros. Do the same on the 2nd and nth days. What you will get is a single number that hopefully decreases over time. When your RMSE number is zero, you hit bullseyes every time. If the rmse number goes up, you are getting worse.

Example in calculating root mean squared error in python:

import numpy as np
d = [0.000, 0.166, 0.333]   #ideal target distances, these can be all zeros.
p = [0.000, 0.254, 0.998]   #your performance goes here

print("d is: " + str(["%.8f" % elem for elem in d]))
print("p is: " + str(["%.8f" % elem for elem in p]))

def rmse(predictions, targets):
    return np.sqrt(((predictions - targets) ** 2).mean())

rmse_val = rmse(np.array(d), np.array(p))
print("rms error is: " + str(rmse_val))

Which prints:

d is: ['0.00000000', '0.16600000', '0.33300000']
p is: ['0.00000000', '0.25400000', '0.99800000']
rms error between lists d and p is: 0.387284994115

The mathematical notation:

root mean squared deviation explained

Glyph Legend: n is a whole positive integer representing the number of throws. i represents a whole positive integer counter that enumerates sum. d stands for the ideal distances, the list2 containing all zeros in above example. p stands for performance, the list1 in the above example. superscript 2 stands for numeric squared. di is the i'th index of d. pi is the i'th index of p.

The rmse done in small steps so it can be understood:

def rmse(predictions, targets):

    differences = predictions - targets                       #the DIFFERENCEs.

    differences_squared = differences ** 2                    #the SQUAREs of ^

    mean_of_differences_squared = differences_squared.mean()  #the MEAN of ^

    rmse_val = np.sqrt(mean_of_differences_squared)           #ROOT of ^

    return rmse_val                                           #get the ^

How does every step of RMSE work:

Subtracting one number from another gives you the distance between them.

8 - 5 = 3         #absolute distance between 8 and 5 is +3
-20 - 10 = -30    #absolute distance between -20 and 10 is +30

If you multiply any number times itself, the result is always positive because negative times negative is positive:

3*3     = 9   = positive
-30*-30 = 900 = positive

Add them all up, but wait, then an array with many elements would have a larger error than a small array, so average them by the number of elements.

But wait, we squared them all earlier to force them positive. Undo the damage with a square root!

That leaves you with a single number that represents, on average, the distance between every value of list1 to it's corresponding element value of list2.

If the RMSE value goes down over time we are happy because variance is decreasing.

RMSE isn't the most accurate line fitting strategy, total least squares is:

Root mean squared error measures the vertical distance between the point and the line, so if your data is shaped like a banana, flat near the bottom and steep near the top, then the RMSE will report greater distances to points high, but short distances to points low when in fact the distances are equivalent. This causes a skew where the line prefers to be closer to points high than low.

If this is a problem the total least squares method fixes this: https://mubaris.com/posts/linear-regression

Gotchas that can break this RMSE function:

If there are nulls or infinity in either input list, then output rmse value is is going to not make sense. There are three strategies to deal with nulls / missing values / infinities in either list: Ignore that component, zero it out or add a best guess or a uniform random noise to all timesteps. Each remedy has its pros and cons depending on what your data means. In general ignoring any component with a missing value is preferred, but this biases the RMSE toward zero making you think performance has improved when it really hasn't. Adding random noise on a best guess could be preferred if there are lots of missing values.

In order to guarantee relative correctness of the RMSE output, you must eliminate all nulls/infinites from the input.

RMSE has zero tolerance for outlier data points which don't belong

Root mean squared error squares relies on all data being right and all are counted as equal. That means one stray point that's way out in left field is going to totally ruin the whole calculation. To handle outlier data points and dismiss their tremendous influence after a certain threshold, see Robust estimators that build in a threshold for dismissal of outliers.

UnsatisfiedDependencyException: Error creating bean with name

Add @Component annotation just above the component definition

Representing Directory & File Structure in Markdown Syntax

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

Modifying a subset of rows in a pandas dataframe

To replace multiples columns convert to numpy array using .values:

df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2

What is the right way to populate a DropDownList from a database?

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();

EDIT - More complete example

private void LoadSubjects()
{

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
            adapter.Fill(subjects);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
            ddlSubject.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

}

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

from the code-behind, or you'll have two "" items.

How to declare a structure in a header that is to be used by multiple files in c?

For a structure definition that is to be used across more than one source file, you should definitely put it in a header file. Then include that header file in any source file that needs the structure.

The extern declaration is not used for structure definitions, but is instead used for variable declarations (that is, some data value with a structure type that you have defined). If you want to use the same variable across more than one source file, declare it as extern in a header file like:

extern struct a myAValue;

Then, in one source file, define the actual variable:

struct a myAValue;

If you forget to do this or accidentally define it in two source files, the linker will let you know about this.

VBA: How to delete filtered rows in Excel?

As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.

ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)

As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().

How do I hide certain files from the sidebar in Visual Studio Code?

I would also like to recommend vscode extension Peep, which allows you to toggle hide on the excluded files in your projects settings.json.

Hit F1 for vscode command line (command palette), then

ext install [enter] peep [enter]

You can bind "extension.peepToggle" to a key like Ctrl+Shift+P (same as F1 by default) for easy toggling. Hit Ctrl+K Ctrl+S for key bindings, enter peep, select Peep Toggle and add your binding.

Arduino Tools > Serial Port greyed out

chdmod works for my under debian (proxmox):

# chmod a+rw /dev/ttyACM0

For installing arduino IDE:

# apt-get install arduino arduino-core arduino-mk

Add the user to dialout group:

# gpasswd -a user dialout

Restart Linux.

Try with the File > Examples > 01.Basic > Blink, change the 2 delays to delay(60) and click the upload button for testing on arduino, led must blink faster. ;)

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

I'm going to assume that you do not have your secrets.yml checked into source control (ie. it's in the .gitignore file). Even if this isn't your situation, it's what many other people viewing this question have done because they have their code exposed on Github and don't want their secret key floating around.

If it's not in source control, Heroku doesn't know about it. So Rails is looking for Rails.application.secrets.secret_key_base and it hasn't been set because Rails sets it by checking the secrets.yml file which doesn't exist. The simple workaround is to go into your config/environments/production.rb file and add the following line:

Rails.application.configure do
    ...
    config.secret_key_base = ENV["SECRET_KEY_BASE"]
    ...
end

This tells your application to set the secret key using the environment variable instead of looking for it in secrets.yml. It would have saved me a lot of time to know this up front.

Should I use PATCH or PUT in my REST API?

I would recommend using PATCH, because your resource 'group' has many properties but in this case, you are updating only the activation field(partial modification)

according to the RFC5789 (https://tools.ietf.org/html/rfc5789)

The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Also, in more details,

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource
identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version
be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it
also MAY have side effects on other resources; i.e., new resources
may be created, or existing ones modified, by the application of a
PATCH.

PATCH is neither safe nor idempotent as defined by [RFC2616], Section 9.1.

Clients need to choose when to use PATCH rather than PUT. For
example, if the patch document size is larger than the size of the
new resource data that would be used in a PUT, then it might make
sense to use PUT instead of PATCH. A comparison to POST is even more difficult, because POST is used in widely varying ways and can
encompass PUT and PATCH-like operations if the server chooses. If
the operation does not modify the resource identified by the Request- URI in a predictable way, POST should be considered instead of PATCH
or PUT.

The response code for PATCH is

The 204 response code is used because the response does not carry a message body (which a response with the 200 code would have). Note that other success codes could be used as well.

also refer thttp://restcookbook.com/HTTP%20Methods/patch/

Caveat: An API implementing PATCH must patch atomically. It MUST not be possible that resources are half-patched when requested by a GET.

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:

foo[]=val1&foo[]=val2&foo[]=val3

Angular ReactiveForms: Producing an array of checkbox values?

If you want to use an Angular reactive form (https://angular.io/guide/reactive-forms).

You can use one form control to manage the outputted value of the group of checkboxes.

component

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { flow } from 'lodash';
import { flatMap, filter } from 'lodash/fp';

@Component({
  selector: 'multi-checkbox',
  templateUrl: './multi-checkbox.layout.html',
})
export class MultiChecboxComponent  {

  checklistState = [ 
      {
        label: 'Frodo Baggins',
        value: 'frodo_baggins',
        checked: false
      },
      {
        label: 'Samwise Gamgee',
        value: 'samwise_gamgee',
        checked: true,
      },
      {
        label: 'Merry Brandybuck',
        value: 'merry_brandybuck',
        checked: false
      }
    ];

  form = new FormGroup({
    checklist : new FormControl(this.flattenValues(this.checklistState)),
  });


  checklist = this.form.get('checklist');

  onChecklistChange(checked, checkbox) {
    checkbox.checked = checked;
    this.checklist.setValue(this.flattenValues(this.checklistState));
  }

  flattenValues(checkboxes) {
    const flattenedValues = flow([
      filter(checkbox => checkbox.checked),
      flatMap(checkbox => checkbox.value )
    ])(checkboxes)
    return flattenedValues.join(',');
  }
}

html

<form [formGroup]="form">
    <label *ngFor="let checkbox of checklistState" class="checkbox-control">
    <input type="checkbox" (change)="onChecklistChange($event.target.checked, checkbox)" [checked]="checkbox.checked" [value]="checkbox.value" /> {{ checkbox.label }}
  </label>
</form>

checklistState

Manages the model/state of the checklist inputs. This model allows you to map the current state to whatever value format you need.

Model:

{
   label: 'Value 1',
   value: 'value_1',
   checked: false
},
{
  label: 'Samwise Gamgee',
  value: 'samwise_gamgee',
  checked: true,
},
{
  label: 'Merry Brandybuck',
  value: 'merry_brandybuck',
  checked: false
}

checklist Form Control

This control stores the value would like to save as e.g

value output: "value_1,value_2"

See demo at https://stackblitz.com/edit/angular-multi-checklist

PHP not displaying errors even though display_errors = On

I had the same problem but I used ini_set('display_errors', '1'); inside the faulty script itself so it never fires on fatal / syntax errors. Finally I solved it by adding this to my .htaccess:

php_value auto_prepend_file /usr/www/{YOUR_PATH}/display_errors.php

display_errors.php:

<?php
ini_set('display_errors', 1);
error_reporting(-1);
?>

By that I was not forced to change the php.ini, use it for specific subfolders and could easily disable it again.

Using %f with strftime() in Python to get microseconds

This should do the work

import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")

It will print

HH:MM:SS.microseconds like this e.g 14:38:19.425961

Remove all stylings (border, glow) from textarea

if no luck with above try to it a class or even id something like textarea.foo and then your style. or try to !important

How to access JSON Object name/value?

You might want to try this approach:

var  str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);     
console.log(jsonData.name)
//Array Object
str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);     
console.log(jsonData[0].name)

Implementing a HashMap in C

Well if you know the basics behind them, it shouldn't be too hard.

Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.

When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.

Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).

Check out this fast hash table implementation:

https://attractivechaos.wordpress.com/2009/09/29/khash-h/

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)

if you make this int i[3] then i takes values i[0] i[1] i[2]

for your problem try this code structure

double[] array = new double[50];

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

    }

    for (int j = 25; j < 50; j++) {

    }

Removing object from array in Swift 3

This is official answer to find index of specific object, then you can easily remove any object using that index :

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
     // students[i] = "Max"
     students.remove(at: i)
}
print(students)
// Prints ["Ben", "Ivy", "Jordell"]

Here is the link: https://developer.apple.com/documentation/swift/array/2994720-firstindex

How do I set up IntelliJ IDEA for Android applications?

Another way to identify the correct SDK is to install Android Studio, create a new project, go to project structure, SDK Location and find where the SDK was installed.

I found using the default installation process on a mac that the SDK home folder was in the /Users/'yourUser'/Library/Android/sdk folder. Make sure you have enabled your Mac to view the Library folder.

What's the best way to get the last element of an array without deleting it?

array_values(array_reverse($array))[0] works in all those situations.

Iterating C++ vector from the end to the beginning

use this code

//print the vector element in reverse order by normal iterator.
cout <<"print the vector element in reverse order by normal iterator." <<endl;
vector<string>::iterator iter=vec.end();
--iter;
while (iter != vec.begin())
{
    cout << *iter  << " "; 
    --iter;
}

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

Changing the CommandTimeout in SQL Management studio

Right click in the query pane, select Query Options... and in the Execution->General section (the default when you first open it) there is an Execution time-out setting.

YouTube Video Embedded via iframe Ignoring z-index?

We can simply add ?wmode=transparent to the end of YouTube URL. This will tell YouTube to include the video with the wmode set. So you new embed code will look like this:-

<iframe width="420" height="315" src="http://www.youtube.com/embed/C4I84Gy-cPI?wmode=transparent" frameborder="0" allowfullscreen>

Convert JSON to DataTable

It can also be achieved using below code.

DataSet data = JsonConvert.DeserializeObject<DataSet>(json);

How can I represent an infinite number in Python?

Since Python 3.5 you can use math.inf:

>>> import math
>>> math.inf
inf

How can I remove all objects but one from the workspace in R?

require(gdata)
keep(object_1,...,object_n,sure=TRUE)
ls()

Associative arrays in Shell scripts

Adding another option, if jq is available:

export NAMES="{
  \"Mary\":\"100\",
  \"John\":\"200\",
  \"Mary\":\"50\",
  \"John\":\"300\",
  \"Paul\":\"100\",
  \"Paul\":\"400\",
  \"David\":\"100\"
}"
export NAME=David
echo $NAMES | jq --arg v "$NAME" '.[$v]' | tr -d '"' 

How do I write a backslash (\) in a string?

There is a special function made for this Path.Combine()

var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");

How do I add a simple jQuery script to WordPress?

Do you only need to load jquery?

1) Like the other guides say, register your script in your functions.php file like so:

// register scripts
if (!is_admin()) {
    // here is an example of loading a custom script in a /scripts/ folder in your theme:
    wp_register_script('sandbox.common', get_bloginfo('template_url').'/scripts/common.js', array('jquery'), '1.0', true);
    // enqueue these scripts everywhere
    wp_enqueue_script('jquery');
    wp_enqueue_script('sandbox.common');
}

2) Notice that we don't need to register jQuery because it's already in the core. Make sure wp_footer() is called in your footer.php and wp_head() is called in your header.php (this is where it will output the script tag), and jQuery will load on every page. When you enqueue jQuery with WordPress it will be in "no conflict" mode, so you have to use jQuery instead of $. You can deregister jQuery if you want and re-register your own by doing wp_deregister_script('jquery').

Pause in Python

There's a simple way to do this, you can use keyboard module's wait function. For example, you can do:

import keyboard
print("things before the pause")
keyboard.wait("esc") # esc is just an example, you can obviously put every key you want
print("things after the pause")

Using Node.JS, how do I read a JSON file into (server) memory?

At least in Node v8.9.1, you can just do

var json_data = require('/path/to/local/file.json');

and access all the elements of the JSON object.

How to get all count of mongoose model?

The collection.count is deprecated, and will be removed in a future version. Use collection.countDocuments or collection.estimatedDocumentCount instead.

userModel.countDocuments(query).exec((err, count) => {
    if (err) {
        res.send(err);
        return;
    }

    res.json({ count: count });
});

How to put a List<class> into a JSONObject and then read that object?

This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this.( with or without an external library).

 Type collectionType = new TypeToken<List<Class>>() {
                } // end new
                        .getType();

                String gsonString = 
                new Gson().toJson(objList, collectionType);

Using Vim's tabs like buffers

I ran into the same problem. I wanted tabs to work like buffers and I never quite manage to get them to. The solution that I finally settled on was to make buffers behave like tabs!

Check out the plugin called Mini Buffer Explorer, once installed and configured, you'll be able to work with buffers virtaully the same way as tabs without losing any functionality.

Where's my invalid character (ORA-00911)

One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Why am I getting "Thread was being aborted" in ASP.NET?

This error can be caused by trying to end a response more than once. As other answers already mentioned, there are various methods that will end a response (like Response.End, or Response.Redirect). If you call more than one in a row, you'll get this error.

I came across this error when I tried to use Response.End after using Response.TransmitFile which seems to end the response too.

C# static class constructor

A static constructor looks like this

static class Foo
{
    static Foo()
    {
         // Static initialization code here
    }
}

It is executed only once when the type is first used. All classes can have static constructors, not just static classes.

How do I sort an NSMutableArray with custom objects in it?

I did this in iOS 4 using a block. Had to cast the elements of my array from id to my class type. In this case it was a class called Score with a property called points.

Also you need to decide what to do if the elements of your array are not the right type, for this example I just returned NSOrderedSame, however in my code I though an exception.

NSArray *sorted = [_scores sortedArrayUsingComparator:^(id obj1, id obj2){
    if ([obj1 isKindOfClass:[Score class]] && [obj2 isKindOfClass:[Score class]]) {
        Score *s1 = obj1;
        Score *s2 = obj2;

        if (s1.points > s2.points) {
            return (NSComparisonResult)NSOrderedAscending;
        } else if (s1.points < s2.points) {
            return (NSComparisonResult)NSOrderedDescending;
        }
    }

    // TODO: default is the same?
    return (NSComparisonResult)NSOrderedSame;
}];

return sorted;

PS: This is sorting in descending order.

google-services.json for different productFlavors

Firebase now supports multiple application ids with one google-services.json file.

This blog post describes it in detail.

You'll create one parent project in Firebase that you'll use for all of your variants. You then create separate Android applications in Firebase under that project for each application id that you have.

When you created all of your variants, you can download a google-services.json that supports all of your applications ids. When it's relevant to see the data separately (i.e. Crash Reporting) you can toggle that with a dropdown.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

StdClass object is accessed by using ->

foreach ($blogs as $blog) {
    $id         = $blog->id;
    $title  = $blog->title;
    $content    = $blog->content;
}

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

You can simply set the status code of the response to 200 like the following

public ActionResult SomeMethod(parameters...)
{
   //others code here
   ...      
   Response.StatusCode = 200;
   return YourObject;  
}

Search for all occurrences of a string in a mysql database

I was looking for the same but couldn't find it, so I make a small script in PHP, you can find it at: http://tequilaphp.wordpress.com/2010/07/05/searching-strings-in-a-database-and-files/

Good luck! (I remove some private code, let me know if I didn't break it in the process :D)

APR based Apache Tomcat Native library was not found on the java.library.path?

For Ubntu Users

 1. Install compilers
    #sudo apt-get install make
    #sudo apt-get install gcc

    2. Install openssl and development libraries
    #sudo apt-get install openssl
    #sudo apt-get install libssl-dev
    3. Install the APR package (Downloaded from http://apr.apache.org/)

    #tar -xzf apr-1.4.6.tar.gz
    #cd apr-1.4.6/
    #sudo ./configure
    #sudo make
    #sudo make install

    You should see the compiled file as
    /usr/local/apr/lib/libapr-1.a

    4. Download, compile and install Tomcat Native sourse package
    tomcat-native-1.1.27-src.tar.gz

    Extract the archive into some folder

    #tar -xzf tomcat-native-1.1.27-src.tar.gz
    #cd tomcat-native-1.1.27-src/jni/native
    #JAVA_HOME=/usr/lib/jvm/jdk1.7.0_21/
    #sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
    #sudo make
    #sudo make install

    Now I have compiled Tomcat Native library in /usr/local/apr/libtcnative-1.so.0.1.27 and symbolic link file /usr/local/apr/@libtcnative-1.so pointed to the library

    5. Create or edit the $CATALINA_HOME/bin/setenv.sh file with following lines :
    export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'

    6. Restart tomcat and see the desired result:

Permission denied error while writing to a file in Python

Make sure that you have write permissions for that directory you were trying to create file by properties

Remove "Using default security password" on Spring Boot

It is also possible to just turn off logging for that specific class in properties :

logging.level.org.springframework.boot.autoconfigure.security.AuthenticationManagerConfiguration=WARN

Browse for a directory in C#

or even more better, you can put this code in a class file

using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;

internal class OpenFolderDialog : IDisposable {

    /// <summary>
    /// Gets/sets folder in which dialog will be open.
    /// </summary>
    public string InitialFolder { get; set; }

    /// <summary>
    /// Gets/sets directory in which dialog will be open if there is no recent directory available.
    /// </summary>
    public string DefaultFolder { get; set; }

    /// <summary>
    /// Gets selected folder.
    /// </summary>
    public string Folder { get; private set; }


    internal DialogResult ShowDialog(IWin32Window owner) {
        if (Environment.OSVersion.Version.Major >= 6) {
            return ShowVistaDialog(owner);
        } else {
            return ShowLegacyDialog(owner);
        }
    }

    private DialogResult ShowVistaDialog(IWin32Window owner) {
        var frm = (NativeMethods.IFileDialog)(new NativeMethods.FileOpenDialogRCW());
        uint options;
        frm.GetOptions(out options);
        options |= NativeMethods.FOS_PICKFOLDERS | NativeMethods.FOS_FORCEFILESYSTEM | NativeMethods.FOS_NOVALIDATE | NativeMethods.FOS_NOTESTFILECREATE | NativeMethods.FOS_DONTADDTORECENT;
        frm.SetOptions(options);
        if (this.InitialFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.InitialFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetFolder(directoryShellItem);
            }
        }
        if (this.DefaultFolder != null) {
            NativeMethods.IShellItem directoryShellItem;
            var riid = new Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"); //IShellItem
            if (NativeMethods.SHCreateItemFromParsingName(this.DefaultFolder, IntPtr.Zero, ref riid, out directoryShellItem) == NativeMethods.S_OK) {
                frm.SetDefaultFolder(directoryShellItem);
            }
        }

        if (frm.Show(owner.Handle) == NativeMethods.S_OK) {
            NativeMethods.IShellItem shellItem;
            if (frm.GetResult(out shellItem) == NativeMethods.S_OK) {
                IntPtr pszString;
                if (shellItem.GetDisplayName(NativeMethods.SIGDN_FILESYSPATH, out pszString) == NativeMethods.S_OK) {
                    if (pszString != IntPtr.Zero) {
                        try {
                            this.Folder = Marshal.PtrToStringAuto(pszString);
                            return DialogResult.OK;
                        } finally {
                            Marshal.FreeCoTaskMem(pszString);
                        }
                    }
                }
            }
        }
        return DialogResult.Cancel;
    }

    private DialogResult ShowLegacyDialog(IWin32Window owner) {
        using (var frm = new SaveFileDialog()) {
            frm.CheckFileExists = false;
            frm.CheckPathExists = true;
            frm.CreatePrompt = false;
            frm.Filter = "|" + Guid.Empty.ToString();
            frm.FileName = "any";
            if (this.InitialFolder != null) { frm.InitialDirectory = this.InitialFolder; }
            frm.OverwritePrompt = false;
            frm.Title = "Select Folder";
            frm.ValidateNames = false;
            if (frm.ShowDialog(owner) == DialogResult.OK) {
                this.Folder = Path.GetDirectoryName(frm.FileName);
                return DialogResult.OK;
            } else {
                return DialogResult.Cancel;
            }
        }
    }


    public void Dispose() { } //just to have possibility of Using statement.

}

internal static class NativeMethods {

    #region Constants

    public const uint FOS_PICKFOLDERS = 0x00000020;
    public const uint FOS_FORCEFILESYSTEM = 0x00000040;
    public const uint FOS_NOVALIDATE = 0x00000100;
    public const uint FOS_NOTESTFILECREATE = 0x00010000;
    public const uint FOS_DONTADDTORECENT = 0x02000000;

    public const uint S_OK = 0x0000;

    public const uint SIGDN_FILESYSPATH = 0x80058000;

    #endregion


    #region COM

    [ComImport, ClassInterface(ClassInterfaceType.None), TypeLibType(TypeLibTypeFlags.FCanCreate), Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
    internal class FileOpenDialogRCW { }


    [ComImport(), Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IFileDialog {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        [PreserveSig()]
        uint Show([In, Optional] IntPtr hwndOwner); //IModalWindow 


        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypes([In] uint cFileTypes, [In, MarshalAs(UnmanagedType.LPArray)] IntPtr rgFilterSpec);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileTypeIndex([In] uint iFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileTypeIndex(out uint piFileType);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Advise([In, MarshalAs(UnmanagedType.Interface)] IntPtr pfde, out uint pdwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Unadvise([In] uint dwCookie);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOptions([In] uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetOptions(out uint fos);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        void SetDefaultFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFolder([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFolder([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetCurrentSelection([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileName([In, MarshalAs(UnmanagedType.LPWStr)] string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string pszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetTitle([In, MarshalAs(UnmanagedType.LPWStr)] string pszTitle);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetOkButtonLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszText);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFileNameLabel([In, MarshalAs(UnmanagedType.LPWStr)] string pszLabel);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetResult([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint AddPlace([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, uint fdap);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetDefaultExtension([In, MarshalAs(UnmanagedType.LPWStr)] string pszDefaultExtension);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Close([MarshalAs(UnmanagedType.Error)] uint hr);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetClientGuid([In] ref Guid guid);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint ClearClientData();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint SetFilter([MarshalAs(UnmanagedType.Interface)] IntPtr pFilter);
    }


    [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    internal interface IShellItem {
        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint BindToHandler([In] IntPtr pbc, [In] ref Guid rbhid, [In] ref Guid riid, [Out, MarshalAs(UnmanagedType.Interface)] out IntPtr ppvOut);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetParent([MarshalAs(UnmanagedType.Interface)] out IShellItem ppsi);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetDisplayName([In] uint sigdnName, out IntPtr ppszName);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint GetAttributes([In] uint sfgaoMask, out uint psfgaoAttribs);

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        uint Compare([In, MarshalAs(UnmanagedType.Interface)] IShellItem psi, [In] uint hint, out int piOrder);
    }

    #endregion


    [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    internal static extern int SHCreateItemFromParsingName([MarshalAs(UnmanagedType.LPWStr)] string pszPath, IntPtr pbc, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);

}

And use it like this

using (var frm = new OpenFolderDialog()) {
                if (frm.ShowDialog(this)== DialogResult.OK) {
                    MessageBox.Show(this, frm.Folder);
                }
            }

Blur the edges of an image or background image with CSS

I'm not entirely sure what visual end result you're after, but here's an easy way to blur an image's edge: place a div with the image inside another div with the blurred image.

Working example here: http://jsfiddle.net/ZY5hn/1/

Screenshot

HTML:

<div class="placeholder">
     <!-- blurred background image for blurred edge -->
     <div class="bg-image-blur"></div>
     <!-- same image, no blur -->
     <div class="bg-image"></div>
     <!-- content -->
     <div class="content">Blurred Image Edges</div>
</div>

CSS:

.placeholder {
    margin-right: auto;
    margin-left:auto;
    margin-top: 20px;
    width: 200px;
    height: 200px;
    position: relative;
    /* this is the only relevant part for the example */
}
/* both DIVs have the same image */
 .bg-image-blur, .bg-image {
    background-image: url('http://lorempixel.com/200/200/city/9');
    position:absolute;
    top:0;
    left:0;
    width: 100%;
    height:100%;
}
/* blur the background, to make blurred edges that overflow the unblurred image that is on top */
 .bg-image-blur {
    -webkit-filter: blur(20px);
    -moz-filter: blur(20px);
    -o-filter: blur(20px);
    -ms-filter: blur(20px);
    filter: blur(20px);
}
/* I added this DIV in case you need to place content inside */
 .content {
    position: absolute;
    top:0;
    left:0;
    width: 100%;
    height: 100%;
    color: #fff;
    text-shadow: 0 0 3px #000;
    text-align: center;
    font-size: 30px;
}

Notice the blurred effect is using the image, so it changes with the image color.

I hope this helps.

Angular 2 router no base href set

Angular 7,8 fix is in app.module.ts

import {APP_BASE_HREF} from '@angular/common';

inside @NgModule add

providers: [{provide: APP_BASE_HREF, useValue: '/'}]

How to sum up elements of a C++ vector?

C++0x only:

vector<int> v; // and fill with data
int sum {}; // or = 0 ... :)
for (int n : v) sum += n;

This is similar to the BOOST_FOREACH mentioned elsewhere and has the same benefit of clarity in more complex situations, compared to stateful functors used with accumulate or for_each.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Chrome Uncaught Syntax Error: Unexpected Token ILLEGAL

I get the same error in Chrome after pasting code copied from jsfiddle.

If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.

What is apache's maximum url length?

The official length according to the offical Apache docs is 8,192, but many folks have run into trouble at ~4,000.

MS Internet Explorer is usually the limiting factor anyway, as it caps the maximum URL size at 2,048.

Using css transform property in jQuery

If you want to use a specific transform function, then all you need to do is include that function in the value. For example:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Secondly, browser support is getting better, but you'll probably still need to use vendor prefixes like so:

$('.user-text').css({
  '-webkit-transform' : 'scale(' + ui.value + ')',
  '-moz-transform'    : 'scale(' + ui.value + ')',
  '-ms-transform'     : 'scale(' + ui.value + ')',
  '-o-transform'      : 'scale(' + ui.value + ')',
  'transform'         : 'scale(' + ui.value + ')'
});

jsFiddle with example: http://jsfiddle.net/jehka/230/

How to change color of Android ListView separator line?

Or you can code it:

int[] colors = {0, 0xFFFF0000, 0}; // red for the example
myList.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
myList.setDividerHeight(1);

Hope it helps

Way to run Excel macros from command line or batch file?

you could write a vbscript to create an instance of excel via the createobject() method, then open the workbook and run the macro. You could either call the vbscript directly, or call the vbscript from a batch file.

Here is a resource I just stumbled accross: http://www.codeguru.com/forum/showthread.php?t=376401

Convert varchar to uniqueidentifier in SQL Server

SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

Select2 doesn't work when embedded in a bootstrap modal

Answer that worked for me found here: https://github.com/select2/select2-bootstrap-theme/issues/41

$('select').select2({
    dropdownParent: $('#my_amazing_modal')
});

Also doesn't require removing the tabindex.

Google Geocoding API - REQUEST_DENIED

If you just copy&paste the example URL that Google gives in their website http://maps.google.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false it will fail because of the wrong parameter of the sensor. You should change it to true or false and not the one that they wrote. Maybe is the error that you have had, like it happened to me...

Select by partial string from a pandas DataFrame

Quick note: if you want to do selection based on a partial string contained in the index, try the following:

df['stridx']=df.index
df[df['stridx'].str.contains("Hello|Britain")]

Convert a String of Hex into ASCII in Java

Check out Convert a string representation of a hex dump to a byte array using Java?

Disregarding encoding, etc. you can do new String (hexStringToByteArray("75546..."));

Background thread with QThread in PyQt

Take this answer updated for PyQt5, python 3.4

Use this as a pattern to start a worker that does not take data and return data as they are available to the form.

1 - Worker class is made smaller and put in its own file worker.py for easy memorization and independent software reuse.

2 - The main.py file is the file that defines the GUI Form class

3 - The thread object is not subclassed.

4 - Both thread object and the worker object belong to the Form object

5 - Steps of the procedure are within the comments.

# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time


class Worker(QObject):
    finished = pyqtSignal()
    intReady = pyqtSignal(int)


    @pyqtSlot()
    def procCounter(self): # A slot takes no params
        for i in range(1, 100):
            time.sleep(1)
            self.intReady.emit(i)

        self.finished.emit()

And the main file is:

  # main.py
  from PyQt5.QtCore import QThread
  from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout
  import sys
  import worker


  class Form(QWidget):

    def __init__(self):
       super().__init__()
       self.label = QLabel("0")

       # 1 - create Worker and Thread inside the Form
       self.obj = worker.Worker()  # no parent!
       self.thread = QThread()  # no parent!

       # 2 - Connect Worker`s Signals to Form method slots to post data.
       self.obj.intReady.connect(self.onIntReady)

       # 3 - Move the Worker object to the Thread object
       self.obj.moveToThread(self.thread)

       # 4 - Connect Worker Signals to the Thread slots
       self.obj.finished.connect(self.thread.quit)

       # 5 - Connect Thread started signal to Worker operational slot method
       self.thread.started.connect(self.obj.procCounter)

       # * - Thread finished signal will close the app if you want!
       #self.thread.finished.connect(app.exit)

       # 6 - Start the thread
       self.thread.start()

       # 7 - Start the form
       self.initUI()


    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)
        grid.addWidget(self.label,0,0)

        self.move(300, 150)
        self.setWindowTitle('thread test')
        self.show()

    def onIntReady(self, i):
        self.label.setText("{}".format(i))
        #print(i)

    app = QApplication(sys.argv)

    form = Form()

    sys.exit(app.exec_())

Concatenating bits in VHDL

The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only

Copy folder recursively, excluding some folders

EXCLUDE="foo bar blah jah"                                                                             
DEST=$1

for i in *
do
    for x in $EXCLUDE
    do  
        if [ $x != $i ]; then
            cp -a $i $DEST
        fi  
    done
done

Untested...

Pretty-Printing JSON with PHP

For those running PHP version 5.3 or before, you may try below:

$pretty_json = "<pre>".print_r(json_decode($json), true)."</pre>";

echo $pretty_json;

How to disable SSL certificate checking with Spring RestTemplate?

Here's a solution where security checking is disabled (for example, conversing with the localhost) Also, some of the solutions I've seen now contain deprecated methods and such.

/**
 * @param configFilePath
 * @param ipAddress
 * @param userId
 * @param password
 * @throws MalformedURLException
 */
public Upgrade(String aConfigFilePath, String ipAddress, String userId, String password) {
    configFilePath = aConfigFilePath;
    baseUri = "https://" + ipAddress + ":" + PORT + "/";

    restTemplate = new RestTemplate(createSecureTransport(userId, password, ipAddress, PORT));
    restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
 }

ClientHttpRequestFactory createSecureTransport(String username,
        String password, String host, int port) {
    HostnameVerifier nullHostnameVerifier = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);

    HttpClient client = HttpClientBuilder.create()
            .setSSLHostnameVerifier(nullHostnameVerifier)
            .setSSLContext(createContext())
            .setDefaultCredentialsProvider(credentialsProvider).build();

    HttpComponentsClientHttpRequestFactory requestFactory = 
            new HttpComponentsClientHttpRequestFactory(client);

    return requestFactory;
}

private SSLContext createContext() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        return sc;

    } catch (Exception e) {
    }
    return null;
}

How to set javascript variables using MVC4 with Razor

It works if you do something like this:

var proID = @proID + 0;

Which produces code that is something like:

var proID = 4 + 0;

A bit odd for sure, but no more fake syntax errors at least. Sadly the errors are still reported in VS2013, so this hasn't been properly addressed (yet).

$(this).val() not working to get text from span using jquery

Here we go:

$(".ui-datepicker-month").click(function(){  
var  textSpan = $(this).text();
alert(textSpan);   
});

Hope it helps;)

How to get a single value from FormGroup

Dot notation will break the type checking, switch to bracket notation. You might also try using the get() method. It also keeps AOT compilation in tact I've read.

this.form.get('controlName').value // safer
this.form.controlName.value // triggers type checking and breaks AOT

Reading a binary file with python

I too found Python lacking when it comes to reading and writing binary files, so I wrote a small module (for Python 3.6+).

With binaryfile you'd do something like this (I'm guessing, since I don't know Fortran):

import binaryfile

def particle_file(f):
    f.array('group_ids')  # Declare group_ids to be an array (so we can use it in a loop)
    f.skip(4)  # Bytes 1-4
    num_particles = f.count('num_particles', 'group_ids', 4)  # Bytes 5-8
    f.int('num_groups', 4)  # Bytes 9-12
    f.skip(8)  # Bytes 13-20
    for i in range(num_particles):
        f.struct('group_ids', '>f')  # 4 bytes x num_particles
    f.skip(4)

with open('myfile.bin', 'rb') as fh:
    result = binaryfile.read(fh, particle_file)
print(result)

Which produces an output like this:

{
    'group_ids': [(1.0,), (0.0,), (2.0,), (0.0,), (1.0,)],
    '__skipped': [b'\x00\x00\x00\x08', b'\x00\x00\x00\x08\x00\x00\x00\x14', b'\x00\x00\x00\x14'],
    'num_particles': 5,
    'num_groups': 3
}

I used skip() to skip the additional data Fortran adds, but you may want to add a utility to handle Fortran records properly instead. If you do, a pull request would be welcome.

HTTP Error 500.19 and error code : 0x80070021

In my case, there were rules for IIS URL Rewrite module but I didn't have that module installed. You should check your web.config if there are any modules included but not installed.

Escape @ character in razor view engine

just add a variable in CSHTML file var myVariable = @"@";

and add it to your layout <span class="my-class"><a href="@myVariale" target="_blank" >link text</a></span>

append new row to old csv file python

# I like using the codecs opening in a with 
field_names = ['latitude', 'longitude', 'date', 'user', 'text']
with codecs.open(filename,"ab", encoding='utf-8') as logfile:
    logger = csv.DictWriter(logfile, fieldnames=field_names)
    logger.writeheader()

# some more code stuff 

    for video in aList:
        video_result = {}                                     
        video_result['date'] = video['snippet']['publishedAt']
        video_result['user'] = video['id']
        video_result['text'] = video['snippet']['description'].encode('utf8')
        logger.writerow(video_result) 

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

Best way to find the intersection of multiple sets?

I believe the simplest thing to do is:

#assuming three sets
set1 = {1,2,3,4,5}
set2 = {2,3,8,9}
set3 = {2,10,11,12}

#intersection
set4 = set1 & set2 & set3

set4 will be the intersection of set1 , set2, set3 and will contain the value 2.

print(set4)

set([2])

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

before going for the step "compile -DIPLIB=NONE filename.cxx" take the path of VIsual Studio installation upto the vcvarsall batch file and change the configuration as shown below.

*C:\apps\MVS9\VC\vcvarsall.bat x86_amd64*

now next step should be

compile -64bit -DIPLIB=none filename.cxx

this solved the problem for me

How to format number of decimal places in wpf using style/template?

The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format

<TextBox Text="{Binding Value,  StringFormat={}{0:#,0.0}}" 

Instagram how to get my user id from username?

https://api.instagram.com/v1/users/search?q="[USERNAME]"&access_token=[ACCESS TOKEN]

Please notice the quotation marks.

This does not always return a valid result but more often than non-quoted one:

https://api.instagram.com/v1/users/search?q="self"&count=1&access_token=[ACCESS TOKEN] 

returns user "self" (id: 311176867)

https://api.instagram.com/v1/users/search?q=self&count=1&access_token=[ACCESS TOKEN]

returns user "super_selfie" (id: 1422944651)

UL has margin on the left

The <ul> element has browser inherent padding & margin by default. In your case, Use

#footer ul {
    margin: 0; /* To remove default bottom margin */ 
    padding: 0; /* To remove default left padding */
}

or a CSS browser reset ( https://cssreset.com/ ) to deal with this.

Is it possible to import modules from all files in a directory, using a wildcard?

Similar to the accepted question but it allows you to scale without the need of adding a new module to the index file each time you create one:

./modules/moduleA.js

export const example = 'example';
export const anotherExample = 'anotherExample';

./modules/index.js

// require all modules on the path and with the pattern defined
const req = require.context('./', true, /.js$/);

const modules = req.keys().map(req);

// export all modules
module.exports = modules;

./example.js

import { example, anotherExample } from './modules'

React router nav bar example

Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.

Nav.js

  import React from 'react';
  import { Link } from 'react-router';

  export default class Nav extends React.Component {
    render() {    
      return (
        <nav className="Nav">
          <div className="Nav__container">
            <Link to="/" className="Nav__brand">
              <img src="logo.svg" className="Nav__logo" />
            </Link>

            <div className="Nav__right">
              <ul className="Nav__item-wrapper">
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path1">Link 1</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path2">Link 2</Link>
                </li>
                <li className="Nav__item">
                  <Link className="Nav__link" to="/path3">Link 3</Link>
                </li>
              </ul>
            </div>
          </div>
        </nav>
      );
    }
  }

App.js

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
            <div>
              <Nav />
              <Switch>
                <Route exactly component={Landing} pattern="/" />
                <Route exactly component={Page1} pattern="/path1" />
                <Route exactly component={Page2} pattern="/path2" />
                <Route exactly component={Page3} pattern="/path3" />
                <Route component={Page404} />
              </Switch>
            </div>
          </Router>
        </div>
      );
    }
  }

Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar

Edit

A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component

  import React from 'react';
  import { Link, Switch, Route } from 'react-router';
  import Nav from './nav';
  import Page1 from './page1';
  import Page2 from './page2';
  import Page3 from './page3';

  const NavRoute = ({exact, path, component: Component}) => (
    <Route exact={exact} path={path} render={(props) => (
      <div>
        <Header/>
        <Component {...props}/>
      </div>
    )}/>
  )

  export default class App extends React.Component {
    render() {    
      return (
        <div className="App">
          <Router>
              <Switch>
                <NavRoute exactly component={Landing} pattern="/" />
                <Route exactly component={Login} pattern="/login" />
                <NavRoute exactly component={Page1} pattern="/path1" />
                <NavRoute exactly component={Page2} pattern="/path2" />
                <NavRoute component={Page404} />
              </Switch>
          </Router>
        </div>
      );
    }
  }

MVC Razor view nested foreach's model

The quick answer is to use a for() loop in place of your foreach() loops. Something like:

@for(var themeIndex = 0; themeIndex < Model.Theme.Count(); themeIndex++)
{
   @Html.LabelFor(model => model.Theme[themeIndex])

   @for(var productIndex=0; productIndex < Model.Theme[themeIndex].Products.Count(); productIndex++)
   {
      @Html.LabelFor(model=>model.Theme[themeIndex].Products[productIndex].name)
      @for(var orderIndex=0; orderIndex < Model.Theme[themeIndex].Products[productIndex].Orders; orderIndex++)
      {
          @Html.TextBoxFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Quantity)
          @Html.TextAreaFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].Note)
          @Html.EditorFor(model => model.Theme[themeIndex].Products[productIndex].Orders[orderIndex].DateRequestedDeliveryFor)
      }
   }
}

But this glosses over why this fixes the problem.

There are three things that you have at least a cursory understanding before you can resolve this issue. I have to admit that I cargo-culted this for a long time when I started working with the framework. And it took me quite a while to really get what was going on.

Those three things are:

  • How do the LabelFor and other ...For helpers work in MVC?
  • What is an Expression Tree?
  • How does the Model Binder work?

All three of these concepts link together to get an answer.

How do the LabelFor and other ...For helpers work in MVC?

So, you've used the HtmlHelper<T> extensions for LabelFor and TextBoxFor and others, and you probably noticed that when you invoke them, you pass them a lambda and it magically generates some html. But how?

So the first thing to notice is the signature for these helpers. Lets look at the simplest overload for TextBoxFor

public static MvcHtmlString TextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TProperty>> expression
) 

First, this is an extension method for a strongly typed HtmlHelper, of type <TModel>. So, to simply state what happens behind the scenes, when razor renders this view it generates a class. Inside of this class is an instance of HtmlHelper<TModel> (as the property Html, which is why you can use @Html...), where TModel is the type defined in your @model statement. So in your case, when you are looking at this view TModel will always be of the type ViewModels.MyViewModels.Theme.

Now, the next argument is a bit tricky. So lets look at an invocation

@Html.TextBoxFor(model=>model.SomeProperty);

It looks like we have a little lambda, And if one were to guess the signature, one might think that the type for this argument would simply be a Func<TModel, TProperty>, where TModel is the type of the view model and TProperty is inferred as the type of the property.

But thats not quite right, if you look at the actual type of the argument its Expression<Func<TModel, TProperty>>.

So when you normally generate a lambda, the compiler takes the lambda and compiles it down into MSIL, just like any other function (which is why you can use delegates, method groups, and lambdas more or less interchangeably, because they are just code references.)

However, when the compiler sees that the type is an Expression<>, it doesn't immediately compile the lambda down to MSIL, instead it generates an Expression Tree!

What is an Expression Tree?

So, what the heck is an expression tree. Well, it's not complicated but its not a walk in the park either. To quote ms:

| Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y.

Simply put, an expression tree is a representation of a function as a collection of "actions".

In the case of model=>model.SomeProperty, the expression tree would have a node in it that says: "Get 'Some Property' from a 'model'"

This expression tree can be compiled into a function that can be invoked, but as long as it's an expression tree, it's just a collection of nodes.

So what is that good for?

So Func<> or Action<>, once you have them, they are pretty much atomic. All you can really do is Invoke() them, aka tell them to do the work they are supposed to do.

Expression<Func<>> on the other hand, represents a collection of actions, which can be appended, manipulated, visited, or compiled and invoked.

So why are you telling me all this?

So with that understanding of what an Expression<> is, we can go back to Html.TextBoxFor. When it renders a textbox, it needs to generate a few things about the property that you are giving it. Things like attributes on the property for validation, and specifically in this case it needs to figure out what to name the <input> tag.

It does this by "walking" the expression tree and building a name. So for an expression like model=>model.SomeProperty, it walks the expression gathering the properties that you are asking for and builds <input name='SomeProperty'>.

For a more complicated example, like model=>model.Foo.Bar.Baz.FooBar, it might generate <input name="Foo.Bar.Baz.FooBar" value="[whatever FooBar is]" />

Make sense? It is not just the work that the Func<> does, but how it does its work is important here.

(Note other frameworks like LINQ to SQL do similar things by walking an expression tree and building a different grammar, that this case a SQL query)

How does the Model Binder work?

So once you get that, we have to briefly talk about the model binder. When the form gets posted, it's simply like a flat Dictionary<string, string>, we have lost the hierarchical structure our nested view model may have had. It's the model binder's job to take this key-value pair combo and attempt to rehydrate an object with some properties. How does it do this? You guessed it, by using the "key" or name of the input that got posted.

So if the form post looks like

Foo.Bar.Baz.FooBar = Hello

And you are posting to a model called SomeViewModel, then it does the reverse of what the helper did in the first place. It looks for a property called "Foo". Then it looks for a property called "Bar" off of "Foo", then it looks for "Baz"... and so on...

Finally it tries to parse the value into the type of "FooBar" and assign it to "FooBar".

PHEW!!!

And voila, you have your model. The instance the Model Binder just constructed gets handed into requested Action.


So your solution doesn't work because the Html.[Type]For() helpers need an expression. And you are just giving them a value. It has no idea what the context is for that value, and it doesn't know what to do with it.

Now some people suggested using partials to render. Now this in theory will work, but probably not the way that you expect. When you render a partial, you are changing the type of TModel, because you are in a different view context. This means that you can describe your property with a shorter expression. It also means when the helper generates the name for your expression, it will be shallow. It will only generate based on the expression it's given (not the entire context).

So lets say you had a partial that just rendered "Baz" (from our example before). Inside that partial you could just say:

@Html.TextBoxFor(model=>model.FooBar)

Rather than

@Html.TextBoxFor(model=>model.Foo.Bar.Baz.FooBar)

That means that it will generate an input tag like this:

<input name="FooBar" />

Which, if you are posting this form to an action that is expecting a large deeply nested ViewModel, then it will try to hydrate a property called FooBar off of TModel. Which at best isn't there, and at worst is something else entirely. If you were posting to a specific action that was accepting a Baz, rather than the root model, then this would work great! In fact, partials are a good way to change your view context, for example if you had a page with multiple forms that all post to different actions, then rendering a partial for each one would be a great idea.


Now once you get all of this, you can start to do really interesting things with Expression<>, by programatically extending them and doing other neat things with them. I won't get into any of that. But, hopefully, this will give you a better understanding of what is going on behind the scenes and why things are acting the way that they are.

What does the "undefined reference to varName" in C mean?

You need to compile and then link the object files like this:

gcc -c a.c  
gcc -c b.c  
gcc a.o b.o -o prog  

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.

Getting "type or namespace name could not be found" but everything seems ok?

My case was same as discussed here but nothing solved it until I've removed the System.Core reference from the references list (Everything worked fine without it)

hope it will help someone because this issue is quite frustrating

How to redirect page after click on Ok button on sweet alert?

I think this will help. It's same as given by Mr. Barmer. But I have enclosed this within php tags.

Here it goes....

    <?php if(!empty($_GET['submitted'])):?>
        <script>
        setTimeout(function() {
            swal({
                title: "Congratulaions!",
                text: "Signed up successfully, now verify your mail",
                type: "success",
                confirmButtonText: "Ok"
            }, function() {
                window.location = "index.php";
            }, 1000);
        });
        </script>   
    <?php endif;?>

MySQL Cannot drop index needed in a foreign key constraint

If you mean that you can do this:

CREATE TABLE mytable_d (
ID          TINYINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name        VARCHAR(255) NOT NULL,
UNIQUE(Name)
) ENGINE=InnoDB;


ALTER TABLE mytable
ADD COLUMN DID tinyint(5) NOT NULL,
ADD CONSTRAINT mytable_ibfk_4 
      FOREIGN KEY (DID) 
        REFERENCES mytable_d (ID) ON DELETE CASCADE;

 > OK.

But then:

ALTER TABLE mytable
DROP KEY AID ;

gives error.


You can drop the index and create a new one in one ALTER TABLE statement:

ALTER TABLE mytable
DROP KEY AID ,
ADD UNIQUE KEY AID (AID, BID, CID, DID);

What is "string[] args" in Main class for?

From the C# programming guide on MSDN:

The parameter of the Main method is a String array that represents the command-line arguments

So, if I had a program (MyApp.exe) like this:

class Program
{
  static void Main(string[] args)
  {
    foreach (var arg in args)
    {
      Console.WriteLine(arg);
    }
  }
}

That I started at the command line like this:

MyApp.exe Arg1 Arg2 Arg3

The Main method would be passed an array that contained three strings: "Arg1", "Arg2", "Arg3".

If you need to pass an argument that contains a space then wrap it in quotes. For example:

MyApp.exe "Arg 1" "Arg 2" "Arg 3"

Command line arguments commonly get used when you need to pass information to your application at runtime. For example if you were writing a program that copies a file from one location to another you would probably pass the two locations as command line arguments. For example:

Copy.exe C:\file1.txt C:\file2.txt

Serializing to JSON in jQuery

Works on IE8+

No need for jQuery, use:

JSON.stringify(countries); 

How to make a gui in python

If you're looking to build a GUI interface to trace an IP address, I would recommend VB.

But if you insist on sticking with Python, TkInter and wxPython are the best choices.

Printing to the console in Google Apps Script?

Even though Logger.log() is technically the correct way to output something to the console, it has a few annoyances:

  1. The output can be an unstructured mess and hard to quickly digest.
  2. You have to first run the script, then click View / Logs, which is two extra clicks (one if you remember the Ctrl+Enter keyboard shortcut).
  3. You have to insert Logger.log(playerArray), and then after debugging you'd probably want to remove Logger.log(playerArray), hence an additional 1-2 more steps.
  4. You have to click on OK to close the overlay (yet another extra click).

Instead, whenever I want to debug something I add breakpoints (click on line number) and press the Debug button (bug icon). Breakpoints work well when you are assigning something to a variable, but not so well when you are initiating a variable and want to peek inside of it at a later point, which is similar to what the op is trying to do. In this case, I would force a break condition by entering "x" (x marks the spot!) to throw a run-time error:

enter image description here

Compare with viewing Logs:

enter image description here

The Debug console contains more information and is a lot easier to read than the Logs overlay. One minor benefit with this method is that you never have to worry about polluting your code with a bunch of logging commands if keeping clean code is your thing. Even if you enter "x", you are forced to remember to remove it as part of the debugging process or else your code won't run (built-in cleanup measure, yay).

How to prevent favicon.ico requests?

Just add the following line to the <head> section of your HTML file:

<link rel="icon" href="data:,">

Features of this solution:

  • 100% valid HTML5
  • very short
  • does not incur any quirks from IE 8 and older
  • does not make the browser interpret the current HTML code as favicon (which would be the case with href="#")

How to make an introduction page with Doxygen

Note that with Doxygen release 1.8.0 you can also add Markdown formated pages. For this to work you need to create pages with a .md or .markdown extension, and add the following to the config file:

INPUT += your_page.md
FILE_PATTERNS += *.md *.markdown

See http://www.doxygen.nl/manual/markdown.html#md_page_header for details.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

As you can see here:

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Difference between @GetMapping & @RequestMapping

@GetMapping supports the consumes attribute like @RequestMapping.

Format a message using MessageFormat.format() in Java

You need to use double apostrophe instead of single in the "You''re", eg:

String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);

How can I check if a Perl array contains a particular value?

@eakssjo's benchmark is broken - measures creating hashes in loop vs creating regexes in loop. Fixed version (plus I've added List::Util::first and List::MoreUtils::any):

use List::Util qw(first);
use List::MoreUtils qw(any);
use Benchmark;

my @list = ( 1..10_000 );
my $hit = 5_000;
my $hit_regex = qr/^$hit$/; # precompute regex
my %params;
$params{$_} = 1 for @list;  # precompute hash
timethese(
    100_000, {
        'any' => sub {
            die unless ( any { $hit_regex } @list );
        },
        'first' => sub {
            die unless ( first { $hit_regex } @list );
        },
        'grep' => sub {
            die unless ( grep { $hit_regex } @list );
        },
        'hash' => sub {
            die unless ( $params{$hit} );
        },
    });

And result (it's for 100_000 iterations, ten times more than in @eakssjo's answer):

Benchmark: timing 100000 iterations of any, first, grep, hash...
       any:  0 wallclock secs ( 0.67 usr +  0.00 sys =  0.67 CPU) @ 149253.73/s (n=100000)
     first:  1 wallclock secs ( 0.63 usr +  0.01 sys =  0.64 CPU) @ 156250.00/s (n=100000)
      grep: 42 wallclock secs (41.95 usr +  0.08 sys = 42.03 CPU) @ 2379.25/s (n=100000)
      hash:  0 wallclock secs ( 0.01 usr +  0.00 sys =  0.01 CPU) @ 10000000.00/s (n=100000)
            (warning: too few iterations for a reliable count)

Oracle SQL Developer and PostgreSQL

Oracle SQL Developer 2020-02 support PostgreSQL, but it is just the basics by adding postgreSQL driver under jdbc dir and configure by adding as a 3rd party driver.

The supported functionality:

  • multiple databases which can be selected at connection definition
  • CRUD operations like query tables
  • scheme operations
  • basic modelling support: show tables without pk, fk, connections

Not supported functionalities:

  • no table or field completion
  • no indexes are shown in a tab
  • no constraints are shown in a tab like: fk, pk-s, unique, or others
  • no table or field completions in the editor
  • no functions, packages,triggers, views are shown

The sad thing is Oracle should only change the queries behind this view in case of PostgreSql connections. For example for indexes they need to use this query: select * from pg_catalog.pg_indexes;

What's the maximum value for an int in PHP?

Although PHP_INT_* constants exist for a very long time, the same MIN / MAX values could be found programmatically by left shifting until reaching the negative number:

$x = 1;
while ($x > 0 && $x <<= 1);
echo "MIN: ", $x;
echo PHP_EOL;
echo "MAX: ", ~$x;

Conditionally Remove Dataframe Rows with R

Subset is your safest and easiest answer.

subset(dataframe, A==B & E!=0)

Real data example with mtcars

subset(mtcars, cyl==6 & am!=0)

Calculating how many days are between two dates in DB2?

I faced the same problem in Derby IBM DB2 embedded database in a java desktop application, and after a day of searching I finally found how it's done :

SELECT days (table1.datecolomn) - days (current date) FROM table1 WHERE days (table1.datecolomn) - days (current date) > 5

for more information check this site

How to check identical array in most efficient way?

You could compare String representations so:

array1.toString() == array2.toString()
array1.toString() !== array3.toString()

but that would also make

array4 = ['1',2,3,4,5]

equal to array1 if that matters to you

Install tkinter for Python

Fedora release 25 (Twenty Five)

dnf install python3-tkinter

This worked for me.

Add data dynamically to an Array

In additon to directly accessing the array, there is also

array_push — Push one or more elements onto the end of array

Invoke JSF managed bean action on page load

Another easy way is to use fire the method before the view is rendered. This is better than postConstruct because for sessionScope, postConstruct will fire only once every session. This will fire every time the page is loaded. This is ofcourse only for JSF 2.0 and not for JSF 1.2.

This is how to do it -

<html xmlns:f="http://java.sun.com/jsf/core">
      <f:metadata>
          <f:event type="preRenderView" listener="#{myController.onPageLoad}"/>
      </f:metadata>
</html>

And in the myController.java

 public void onPageLoad(){
    // Do something
 }

EDIT - Though this is not a solution for the question on this page, I add this just for people using higher versions of JSF.

JSF 2.2 has a new feature which performs this task using viewAction.

<f:metadata>
    <f:viewAction action="#{myController.onPageLoad}" />
</f:metadata>

mkdir -p functionality in Python

As mentioned in the other solutions, we want to be able to hit the file system once while mimicking the behaviour of mkdir -p. I don't think that this is possible to do, but we should get as close as possible.

Code first, explanation later:

import os
import errno

def mkdir_p(path):
    """ 'mkdir -p' in Python """
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

As the comments to @tzot's answer indicate there are problems with checking whether you can create a directory before you actually create it: you can't tell whether someone has changed the file system in the meantime. That also fits in with Python's style of asking for forgiveness, not permission.

So the first thing we should do is try to make the directory, then if it goes wrong, work out why.

As Jacob Gabrielson points out, one of the cases we must look for is the case where a file already exists where we are trying to put the directory.

With mkdir -p:

$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory '/tmp/foo': File exists

The analogous behaviour in Python would be to raise an exception.

So we have to work out if this was the case. Unfortunately, we can't. We get the same error message back from makedirs whether a directory exists (good) or a file exists preventing the creation of the directory (bad).

The only way to work out what happened is to inspect the file system again to see if there is a directory there. If there is, then return silently, otherwise raise the exception.

The only problem is that the file system may be in a different state now than when makedirs was called. eg: a file existed causing makedirs to fail, but now a directory is in its place. That doesn't really matter that much, because the the function will only exit silently without raising an exception when at the time of the last file system call the directory existed.

What are queues in jQuery?

This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:

/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
    for (var l = 0; l < ph[i].length; l++) {
        /* create a function which swaps an image, and calls the next function in the queue */
        theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
        /* set the animation speed */
        theQueue.delay(200,'anim');
    }
}
/* start the animation */
theQueue.dequeue('anim');

This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.

Java naming convention for static final variables

That's still a constant. See the JLS for more information regarding the naming convention for constants. But in reality, it's all a matter of preference.


The names of constants in interface types should be, and final variables of class types may conventionally be, a sequence of one or more words, acronyms, or abbreviations, all uppercase, with components separated by underscore "_" characters. Constant names should be descriptive and not unnecessarily abbreviated. Conventionally they may be any appropriate part of speech. Examples of names for constants include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class Character.

A group of constants that represent alternative values of a set, or, less frequently, masking bits in an integer value, are sometimes usefully specified with a common acronym as a name prefix, as in:

interface ProcessStates {
  int PS_RUNNING = 0;
  int PS_SUSPENDED = 1;
}

Obscuring involving constant names is rare:

  • Constant names normally have no lowercase letters, so they will not normally obscure names of packages or types, nor will they normally shadow fields, whose names typically contain at least one lowercase letter.
  • Constant names cannot obscure method names, because they are distinguished syntactically.

add an element to int [] array in java

This works for me:

int[] list = new int[maximum];
for (int i = 0; i < maximum; i++{
    list[i] = put_input_here;
}

This way, it's simple, yet efficient.

How do I create a MongoDB dump of my database?

 Use -v to see progress of backup data
    mongodump -v --db dbname --out /pathforbackup/NewFolderforBackupData

 you can use it for restore also
    mongorestore -v --db dbname --drop /pathforbackup/NewFolderforBackupData/dbname

with multile v like -vvvv you will get more information

PHP7 : install ext-dom issue

simply run

sudo apt install php-xml

its worked for me

How to create JSON string in JavaScript?

I think this way helps you...

var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);

CSS: Position loading indicator in the center of the screen

This is what I've done for Angular 4:

<style type="text/css">  
  .centered {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transform: -webkit-translate(-50%, -50%);
    transform: -moz-translate(-50%, -50%);
    transform: -ms-translate(-50%, -50%);
    color:darkred;
  }
</style>

</head>

<body>
  <app-root>
        <div class="centered">
          <h1>Loading...</h1>
        </div>
  </app-root>
</body>

How can I exclude $(this) from a jQuery selector?

Try using the not() method instead of the :not() selector.

$(".content a").click(function() {
    $(".content a").not(this).hide("slow");
});

Error: Specified cast is not valid. (SqlManagerUI)

There are some funnies restoring old databases into SQL 2008 via the guy; have you tried doing it via TSQL ?

Use Master
Go
RESTORE DATABASE YourDB
FROM DISK = 'C:\YourBackUpFile.bak'
WITH MOVE 'YourMDFLogicalName' TO 'D:\Data\YourMDFFile.mdf',--check and adjust path
MOVE 'YourLDFLogicalName' TO 'D:\Data\YourLDFFile.ldf' 

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Bash array with spaces in elements

There must be something wrong with the way you access the array's items. Here's how it's done:

for elem in "${files[@]}"
...

From the bash manpage:

Any element of an array may be referenced using ${name[subscript]}. ... If subscript is @ or *, the word expands to all members of name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS special variable, and ${name[@]} expands each element of name to a separate word.

Of course, you should also use double quotes when accessing a single member

cp "${files[0]}" /tmp

What's the PowerShell syntax for multiple values in a switch statement?

The switch doesn't appear to be case sensitive in PowerShell 5.1. All four of the $someString examples below work.

$someString = "YES"
$someString = "yes"
$someString = "yEs"
$someString = "y"

switch ($someString) {
   {"y","yes"} { "You entered Yes." }
   Default { "You didn't enter Yes."}
}

Here is my $PSVersionTable data.

Name                           Value
----                           -----
PSVersion                      5.1.17763.771
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.17763.771
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

How can I check if a value is of type Integer?

You can use modulus %, the solution is so simple:

import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Enter first number");
    Double m = scan.nextDouble();
    System.out.println("Enter second number");
    Double n= scan.nextDouble();

    if(m%n==0) 
    {
        System.out.println("Integer");
    }
    else
    {
        System.out.println("Double");
    }


}
}

how to make window.open pop up Modal?

You can't make window.open modal and I strongly recommend you not to go that way. Instead you can use something like jQuery UI's dialog widget.

UPDATE:

You can use load() method:

$("#dialog").load("resource.php").dialog({options});

This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.

And you can use an IFRAME:

$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});

This is slower, but will submit independently.

Eclipse - Failed to create the java virtual machine

Reduce the memory size to Xmx512m and it works.

Get current time in milliseconds using C++ and Boost

You can use boost::posix_time::time_duration to get the time range. E.g like this

boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();

And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock has milisecond resolution, not microsecond.

An example which is a little dependent on the hardware.

int main(int argc, char* argv[])
{
    boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
    boost::posix_time::time_duration diff = t2 - t1;
    std::cout << diff.total_milliseconds() << std::endl;

    boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
    boost::posix_time::time_duration msdiff = mst2 - mst1;
    std::cout << msdiff.total_milliseconds() << std::endl;
    return 0;
}

On my win7 machine. The first out is either 0 or 1000. Second resolution. The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.

How to clear cache of Eclipse Indigo

Instructions

  1. Open Eclipse and navigate to the Window > Preferences.
  2. Scroll down the left-hand panel in the Preferences window and click the Remote Systems drop-down root menu. Select File Cache.
  3. Click the Clear Cached Files button in the File Cache window. Note that this will automatically close any open remote files on your computer.
  4. Press Apply and OK to save your changes and exit out of the Preferences window.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

DNS problem, nslookup works, ping doesn't

I found a little bug in windows Server 2003 R2 EE. you know that when you specify your IP address in the NIC (network connections), windows tells you that if you dont specify the preferred DNS server, it will put his own ip because it is an DNS server? well it doesn't do that...

I fixed my problem writing the dns adress manually, instead of letting windows do it for me.

Refresh a page using JavaScript or HTML

Use:

window.location.reload();

ORA-06508: PL/SQL: could not find program unit being called

Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.

Original script was

create or replace PACKAGE BODY APPLICATION_VALIDATION AS 

V_ERROR_NAME varchar2(200) := '';

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

Rewritten the same without global variable V_ERROR_NAME and moved to procedure under package level as

Modified Code

create or replace PACKAGE BODY APPLICATION_VALIDATION AS

PROCEDURE  APP_ERROR_X47_VALIDATION (   PROCESS_ID IN VARCHAR2 ) AS

**V_ERROR_NAME varchar2(200) := '';** 

BEGIN
     ------ rules for validation... END APP_ERROR_X47_VALIDATION ;

/* Some more code
*/

END APPLICATION_VALIDATION; /

How to configure Spring Security to allow Swagger URL to be accessed without authentication

I updated with /configuration/** and /swagger-resources/** and it worked for me.

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**", "/swagger-ui.html", "/webjars/**");

}

HTML Input - already filled in text

<input type="text" value="Your value">

Use the value attribute for the pre filled in values.

How to encrypt String in Java

String s1="arshad"; 
char[] s2=s1.toCharArray(); 
int s3= s2.length; 

  System.out.println(s3);
 int i=0; 

// for(int j=0;j<s3;j++) 
// System.out.println(s2[j]); 

for(i=0;i<((s3)/2);i++) { 

char z,f=10; 
z=(char) (s2[i] * f); 
s2[i]=s2[(s3-1)-i]; 
s2[(s3-1)-i]=z; 

String b=new String(s2);

 print(b);  }

How do you copy a record in a SQL table but swap out the unique id of the new row?

My table has 100 fields, and I needed a query to just work. Now I can switch out any number of fields with some basic conditional logic and not worry about its ordinal position.

  1. Replace the below table name with your table name

    SQLcolums = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE (TABLE_NAME = 'TABLE-NAME')"
    
    Set GetColumns = Conn.Execute(SQLcolums)
    Do WHILE not GetColumns.eof
    
    colName = GetColumns("COLUMN_NAME")
    
  2. Replace the original identity field name with your PK field name

    IF colName = "ORIGINAL-IDENTITY-FIELD-NAME" THEN ' ASSUMING THAT YOUR PRIMARY KEY IS THE FIRST FIELD DONT WORRY ABOUT COMMAS AND SPACES
        columnListSOURCE = colName 
        columnListTARGET = "[PreviousId field name]"
    ELSE
        columnListSOURCE = columnListSOURCE & colName
        columnListTARGET = columnListTARGET & colName
    END IF
    
    GetColumns.movenext
    
    loop
    
    GetColumns.close    
    
  3. Replace the table names again (both target table name and source table name); edit your where conditions

    SQL = "INSERT INTO TARGET-TABLE-NAME (" & columnListTARGET & ") SELECT " & columnListSOURCE & " FROM SOURCE-TABLE-NAME WHERE (FIELDNAME = FIELDVALUE)" 
    Conn.Execute(SQL)
    

[Vue warn]: Property or method is not defined on the instance but referenced during render

My issue was I was placing the methods inside my data object. just format it like this and it'll work nicely.

<script>
module.exports = {
    data: () => {
        return {
            name: ""
        }
    },
    methods: {
        myFunc() {
            // code
        }
    }
}
</script>

Negative matching using grep (match lines that do not contain foo)

You can also use awk for these purposes, since it allows you to perform more complex checks in a clearer way:

Lines not containing foo:

awk '!/foo/'

Lines containing neither foo nor bar:

awk '!/foo/ && !/bar/'

Lines containing neither foo nor bar which contain either foo2 or bar2:

awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'

And so on.

Emulator: ERROR: x86 emulation currently requires hardware acceleration

For those who still have problems with this, you can try using an alternative Android emulator such as Genymotion.

I'm using Ryzen 5 processor with latest Windows 10 update installed (1809), but still can't install HAXM. So, what I did to resolve this was:

  1. Enable Hardware Virtualization in BIOS settings
  2. Enable Hypervisor Platform in Windows Feature
  3. Install Genymotion with Virtual Box -- select for personal use
  4. Install Genymotion Android Studio plugin -- find this in Android Studio plugins settings

You're good to go from here.

cpu screenshot

'Access denied for user 'root'@'localhost' (using password: NO)'

For some information I've get error after changing password:

Access denied for user 'root'@'localhost' (using password: NO)

Access denied for user 'root'@'localhost' (using password: YES)

In both cases there was error.

But the thing is after that I've tried it with

mysql -uroot -ppassword instead of

mysql -u root -p password -> with spaces between -uroot and -ppassword so maybe if someone get trouble can try this way.

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Convert hex color value ( #ffffff ) to integer value

Get Shared Preferences Color Code in String then Convert to integer and add layout-background color:

    sharedPreferences = getSharedPreferences(mypref, Context.MODE_PRIVATE);
    String sw=sharedPreferences.getString(name, "");
    relativeLayout.setBackgroundColor(Color.parseColor(sw));

Is there any option to limit mongodb memory usage?

One thing you can limit is the amount of memory mongodb uses while building indexes. This is set using the maxIndexBuildMemoryUsageMegabytes setting. An example of how its set is below:

mongo --eval "db.adminCommand( { setParameter: 1, maxIndexBuildMemoryUsageMegabytes: 70000 } )"

How to add screenshot to READMEs in github repository?

Even though there is already an accepted answer I would like to add another way to upload images to readme on GitHub.

  • You need to create issue in your repo
  • Drag and drop in the comment area your image
  • After link for the image is generated insert it to your readme

More details you can find here

MySQL INNER JOIN select only one row from second table

You need to have a subquery to get their latest date per user ID.

SELECT  a.*, c.*
FROM users a 
    INNER JOIN payments c
        ON a.id = c.user_ID
    INNER JOIN
    (
        SELECT user_ID, MAX(date) maxDate
        FROM payments
        GROUP BY user_ID
    ) b ON c.user_ID = b.user_ID AND
            c.date = b.maxDate
WHERE a.package = 1

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

Html.DropDownList - Disabled/Readonly

For completeness here is the HTML Helper for DropDownListFor that adds enabled parameter, when false select is disabled. It keeps html attributes defined in markup, or it enables usage of html attributes in markup, it posts select value to server and usage is very clean and simple.

Here is the code for helper:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
  if (enabled)
  {
    return SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributes);
  }

  var htmlAttributesAsDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
  htmlAttributesAsDict.Add("disabled", "disabled");
  string selectClientId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
  htmlAttributesAsDict.Add("id", selectClientId + "_disabled");

  var hiddenFieldMarkup = html.HiddenFor<TModel, TProperty>(expression);
  var selectMarkup = SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributesAsDict);
  return MvcHtmlString.Create(selectMarkup.ToString() + Environment.NewLine + hiddenFieldMarkup.ToString());
}

and usage, goal is to disable select if there is just one item in options, markup:

@Html.DropDownListFor(m => m.SomeValue, Model.SomeList, new { @class = "some-class" }, Model.SomeList > 1)

And there is one even more elegant HTML Helper example, no post support for now (pretty straight forward job, just use HAP and add hidden input as root element sibling and swap id's):

public static MvcHtmlString Disable(this MvcHtmlString previous, bool disabled, bool disableChildren = false)
{
  if (disabled)
  {
    var canBeDisabled = new HashSet<string> { "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea" };
    var doc = new HtmlDocument();
    doc.LoadHtml(previous.ToString());
    var rootElements = doc.DocumentNode.Descendants().Where(
      hn => hn.NodeType == HtmlNodeType.Element && 
      canBeDisabled.Contains(hn.Name.ToLower()) && 
      (disableChildren || hn.ParentNode.NodeType == HtmlNodeType.Document));

    foreach (var element in rootElements)
    {
      element.SetAttributeValue("disabled", "");
    }
    string html = doc.DocumentNode.OuterHtml;
    return MvcHtmlString.Create(html);
  }
  return previous;
}

For example there is a model property bool AllInputsDisabled, when true all html inputs should be disabled:

@Html.TextBoxFor(m => m.Address, new { placeholder = "Enter address" }).Disable(Model.AllInputsDisabled)

@Html.DropDownListFor(m => m.DoYou, Model.YesNoList).Disable(Model.AllInputsDisabled)

What size should apple-touch-icon.png be for iPad and iPhone?

Updated list December 2019, iOS13 One icon for iOS 180x180 px and one for android 192x192 px (declared in site.webmanifest).

<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
#### site.webmanifest
{
    "name": "",
    "short_name": "",
    "icons": [
        {
            "src": "/android-chrome-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        }
    ],
    "display": "standalone"
}

Deprecated list October 2017, iOS11

List for iPhone and iPad with and without retina

<!-- iPhone(first generation or 2G), iPhone 3G, iPhone 3GS -->
<link rel="apple-touch-icon" sizes="57x57" href="touch-icon-iphone.png">
<!-- iPad and iPad mini @1x -->
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
<!-- iPhone 4, iPhone 4s, iPhone 5, iPhone 5c, iPhone 5s, iPhone 6, iPhone 6s, iPhone 7, iPhone 7s, iPhone8 -->
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
<!-- iPad and iPad mini @2x -->
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">
<!-- iPad Pro -->
<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-pro.png">
<!-- iPhone X, iPhone 8 Plus, iPhone 7 Plus, iPhone 6s Plus, iPhone 6 Plus -->
<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-6-plus.png">
<!-- Android Devices High Resolution -->
<link rel="icon" sizes="192x192" href="icon-hd.png">
<!-- Android Devices Normal Resolution -->
<link rel="icon" sizes="128x128" href="icon.png">

Update Oct 2017 iOS 11: iOS 11 checked, iPhone X and iPhone 8 introduced

Update Nov 2016 iOS 10: New iOS version iPhone 7 and iPhone 7plus introduced, they have the same display resolution, dpi, etc as iPhone 6s and iPhone 7plus, until now no changes found respecting the update 2015

Update Mid 2016 Android: Add Android Devices to the list as the apple-touch links are marked as deprecated by Google and will be not supported anytime for their devices

<!-- Android Devices High Resolution -->
<link rel="icon" sizes="192x192" href="icon-hd.png">
<!-- Android Devices High Resolution -->
<link rel="icon" sizes="128x128" href="icon.png">

Update 2015 iOS 9: For iOS 9 and iPad pro

<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-pro.png">

The new iPhones (6s and 6s Plus) are using the same sizes as the iPhone(6 and 6 Plus), the new iPad pro uses an image of size 167x167 px, the other resolutions are still the same.

Update 2014 iOS 8:

For iOS 8 and iPhone 6 plus

<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-6-plus.png"> 

Iphone 6 uses the same 120 x 120 px image as iphone 4 and 5 the rest is the same as for iOS 7

Update 2013 iOS7:

For iOS 7 the recommended resolutions changed:

  • for iPhone Retina from 114 x 114 px to 120 x 120 px
  • for iPad Retina from 144 x 144 px to 152 x 152 px

The other resolution are still the same

  • 57 x 57 px default
  • 76 x 76 px for iPads without retina

Source: https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/

Breaking out of a nested loop

C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable INT_MAX -1 is often good choice):

for (int i = 0; i < 100; i++)
{
    for (int j = 0; j < 100; j++)
    {
        if (exit_condition)
        {
            // cause the outer loop to break:
            // use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue 
            i = int.MaxValue - 1;
            Console.WriteLine("Hi");
            // break the inner loop
            break;
        }
    }
    // if you have code in outer loop it will execute after break from inner loop    
}

As note in code says break will not magically jump to next iteration of the outer loop - so if you have code outside of inner loop this approach requires more checks. Consider other solutions in such case.

This approach works with for and while loops but does not work for foreach. In case of foreach you won't have code access to the hidden enumerator so you can't change it (and even if you could IEnumerator doesn't have some "MoveToEnd" method).

Acknowledgments to inlined comments' authors:
i = INT_MAX - 1 suggestion by Meta
for/foreach comment by ygoe.
Proper IntMax by jmbpiano
remark about code after inner loop by blizpasta

How to get elements with multiple classes

AND (both classes)

var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");

OR (at least one class)

var list = document.querySelectorAll(".class1,.class2");

XOR (one class but not the other)

var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");

NAND (not both classes)

var list = document.querySelectorAll(":not(.class1),:not(.class2)");

NOR (not any of the two classes)

var list = document.querySelectorAll(":not(.class1):not(.class2)");

jQuery select change event get selected option

$('select').on('change', function (e) {
    var optionSelected = $("option:selected", this);
    var valueSelected = this.value;
    ....
});

How do I set the driver's python version in spark?

I was running it in IPython (as described in this link by Jacek Wasilewski ) and was getting this exception; Added PYSPARK_PYTHON to the IPython kernel file and used jupyter notebook to run, and started working.

vi  ~/.ipython/kernels/pyspark/kernel.json

{
 "display_name": "pySpark (Spark 1.4.0)",
 "language": "python",
 "argv": [
  "/usr/bin/python2",
  "-m",
  "IPython.kernel",
  "--profile=pyspark",
  "-f",
  "{connection_file}"
 ],

 "env": {
  "SPARK_HOME": "/usr/local/spark-1.6.1-bin-hadoop2.6/",
  "PYTHONPATH": "/usr/local/spark-1.6.1-bin-hadoop2.6/python/:/usr/local/spark-1
.6.1-bin-hadoop2.6/python/lib/py4j-0.8.2.1-src.zip",
  "PYTHONSTARTUP": "/usr/local/spark-1.6.1-bin-hadoop2.6/python/pyspark/shell.py
",
  "PYSPARK_SUBMIT_ARGS": "--master spark://127.0.0.1:7077 pyspark-shell",
  "PYSPARK_DRIVER_PYTHON":"ipython2",
   "PYSPARK_PYTHON": "python2"
 }

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

How to scroll to top of page with JavaScript/jQuery?

I remember seeing this posted somewhere else (I couldn't find where), but this works really well:

setTimeout(() => {
    window.scrollTo(0, 0);
}, 0);

It's weird, but the way it works is based off of the way JavaScript's stack queue works. The full explanation is found here in the Zero Delays section.

The basic idea is that the time for setTimeout doesn't actually specify the set amount of time it will wait, but the minimum amount of time it will wait. So when you tell it to wait 0ms, the browser runs all the other queued processes (like scrolling the window to where you were last) and then executes the callback.

How do you create nested dict in Python?

If you want to create a nested dictionary given a list (arbitrary length) for a path and perform a function on an item that may exist at the end of the path, this handy little recursive function is quite helpful:

def ensure_path(data, path, default=None, default_func=lambda x: x):
    """
    Function:

    - Ensures a path exists within a nested dictionary

    Requires:

    - `data`:
        - Type: dict
        - What: A dictionary to check if the path exists
    - `path`:
        - Type: list of strs
        - What: The path to check

    Optional:

    - `default`:
        - Type: any
        - What: The default item to add to a path that does not yet exist
        - Default: None

    - `default_func`:
        - Type: function
        - What: A single input function that takes in the current path item (or default) and adjusts it
        - Default: `lambda x: x` # Returns the value in the dict or the default value if none was present
    """
    if len(path)>1:
        if path[0] not in data:
            data[path[0]]={}
        data[path[0]]=ensure_path(data=data[path[0]], path=path[1:], default=default, default_func=default_func)
    else:
        if path[0] not in data:
            data[path[0]]=default
        data[path[0]]=default_func(data[path[0]])
    return data

Example:

data={'a':{'b':1}}
ensure_path(data=data, path=['a','c'], default=[1])
print(data) #=> {'a':{'b':1, 'c':[1]}}
ensure_path(data=data, path=['a','c'], default=[1], default_func=lambda x:x+[2])
print(data) #=> {'a': {'b': 1, 'c': [1, 2]}}