Programs & Examples On #Hammer

HAMMER is a high-availability filesystem written for DragonFly BSD. For a web development application on Macs, use the [tag:hammerformac] tag. For the JavaScript Hammer library, use the [tag:hammer.js] tag.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

I solved the same issue by following steps:

Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10

After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap

In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",

Now after updating package.json, use the command npm update

After this use command ng serve and my error got resolved

How to upgrade Angular CLI project?

JJB's answer got me on the right track, but the upgrade didn't go very smoothly. My process is detailed below. Hopefully the process becomes easier in the future and JJB's answer can be used or something even more straightforward.

Solution Details

I have followed the steps captured in JJB's answer to update the angular-cli precisely. However, after running npm install angular-cli was broken. Even trying to do ng version would produce an error. So I couldn't do the ng init command. See error below:

$ ng init
core_1.Version is not a constructor
TypeError: core_1.Version is not a constructor
    at Object.<anonymous> (C:\_git\my-project\code\src\main\frontend\node_modules\@angular\compiler-cli\src\version.js:18:19)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    ...

To be able to use any angular-cli commands, I had to update my package.json file by hand and bump the @angular dependencies to 2.4.1, then do another npm install.

After this I was able to do ng init. I updated my configuration files, but none of my app/* files. When this was done, I was still getting errors. The first one is detailed below, the second was the same type of error but in a different file.

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 62:9 in the original .ts file), resolving symbol AppModule in C:/_git/my-project/code/src/main/frontend/src/app/app.module.ts

This error is tied to the following factory provider in my AppModule

{ provide: Http, useFactory: 
    (backend: XHRBackend, options: RequestOptions, router: Router, navigationService: NavigationService, errorService: ErrorService) => {
    return new HttpRerouteProvider(backend, options, router, navigationService, errorService);  
  }, deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}

To address this error, I had use an exported function and made the following change to the provider.

    { 
      provide: Http, 
      useFactory: httpFactory, 
      deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
    }

... // elsewhere in AppModule

export function httpFactory(backend: XHRBackend, 
                            options: RequestOptions, 
                            router: Router, 
                            navigationService: NavigationService, 
                            errorService: ErrorService) {
  return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}

Summary

To summarize what I understand to be the most important details, the following changes were required:

  1. Update angular-cli version using the steps detailed in JJB's answer (and on their github page).

  2. Updating @angular version by hand, 2.0.0 did not seem to be supported by angular-cli version 1.0.0-beta.24

  3. With the assistance of angular-cli and the ng init command, I updated my configuration files. I think the critical changes were to angular-cli.json and package.json. See configuration file changes at the bottom.

  4. Make code changes to export functions before I reference them, as captured in the solution details.

Key Configuration Changes

angular-cli.json changes

{
  "project": {
    "version": "1.0.0-beta.16",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": "assets",
...

changed to...

{
  "project": {
    "version": "1.0.0-beta.24",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
...

My package.json looks like this after a manual merge that considers the versions used by ng-init. Note my angular version is not 2.4.1, but the change I was after was component inheritance which was introduced in 2.3, so I was fine with these versions. The original package.json is in the question.

{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build",
    "buildProd": "ng build --env=prod"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "@angular/material": "^2.0.0-beta.1",
    "@types/google-libphonenumber": "^7.4.8",
    "angular2-datatable": "^0.4.2",
    "apollo-client": "^0.4.22",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2",
    "google-libphonenumber": "^2.0.4",
    "graphql-tag": "^0.1.15",
    "hammerjs": "^2.0.8",
    "ng2-bootstrap": "^1.1.16"
  },
  "devDependencies": {
    "@types/hammerjs": "^2.0.33",
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "^4.14.39",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.24",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3",
    "typings": "1.4.0"
  }
}

Consider marking event handler as 'passive' to make the page more responsive

Also encounter this in select2 dropdown plugin in Laravel. Changing the value as suggested by Alfred Wallace from

this.element.addEventListener(t, e, !1)

to

this.element.addEventListener(t, e, { passive: true} )

solves the issue. Why he has a down vote, I don't know but it works for me.

Summarizing count and conditional aggregate functions on the same factor

Assuming that your original dataset is similar to the one you created (i.e. with NA as character. You could specify na.strings while reading the data using read.table. But, I guess NAs would be detected automatically.

The price column is factor which needs to be converted to numeric class. When you use as.numeric, all the non-numeric elements (i.e. "NA", FALSE) gets coerced to NA) with a warning.

library(dplyr)
df %>%
     mutate(price=as.numeric(as.character(price))) %>%  
     group_by(company, year, product) %>%
     summarise(total.count=n(), 
               count=sum(is.na(price)), 
               avg.price=mean(price,na.rm=TRUE),
               max.price=max(price, na.rm=TRUE))

data

I am using the same dataset (except the ... row) that was showed.

df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
 year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
 "Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
 "7.12", "12.99", "10.99", "NA",FALSE)))

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

"Update-Package –reinstall Microsoft.AspNet.WebPages"

Reinstall Microsoft.AspNet.WebPages nuget packages using this command in the package manager console. 100% work!!

Read Excel sheet in Powershell

This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.

$lastCell = 11 
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7

$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row

$phoneData = for ($i=1; $i -le $endRow; $i++)
            {
                $pModel = $sh.Cells.Item($startRow,$model).Value2
                $pMAC = $sh.Cells.Item($startRow,$mac).Value2
                $nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
                $extension = $sh.Cells.Item($startRow,$ext).Value2
                New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
                $startRow++
            }

I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

How do I shut down a python simpleHTTPserver?

if you have started the server with

python -m SimpleHTTPServer 8888 

then you can press ctrl + c to down the server.

But if you have started the server with

python -m SimpleHTTPServer 8888 &

or

python -m SimpleHTTPServer 8888 & disown

you have to see the list first to kill the process,

run command

ps

or

ps aux | less

it will show you some running process like this ..

PID TTY          TIME CMD
7247 pts/3     00:00:00 python
7360 pts/3     00:00:00 ps
23606 pts/3    00:00:00 bash

you can get the PID from here. and kill that process by running this command..

kill -9 7247

here 7247 is the python id.

Also for some reason if the port still open you can shut down the port with this command

fuser -k 8888/tcp

here 8888 is the tcp port opened by python.

Hope its clear now.

Adding calculated column(s) to a dataframe in pandas

The first four functions you list will work on vectors as well, with the exception that lower_wick needs to be adapted. Something like this,

def lower_wick_vec(o, l, c):
    min_oc = numpy.where(o > c, c, o)
    return min_oc - l

where o, l and c are vectors. You could do it this way instead which just takes the df as input and avoid using numpy, although it will be much slower:

def lower_wick_df(df):
    min_oc = df[['Open', 'Close']].min(axis=1)
    return min_oc - l

The other three will work on columns or vectors just as they are. Then you can finish off with

def is_hammer(df):
    lw = lower_wick_at_least_twice_real_body(df["Open"], df["Low"], df["Close"]) 
    cl = closed_in_top_half_of_range(df["High"], df["Low"], df["Close"])
    return cl & lw

Bit operators can perform set logic on boolean vectors, & for and, | for or etc. This is enough to completely vectorize the sample calculations you gave and should be relatively fast. You could probably speed up even more by temporarily working with the numpy arrays underlying the data while performing these calculations.

For the second part, I would recommend introducing a column indicating the pattern for each row and writing a family of functions which deal with each pattern. Then groupby the pattern and apply the appropriate function to each group.

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

How can I make my website's background transparent without making the content (images & text) transparent too?

I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8

The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:

filter:Alpha(opacity=50)

What's the best practice using a settings file in Python?

You can have a regular Python module, say config.py, like this:

truck = dict(
    color = 'blue',
    brand = 'ford',
)
city = 'new york'
cabriolet = dict(
    color = 'black',
    engine = dict(
        cylinders = 8,
        placement = 'mid',
    ),
    doors = 2,
)

and use it like this:

import config
print(config.truck['color'])  

Append an object to a list in R in amortized constant time, O(1)?

The OP (in the April 2012 updated revision of the question) is interested in knowing if there's a way to add to a list in amortized constant time, such as can be done, for example, with a C++ vector<> container. The best answer(s?) here so far only show the relative execution times for various solutions given a fixed-size problem, but do not address any of the various solutions' algorithmic efficiency directly. Comments below many of the answers discuss the algorithmic efficiency of some of the solutions, but in every case to date (as of April 2015) they come to the wrong conclusion.

Algorithmic efficiency captures the growth characteristics, either in time (execution time) or space (amount of memory consumed) as a problem size grows. Running a performance test for various solutions given a fixed-size problem does not address the various solutions' growth rate. The OP is interested in knowing if there is a way to append objects to an R list in "amortized constant time". What does that mean? To explain, first let me describe "constant time":

  • Constant or O(1) growth:

    If the time required to perform a given task remains the same as the size of the problem doubles, then we say the algorithm exhibits constant time growth, or stated in "Big O" notation, exhibits O(1) time growth. When the OP says "amortized" constant time, he simply means "in the long run"... i.e., if performing a single operation occasionally takes much longer than normal (e.g. if a preallocated buffer is exhausted and occasionally requires resizing to a larger buffer size), as long as the long-term average performance is constant time, we'll still call it O(1).

    For comparison, I will also describe "linear time" and "quadratic time":

  • Linear or O(n) growth:

    If the time required to perform a given task doubles as the size of the problem doubles, then we say the algorithm exhibits linear time, or O(n) growth.

  • Quadratic or O(n2) growth:

    If the time required to perform a given task increases by the square of the problem size, them we say the algorithm exhibits quadratic time, or O(n2) growth.

There are many other efficiency classes of algorithms; I defer to the Wikipedia article for further discussion.

I thank @CronAcronis for his answer, as I am new to R and it was nice to have a fully-constructed block of code for doing a performance analysis of the various solutions presented on this page. I am borrowing his code for my analysis, which I duplicate (wrapped in a function) below:

library(microbenchmark)
### Using environment as a container
lPtrAppend <- function(lstptr, lab, obj) {lstptr[[deparse(substitute(lab))]] <- obj}
### Store list inside new environment
envAppendList <- function(lstptr, obj) {lstptr$list[[length(lstptr$list)+1]] <- obj} 
runBenchmark <- function(n) {
    microbenchmark(times = 5,  
        env_with_list_ = {
            listptr <- new.env(parent=globalenv())
            listptr$list <- NULL
            for(i in 1:n) {envAppendList(listptr, i)}
            listptr$list
        },
        c_ = {
            a <- list(0)
            for(i in 1:n) {a = c(a, list(i))}
        },
        list_ = {
            a <- list(0)
            for(i in 1:n) {a <- list(a, list(i))}
        },
        by_index = {
            a <- list(0)
            for(i in 1:n) {a[length(a) + 1] <- i}
            a
        },
        append_ = { 
            a <- list(0)    
            for(i in 1:n) {a <- append(a, i)} 
            a
        },
        env_as_container_ = {
            listptr <- new.env(parent=globalenv())
            for(i in 1:n) {lPtrAppend(listptr, i, i)} 
            listptr
        }   
    )
}

The results posted by @CronAcronis definitely seem to suggest that the a <- list(a, list(i)) method is fastest, at least for a problem size of 10000, but the results for a single problem size do not address the growth of the solution. For that, we need to run a minimum of two profiling tests, with differing problem sizes:

> runBenchmark(2e+3)
Unit: microseconds
              expr       min        lq      mean    median       uq       max neval
    env_with_list_  8712.146  9138.250 10185.533 10257.678 10761.33 12058.264     5
                c_ 13407.657 13413.739 13620.976 13605.696 13790.05 13887.738     5
             list_   854.110   913.407  1064.463   914.167  1301.50  1339.132     5
          by_index 11656.866 11705.140 12182.104 11997.446 12741.70 12809.363     5
           append_ 15986.712 16817.635 17409.391 17458.502 17480.55 19303.560     5
 env_as_container_ 19777.559 20401.702 20589.856 20606.961 20939.56 21223.502     5
> runBenchmark(2e+4)
Unit: milliseconds
              expr         min         lq        mean    median          uq         max neval
    env_with_list_  534.955014  550.57150  550.329366  553.5288  553.955246  558.636313     5
                c_ 1448.014870 1536.78905 1527.104276 1545.6449 1546.462877 1558.609706     5
             list_    8.746356    8.79615    9.162577    8.8315    9.601226    9.837655     5
          by_index  953.989076 1038.47864 1037.859367 1064.3942 1065.291678 1067.143200     5
           append_ 1634.151839 1682.94746 1681.948374 1689.7598 1696.198890 1706.683874     5
 env_as_container_  204.134468  205.35348  208.011525  206.4490  208.279580  215.841129     5
> 

First of all, a word about the min/lq/mean/median/uq/max values: Since we are performing the exact same task for each of 5 runs, in an ideal world, we could expect that it would take exactly the same amount of time for each run. But the first run is normally biased toward longer times due to the fact that the code we are testing is not yet loaded into the CPU's cache. Following the first run, we would expect the times to be fairly consistent, but occasionally our code may be evicted from the cache due to timer tick interrupts or other hardware interrupts that are unrelated to the code we are testing. By testing the code snippets 5 times, we are allowing the code to be loaded into the cache during the first run and then giving each snippet 4 chances to run to completion without interference from outside events. For this reason, and because we are really running the exact same code under the exact same input conditions each time, we will consider only the 'min' times to be sufficient for the best comparison between the various code options.

Note that I chose to first run with a problem size of 2000 and then 20000, so my problem size increased by a factor of 10 from the first run to the second.

Performance of the list solution: O(1) (constant time)

Let's first look at the growth of the list solution, since we can tell right away that it's the fastest solution in both profiling runs: In the first run, it took 854 microseconds (0.854 milliseconds) to perform 2000 "append" tasks. In the second run, it took 8.746 milliseconds to perform 20000 "append" tasks. A naïve observer would say, "Ah, the list solution exhibits O(n) growth, since as the problem size grew by a factor of ten, so did the time required to execute the test." The problem with that analysis is that what the OP wants is the growth rate of a single object insertion, not the growth rate of the overall problem. Knowing that, it's clear then that the list solution provides exactly what the OP wants: a method of appending objects to a list in O(1) time.

Performance of the other solutions

None of the other solutions come even close to the speed of the list solution, but it is informative to examine them anyway:

Most of the other solutions appear to be O(n) in performance. For example, the by_index solution, a very popular solution based on the frequency with which I find it in other SO posts, took 11.6 milliseconds to append 2000 objects, and 953 milliseconds to append ten times that many objects. The overall problem's time grew by a factor of 100, so a naïve observer might say "Ah, the by_index solution exhibits O(n2) growth, since as the problem size grew by a factor of ten, the time required to execute the test grew by a factor of 100." As before, this analysis is flawed, since the OP is interested in the growth of a single object insertion. If we divide the overall time growth by the problem's size growth, we find that the time growth of appending objects increased by a factor of only 10, not a factor of 100, which matches the growth of the problem size, so the by_index solution is O(n). There are no solutions listed which exhibit O(n2) growth for appending a single object.

How to force Sequential Javascript Execution?

I am an old hand at programming and came back recently to my old passion and am struggling to fit in this Object oriented, event driven bright new world and while i see the advantages of the non sequential behavior of Javascript there are time where it really get in the way of simplicity and reusability. A simple example I have worked on was to take a photo (Mobile phone programmed in javascript, HTML, phonegap, ...), resize it and upload it on a web site. The ideal sequence is :

  1. Take a photo
  2. Load the photo in an img element
  3. Resize the picture (Using Pixastic)
  4. Upload it to a web site
  5. Inform the user on success failure

All this would be a very simple sequential program if we would have each step returning control to the next one when it is finished, but in reality :

  1. Take a photo is async, so the program attempt to load it in the img element before it exist
  2. Load the photo is async so the resize picture start before the img is fully loaded
  3. Resize is async so Upload to the web site start before the Picture is completely resized
  4. Upload to the web site is asyn so the program continue before the photo is completely uploaded.

And btw 4 of the 5 steps involve callback functions.

My solution thus is to nest each step in the previous one and use .onload and other similar stratagems, It look something like this :

takeAPhoto(takeaphotocallback(photo) {
  photo.onload = function () {
    resizePhoto(photo, resizePhotoCallback(photo) {
      uploadPhoto(photo, uploadPhotoCallback(status) {
        informUserOnOutcome();
      });
    }); 
  };
  loadPhoto(photo);
});

(I hope I did not make too many mistakes bringing the code to it's essential the real thing is just too distracting)

This is I believe a perfect example where async is no good and sync is good, because contrary to Ui event handling we must have each step finish before the next is executed, but the code is a Russian doll construction, it is confusing and unreadable, the code reusability is difficult to achieve because of all the nesting it is simply difficult to bring to the inner function all the parameters needed without passing them to each container in turn or using evil global variables, and I would have loved that the result of all this code would give me a return code, but the first container will be finished well before the return code will be available.

Now to go back to Tom initial question, what would be the smart, easy to read, easy to reuse solution to what would have been a very simple program 15 years ago using let say C and a dumb electronic board ?

The requirement is in fact so simple that I have the impression that I must be missing a fundamental understanding of Javsascript and modern programming, Surely technology is meant to fuel productivity right ?.

Thanks for your patience

Raymond the Dinosaur ;-)

How do I find out what is hammering my SQL Server?

I assume due diligence here that you confirmed the CPU is actually consumed by SQL process (perfmon Process category counters would confirm this). Normally for such cases you take a sample of the relevant performance counters and you compare them with a baseline that you established in normal load operating conditions. Once you resolve this problem I recommend you do establish such a baseline for future comparisons.

You can find exactly where is SQL spending every single CPU cycle. But knowing where to look takes a lot of know how and experience. Is is SQL 2005/2008 or 2000 ? Fortunately for 2005 and newer there are a couple of off the shelf solutions. You already got a couple good pointer here with John Samson's answer. I'd like to add a recommendation to download and install the SQL Server Performance Dashboard Reports. Some of those reports include top queries by time or by I/O, most used data files and so on and you can quickly get a feel where the problem is. The output is both numerical and graphical so it is more usefull for a beginner.

I would also recommend using Adam's Who is Active script, although that is a bit more advanced.

And last but not least I recommend you download and read the MS SQL Customer Advisory Team white paper on performance analysis: SQL 2005 Waits and Queues.

My recommendation is also to look at I/O. If you added a load to the server that trashes the buffer pool (ie. it needs so much data that it evicts the cached data pages from memory) the result would be a significant increase in CPU (sounds surprising, but is true). The culprit is usually a new query that scans a big table end-to-end.

Is there a limit on number of tcp/ip connections between machines on linux?

You might wanna check out /etc/security/limits.conf

IIS7 Cache-Control

The F5 Refresh has the semantic of "please reload the current HTML AND its direct dependancies". Hence you should expect to see any imgs, css and js resource directly referenced by the HTML also being refetched. Of course a 304 is an acceptable response to this but F5 refresh implies that the browser will make the request rather than rely on fresh cache content.

Instead try simply navigating somewhere else and then navigating back.

You can force the refresh, past a 304, by holding ctrl while pressing f5 in most browsers.

Multi-gradient shapes

You CAN do it using only xml shapes - just use layer-list AND negative padding like this:

    <layer-list>

        <item>
            <shape>
                <solid android:color="#ffffff" />

                <padding android:top="20dp" />
            </shape>
        </item>

        <item>
            <shape>
                <gradient android:endColor="#ffffff" android:startColor="#efefef" android:type="linear" android:angle="90" />

                <padding android:top="-20dp" />
            </shape>
        </item>

    </layer-list>

How to get client IP address in Laravel 5+

If you want client IP and your server is behind aws elb, then user the following code. Tested for laravel 5.3

$elbSubnet = '172.31.0.0/16';
Request::setTrustedProxies([$elbSubnet]);
$clientIp = $request->ip();

pip install access denied on Windows

Personally, I found that by opening cmd as admin then run python -m pip install mitproxy seems to fix my problem.

Note:- I installed python through chocolatey

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

PowerShell: how to grep command output?

For a more flexible and lazy solution, you could match all properties of the objects. Most of the time, this should get you the behavior you want, and you can always be more specific when it doesn't. Here's a grep function that works based on this principle:

Function Select-ObjectPropertyValues {
    param(
    [Parameter(Mandatory=$true,Position=0)]
    [String]
    $Pattern,
    [Parameter(ValueFromPipeline)]
    $input)

    $input | Where-Object {($_.PSObject.Properties | Where-Object {$_.Value -match $Pattern} | Measure-Object).count -gt 0} | Write-Output
}

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

This resolved issue for me.

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'password';

GRANT ALL PRIVILEGES ON *.cfe TO 'root'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;

how do I use an enum value on a switch statement in C++

#include <iostream>
using namespace std;

int main() {

    enum level {EASY = 1, NORMAL, HARD};

    // Present menu
    int choice;
    cout << "Choose your level:\n\n";
    cout << "1 - Easy.\n";
    cout << "2 - Normal.\n";
    cout << "3 - Hard.\n\n";
    cout << "Choice --> ";
    cin >> choice;
    cout << endl;

    switch (choice) {
    case EASY:
        cout << "You chose Easy.\n";
        break;
    case NORMAL:
        cout << "You chose Normal.\n";
        break;
    case HARD:
        cout << "You chose Hard.\n";
        break;
    default:
        cout << "Invalid choice.\n";
    }

    return 0;
}

jQuery detect if string contains something

You could use String.prototype.indexOf to accomplish that. Try something like this:

_x000D_
_x000D_
$('.type').keyup(function() {_x000D_
  var v = $(this).val();_x000D_
  if (v.indexOf('> <') !== -1) {_x000D_
    console.log('contains > <');_x000D_
  }_x000D_
  console.log(v);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea class="type"></textarea>
_x000D_
_x000D_
_x000D_

Update

Modern browsers also have a String.prototype.includes method.

How to have multiple conditions for one if statement in python

Might be a bit odd or bad practice but this is one way of going about it.

(arg1, arg2, arg3) = (1, 2, 3)

if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
    print('Example.')

Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

How to get multiple selected values from select box in JSP?

It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.

// jsp form
    <form:select path="friendlyNumber" items="${friendlyNumberItems}" />

    // the command class
    public class NumberCmd {
      private String[] friendlyNumber;
    }

    // in your Spring MVC controller submit method
    @RequestMapping(method=RequestMethod.POST)
    public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){

       String[] selectedNumbers = nbrCmd.getFriendlyNumber();

    }

python JSON object must be str, bytes or bytearray, not 'dict

json.dumps() is used to decode JSON data

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

json.loads() is used to convert JSON data into Python data.

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

output:

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
  • JSON Data to Python Object Conversion
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |

Node.js: Difference between req.query[] and req.params

Suppose you have defined your route name like this:

https://localhost:3000/user/:userid

which will become:

https://localhost:3000/user/5896544

Here, if you will print: request.params

{
userId : 5896544
}

so

request.params.userId = 5896544

so request.params is an object containing properties to the named route

and request.query comes from query parameters in the URL eg:

https://localhost:3000/user?userId=5896544 

request.query

{

userId: 5896544

}

so

request.query.userId = 5896544

Reading Xml with XmlReader in C#

    XmlDataDocument xmldoc = new XmlDataDocument();
    XmlNodeList xmlnode ;
    int i = 0;
    string str = null;
    FileStream fs = new FileStream("product.xml", FileMode.Open, FileAccess.Read);
    xmldoc.Load(fs);
    xmlnode = xmldoc.GetElementsByTagName("Product");

You can loop through xmlnode and get the data...... C# XML Reader

Content-Disposition:What are the differences between "inline" and "attachment"?

If it is inline, the browser should attempt to render it within the browser window. If it cannot, it will resort to an external program, prompting the user.

With attachment, it will immediately go to the user, and not try to load it in the browser, whether it can or not.

afxwin.h file is missing in VC++ Express Edition

Found this post that may help: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/7c274008-80eb-42a0-a79b-95f5afbf6528/

Or shortly, afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition).

Keras input explanation: input_shape, units, batch_size, dim, etc

Units:

The amount of "neurons", or "cells", or whatever the layer has inside it.

It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

  • Hidden layer 1: 4 units (4 neurons)
  • Hidden layer 2: 4 units
  • Last layer: 1 unit

Shapes

Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

The input shape

What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

Each type of layer requires the input with a certain number of dimensions:

  • Dense layers require inputs as (batch_size, input_size)
    • or (batch_size, optional,...,optional, input_size)
  • 2D convolutional layers need inputs as:
    • if using channels_last: (batch_size, imageside1, imageside2, channels)
    • if using channels_first: (batch_size, channels, imageside1, imageside2)
  • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).

Weights

Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.

Dim

And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.


Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

don't fail jenkins build if execute shell fails

Jenkins is executing shell build steps using /bin/sh -xe by default. -x means to print every command executed. -e means to exit with failure if any of the commands in the script failed.

So I think what happened in your case is your git command exit with 1, and because of the default -e param, the shell picks up the non-0 exit code, ignores the rest of the script and marks the step as a failure. We can confirm this if you can post your build step script here.

If that's the case, you can try to put #!/bin/sh so that the script will be executed without option; or do a set +e or anything similar on top of the build step to override this behavior.


Edited: Another thing to note is that, if the last command in your shell script returns non-0 code, the whole build step will still be marked as fail even with this setup. In this case, you can simply put a true command at the end to avoid that.

Another related question

What is tempuri.org?

Probably to guarantee that public webservices will be unique.

It always makes me think of delicious deep fried treats...

Pandas: Creating DataFrame from Series

No need to initialize an empty DataFrame (you weren't even doing that, you'd need pd.DataFrame() with the parens).

Instead, to create a DataFrame where each series is a column,

  1. make a list of Series, series, and
  2. concatenate them horizontally with df = pd.concat(series, axis=1)

Something like:

series = [pd.Series(mat[name][:, 1]) for name in Variables]
df = pd.concat(series, axis=1)

How to read and write excel file

I edited the most voted one a little cuz it didn't count blanks columns or rows well not totally, so here is my code i tested it and now can get any cell in any part of an excel file. also now u can have blanks columns between filled column and it will read them

  try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(Dir));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;

int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();

int cols = 0; // No of columns
int tmp = 0;
int cblacks=0;

// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i <= 10 || i <= rows; i++) {
    row = sheet.getRow(i);
    if(row != null) {
        tmp = sheet.getRow(i).getPhysicalNumberOfCells();
        if(tmp >= cols) cols = tmp;else{rows++;cblacks++;}
    }

    cols++;
}
cols=cols+cblacks;
for(int r = 0; r < rows; r++) {
    row = sheet.getRow(r);
    if(row != null) {
        for(int c = 0; c < cols; c++) {
            cell = row.getCell(c);
            if(cell != null) {
                System.out.print(cell+"\n");//Your Code here
            }
        }
    }
}} catch(Exception ioe) {
ioe.printStackTrace();}

Creating a very simple linked list

A Linked List, at its core is a bunch of Nodes linked together.

So, you need to start with a simple Node class:

public class Node {
    public Node next;
    public Object data;
}

Then your linked list will have as a member one node representing the head (start) of the list:

public class LinkedList {
    private Node head;
}

Then you need to add functionality to the list by adding methods. They usually involve some sort of traversal along all of the nodes.

public void printAllNodes() {
    Node current = head;
    while (current != null) 
    {
        Console.WriteLine(current.data);
        current = current.next;
    }
}

Also, inserting new data is another common operation:

public void Add(Object data) {
    Node toAdd = new Node();
    toAdd.data = data;
    Node current = head;
    // traverse all nodes (see the print all nodes method for an example)
    current.next = toAdd;
}

This should provide a good starting point.

Use virtualenv with Python with Visual Studio Code in Ubuntu

On Mac OS X using Visual Studio Code version 1.34.0 (1.34.0) I had to do the following to get Visual Studio Code to recognise the virtual environments:

Location of my virtual environment (named ml_venv):

/Users/auser/.pyvenv/ml_venv

auser@HOST:~/.pyvenv$ tree -d -L 2
.
+-- ml_venv
    +-- bin
    +-- include
    +-- lib

I added the following entry in Settings.json: "python.venvPath": "/Users/auser/.pyvenv"

I restarted the IDE, and now I could see the interpreter from my virtual environment:

Enter image description here

How to include a class in PHP

Your code should be something like

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

How to cast int to enum in C++?

Your code

enum Test
{
    A, B
}

int a = 1;

Solution

Test castEnum = static_cast<Test>(a);

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

l = [1, 2, 3]
print '\n'.join(['%i: %s' % (n, l[n]) for n in xrange(len(l))])

What is the difference between signed and unsigned variables?

Signed variables can be 0, positive or negative.

Unsigned variables can be 0 or positive.

Unsigned variables are used sometimes because more bits can be used to represent the actual value. Giving you a larger range. Also you can ensure that a negative value won't be passed to your function for example.

Get value of c# dynamic property via string

Similar to the accepted answer, you can also try GetField instead of GetProperty.

d.GetType().GetField("value2").GetValue(d);

Depending on how the actual Type was implemented, this may work when GetProperty() doesn't and can even be faster.

Passing enum or object through an intent (the best solution)

Most of the answers that are using Parcelable concept here are in Java code. It is easier to do it in Kotlin.

Just annotate your enum class with @Parcelize and implement Parcelable interface.

@Parcelize
enum class ViewTypes : Parcelable {
TITLE, PRICES, COLORS, SIZES
}

How to amend a commit without changing commit message (reusing the previous one)?

git commit -C HEAD --amend will do what you want. The -C option takes the metadata from another commit.

summing two columns in a pandas dataframe

I think you've misunderstood some python syntax, the following does two assignments:

In [11]: a = b = 1

In [12]: a
Out[12]: 1

In [13]: b
Out[13]: 1

So in your code it was as if you were doing:

sum = df['budget'] + df['actual']  # a Series
# and
df['variance'] = df['budget'] + df['actual']  # assigned to a column

The latter creates a new column for df:

In [21]: df
Out[21]:
  cluster                 date  budget  actual
0       a  2014-01-01 00:00:00   11000   10000
1       a  2014-02-01 00:00:00    1200    1000
2       a  2014-03-01 00:00:00     200     100
3       b  2014-04-01 00:00:00     200     300
4       b  2014-05-01 00:00:00     400     450
5       c  2014-06-01 00:00:00     700    1000
6       c  2014-07-01 00:00:00    1200    1000
7       c  2014-08-01 00:00:00     200     100
8       c  2014-09-01 00:00:00     200     300

In [22]: df['variance'] = df['budget'] + df['actual']

In [23]: df
Out[23]:
  cluster                 date  budget  actual  variance
0       a  2014-01-01 00:00:00   11000   10000     21000
1       a  2014-02-01 00:00:00    1200    1000      2200
2       a  2014-03-01 00:00:00     200     100       300
3       b  2014-04-01 00:00:00     200     300       500
4       b  2014-05-01 00:00:00     400     450       850
5       c  2014-06-01 00:00:00     700    1000      1700
6       c  2014-07-01 00:00:00    1200    1000      2200
7       c  2014-08-01 00:00:00     200     100       300
8       c  2014-09-01 00:00:00     200     300       500

As an aside, you shouldn't use sum as a variable name as the overrides the built-in sum function.

Can you require two form fields to match with HTML5?

As has been mentioned in other answers, there is no pure HTML5 way to do this.

If you are already using JQuery, then this should do what you need:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#ourForm').submit(function(e){_x000D_
      var form = this;_x000D_
      e.preventDefault();_x000D_
      // Check Passwords are the same_x000D_
      if( $('#pass1').val()==$('#pass2').val() ) {_x000D_
          // Submit Form_x000D_
          alert('Passwords Match, submitting form');_x000D_
          form.submit();_x000D_
      } else {_x000D_
          // Complain bitterly_x000D_
          alert('Password Mismatch');_x000D_
          return false;_x000D_
      }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="ourForm">_x000D_
    <input type="password" name="password" id="pass1" placeholder="Password" required>_x000D_
    <input type="password" name="password" id="pass2" placeholder="Repeat Password" required>_x000D_
    <input type="submit" value="Go">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Padding a table row

You could simply add this style to the table.

table {
    border-spacing: 15px;
}

Check if a Postgres JSON array contains a string

Not smarter but simpler:

select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';

What's the UIScrollView contentInset property for?

While jball's answer is an excellent description of content insets, it doesn't answer the question of when to use it. I'll borrow from his diagrams:

  _|?_cW_?_|_?_
   |       | 
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
   |content|    
-------------?-

That's what you get when you do it, but the usefulness of it only shows when you scroll:

  _|?_cW_?_|_?_
   |content| ? content is still visible
---------------
   |content| ?
 ? |content| contentInset.top
cH |content|
 ? |content| contentInset.bottom
   |content| ?
---------------
  _|_______|___ 
             ?

That top row of content will still be visible because it's still inside the frame of the scroll view. One way to think of the top offset is "how much to shift the content down the scroll view when we're scrolled all the way to the top"

To see a place where this is actually used, look at the build-in Photos app on the iphone. The Navigation bar and status bar are transparent, and the contents of the scroll view are visible underneath. That's because the scroll view's frame extends out that far. But if it wasn't for the content inset, you would never be able to have the top of the content clear that transparent navigation bar when you go all the way to the top.

The source was not found, but some or all event logs could not be searched

For me this error was due to the command prompt, which was not running under administrator privileges. You need to right click on the command prompt and say "Run as administrator".

You need administrator role to install or uninstall a service.

How to get column values in one comma separated value

You tagged the question with both sql-server and plsql so I will provide answers for both SQL Server and Oracle.

In SQL Server you can use FOR XML PATH to concatenate multiple rows together:

select distinct t.[user],
  STUFF((SELECT distinct ', ' + t1.department
         from yourtable t1
         where t.[user] = t1.[user]
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,2,'') department
from yourtable t;

See SQL Fiddle with Demo.

In Oracle 11g+ you can use LISTAGG:

select "User",
  listagg(department, ',') within group (order by "User") as departments
from yourtable
group by "User"

See SQL Fiddle with Demo

Prior to Oracle 11g, you could use the wm_concat function:

select "User",
  wm_concat(department) departments
from yourtable
group by "User"

Append String in Swift

You can simply append string like:

var worldArg = "world is good"

worldArg += " to live";

Calling a class method raises a TypeError in Python

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.

How can I remove the string "\n" from within a Ruby string?

You don't need a regex for this. Use tr:

"some text\nandsomemore".tr("\n","")

CSS Background Opacity

I would do something like this

<div class="container">
  <div class="text">
    <p>text yay!</p>
  </div>
</div>

CSS:

.container {
    position: relative;
}

.container::before {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: url('/path/to/image.png');
    opacity: .4;
    content: "";
    z-index: -1;
}

It should work. This is assuming you are required to have a semi-transparent image BTW, and not a color (which you should just use rgba for). Also assumed is that you can't just alter the opacity of the image beforehand in Photoshop.

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

Pip freeze vs. pip list

pip list shows ALL installed packages.

pip freeze shows packages YOU installed via pip (or pipenv if using that tool) command in a requirements format.

Remark below that setuptools, pip, wheel are installed when pipenv shell creates my virtual envelope. These packages were NOT installed by me using pip:

test1 % pipenv shell
Creating a virtualenv for this project…
Pipfile: /Users/terrence/Development/Python/Projects/test1/Pipfile
Using /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 (3.8.1) to create virtualenv…
? Creating virtual environment...
<SNIP>
Installing setuptools, pip, wheel...
done.
? Successfully created virtual environment! 
<SNIP>

Now review & compare the output of the respective commands where I've only installed cool-lib and sampleproject (of which peppercorn is a dependency):

test1 % pip freeze       <== Packages I'VE installed w/ pip

-e git+https://github.com/gdamjan/hello-world-python-package.git@10<snip>71#egg=cool_lib
peppercorn==0.6
sampleproject==1.3.1


test1 % pip list         <== All packages, incl. ones I've NOT installed w/ pip

Package       Version Location                                                                    
------------- ------- --------------------------------------------------------------------------
cool-lib      0.1  /Users/terrence/.local/share/virtualenvs/test1-y2Zgz1D2/src/cool-lib           <== Installed w/ `pip` command
peppercorn    0.6       <== Dependency of "sampleproject"
pip           20.0.2  
sampleproject 1.3.1     <== Installed w/ `pip` command
setuptools    45.1.0  
wheel         0.34.2

Using PHP variables inside HTML tags?

HI Jasper,

you can do this:

<?
sprintf("<a href=\"http://www.whatever.com/%s\">Click Here</a>", $param);
?>

How to set tbody height with overflow scroll

By default overflow does not apply to table group elements unless you give a display:block to <tbody> also you have to give a position:relative and display: block to <thead>. Check the DEMO.

.fixed {
  width:350px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed th {
  text-decoration: underline;
}
.fixed th,
.fixed td {
  padding: 5px;
  text-align: left;
  min-width: 200px;
}


.fixed thead {
  background-color: red;
  color: #fdfdfd;
}
.fixed thead tr {
  display: block;
  position: relative;
}
.fixed tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 100px;
  overflow-y: scroll;
    overflow-x: hidden;
}

Arrow operator (->) usage in C

Dot is a dereference operator and used to connect the structure variable for a particular record of structure. Eg :

struct student
    {
      int s.no;
      Char name [];
      int age;
    } s1,s2;

main()
    {
      s1.name;
      s2.name;
    }

In such way we can use a dot operator to access the structure variable

UTF-8 encoding in JSP page

Page encoding or anything else do not matter a lot. ISO-8859-1 is a subset of UTF-8, therefore you never have to convert ISO-8859-1 to UTF-8 because ISO-8859-1 is already UTF-8,a subset of UTF-8 but still UTF-8. Plus, all that do not mean a thing if You have a double encoding somewhere. This is my "cure all" recipe for all things encoding and charset related:

        String myString = "heartbroken ð";

//String is double encoded, fix that first.

                myString = new String(myString.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                String cleanedText = StringEscapeUtils.unescapeJava(myString);
                byte[] bytes = cleanedText.getBytes(StandardCharsets.UTF_8);
                String text = new String(bytes, StandardCharsets.UTF_8);
                Charset charset = Charset.forName("UTF-8");
                CharsetDecoder decoder = charset.newDecoder();
                decoder.onMalformedInput(CodingErrorAction.IGNORE);
                decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                CharsetEncoder encoder = charset.newEncoder();
                encoder.onMalformedInput(CodingErrorAction.IGNORE);
                encoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
                try {
                    // The new ByteBuffer is ready to be read.
                    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(text));
                    // The new ByteBuffer is ready to be read.
                    CharBuffer cbuf = decoder.decode(bbuf);
                    String str = cbuf.toString();
                } catch (CharacterCodingException e) {
                    logger.error("Error Message if you want to");

                } 

jQuery get content between <div> tags

var x = '<p>blah</p><div><a href="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=brd&FlightID=2997227&Page=&PluID=0&Pos=9088" target="_blank"><img src="http://bs.serving-sys.com/BurstingPipe/adServer.bs?cn=bsr&FlightID=2997227&Page=&PluID=0&Pos=9088" border=0 width=300 height=250></a></div>';
$(x).children('div').html();

How to configure log4j with a properties file

just set -Dlog4j.configuration=file:log4j.properties worked for me.

log4j then looks for the file log4j.properties in the current working directory of the application.

Remember that log4j.configuration is a URL specification, so add 'file:' in front of your log4j.properties filename if you want to refer to a regular file on the filesystem, i.e. a file not on the classpath!

Initially I specified -Dlog4j.configuration=log4j.properties. However that only works if log4j.properties is on the classpath. When I copied log4j.properties to main/resources in my project and rebuild so that it was copied to the target directory (maven project) this worked as well (or you could package your log4j.properties in your project jars, but that would not allow the user to edit the logger configuration!).

How to use doxygen to create UML class diagrams from C++ source

Doxygen creates inheritance diagrams but I dont think it will create an entire class hierachy. It does allow you to use the GraphViz tool. If you use the Doxygen GUI frontend tool you will find the relevant options in Step2: -> Wizard tab -> Diagrams. The DOT relation options are under the Expert Tab.

Fixing Segmentation faults in C++

On Unix you can use valgrind to find issues. It's free and powerful. If you'd rather do it yourself you can overload the new and delete operators to set up a configuration where you have 1 byte with 0xDEADBEEF before and after each new object. Then track what happens at each iteration. This can fail to catch everything (you aren't guaranteed to even touch those bytes) but it has worked for me in the past on a Windows platform.

How to use a variable for the database name in T-SQL?

Unfortunately you can't declare database names with a variable in that format.

For what you're trying to accomplish, you're going to need to wrap your statements within an EXEC() statement. So you'd have something like:

DECLARE @Sql varchar(max) ='CREATE DATABASE ' + @DBNAME

Then call

EXECUTE(@Sql) or sp_executesql(@Sql)

to execute the sql string.

Python datetime strptime() and strftime(): how to preserve the timezone information

Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.

You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.

If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil.

If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:

d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"

d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)

print dtz_string 
print d2.strftime(fmt) + ' ' + tz_string

Or… halfway between those two, you're already using the pytz library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z in on the formatting side, then pull it off and parse it with pytz.timezone() before passing the rest to strptime.

ORA-00060: deadlock detected while waiting for resource

I was recently struggling with a similar problem. It turned out that the database was missing indexes on foreign keys. That caused Oracle to lock many more records than required which quickly led to a deadlock during high concurrency.

Here is an excellent article with lots of good detail, suggestions, and details about how to fix a deadlock: http://www.oratechinfo.co.uk/deadlocks.html#unindex_fk

Apache Prefork vs Worker MPM

Prefork and worker are two type of MPM apache provides. Both have their merits and demerits.

By default mpm is prefork which is thread safe.

Prefork MPM uses multiple child processes with one thread each and each process handles one connection at a time.

Worker MPM uses multiple child processes with many threads each. Each thread handles one connection at a time.

For more details you can visit https://httpd.apache.org/docs/2.4/mpm.html and https://httpd.apache.org/docs/2.4/mod/prefork.html

Selecting last element in JavaScript array

So, a lot of people are answering with pop(), but most of them don't seem to realize that's a destructive method.

var a = [1,2,3]
a.pop()
//3
//a is now [1,2]

So, for a really silly, nondestructive method:

var a = [1,2,3]
a[a.push(a.pop())-1]
//3

a push pop, like in the 90s :)

push appends a value to the end of an array, and returns the length of the result. so

d=[]
d.push('life') 
//=> 1
d 
//=>['life']

pop returns the value of the last item of an array, prior to it removing that value at that index. so

c = [1,2,1]
c.pop() 
//=> 1
c 
//=> [1,2]

arrays are 0 indexed, so c.length => 3, c[c.length] => undefined (because you're looking for the 4th value if you do that(this level of depth is for any hapless newbs that end up here)).

Probably not the best, or even a good method for your application, what with traffic, churn, blah. but for traversing down an array, streaming it onto another, just being silly with inefficient methods, this. Totally this.

Can't connect Nexus 4 to adb: unauthorized

This kind of an old post and in most cases I think the answer that has been upvoted the most will work for people.

In Lollipop on a GPE HTC M8 I was still having problems. The below steps worked for me.

  1. Go to Settings
  2. Tap on Storage
  3. Tap on 3 dots in the top right
  4. Tap on USB Computer Connection
  5. UNCHECK MTP
  6. UNCHECK PTP
  7. Back in your console, type adb devices

Now you should get the RSA popup on your phone.

How to find files modified in last x minutes (find -mmin does not work as expected)

Manual of find:

   Numeric arguments can be specified as

   +n     for greater than n,

   -n     for less than n,

   n      for exactly n.

   -amin n
          File was last accessed n minutes ago.

   -anewer file
          File was last accessed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the access time of the file it points  to  is  always
          used.

   -atime n
          File  was  last  accessed  n*24 hours ago.  When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to
          have been accessed at least two days ago.

   -cmin n
          File's status was last changed n minutes ago.

   -cnewer file
          File's status was last changed more recently than file was modified.  If file is a symbolic link and the -H option or the -L option is in effect, the status-change time of the file it  points
          to is always used.

   -ctime n
          File's status was last changed n*24 hours ago.  See the comments for -atime to understand how rounding affects the interpretation of file status change times.

Example:

find /dir -cmin -60 # creation time
find /dir -mmin -60 # modification time
find /dir -amin -60 # access time

Graph implementation C++

Below is a implementation of Graph Data Structure in C++ as Adjacency List.

I have used STL vector for representation of vertices and STL pair for denoting edge and destination vertex.

#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

struct vertex {
    typedef pair<int, vertex*> ve;
    vector<ve> adj; //cost of edge, destination vertex
    string name;
    vertex(string s) : name(s) {}
};

class graph
{
public:
    typedef map<string, vertex *> vmap;
    vmap work;
    void addvertex(const string&);
    void addedge(const string& from, const string& to, double cost);
};

void graph::addvertex(const string &name)
{
    vmap::iterator itr = work.find(name);
    if (itr == work.end())
    {
        vertex *v;
        v = new vertex(name);
        work[name] = v;
        return;
    }
    cout << "\nVertex already exists!";
}

void graph::addedge(const string& from, const string& to, double cost)
{
    vertex *f = (work.find(from)->second);
    vertex *t = (work.find(to)->second);
    pair<int, vertex *> edge = make_pair(cost, t);
    f->adj.push_back(edge);
}

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

Had that issue with homebrew MacOS the problem was some sort of permission missing on /usr/local/var/log directory see issue here

In order to solve it I deleted the /usr/local/var/log and reinstall redis brew reinstall redis

Jersey stopped working with InjectionManagerFactory not found

As far as I can see dependencies have changed between 2.26-b03 and 2.26-b04 (HK2 was moved to from compile to testCompile)... there might be some change in the jersey dependencies that has not been completed yet (or which lead to a bug).

However, right now the simple solution is to stick to an older version :-)

Proper way to initialize C++ structs

You need to initialize whatever members you have in your struct, e.g.:

struct MyStruct {
  private:
    int someInt_;
    float someFloat_;

  public:
    MyStruct(): someInt_(0), someFloat_(1.0) {} // Initializer list will set appropriate values

};

Find an object in SQL Server (cross-database)

There is a schema called INFORMATION_SCHEMA schema which contains a set of views on tables from the SYS schema that you can query to get what you want.

A major upside of the INFORMATION_SCHEMA is that the object names are very query friendly and user readable. The downside of the INFORMATION_SCHEMA is that you have to write one query for each type of object.

The Sys schema may seem a little cryptic initially, but it has all the same information (and more) in a single spot.

You'd start with a table called SysObjects (each database has one) that has the names of all objects and their types.

One could search in a database as follows:

Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
    and [Name] like '%YourObjectName%'

Now, if you wanted to restrict this to only search for tables and stored procs, you would do

Select [name] as ObjectName, Type as ObjectType
From Sys.Objects
Where 1=1
    and [Name] like '%YourObjectName%'
    and Type in ('U', 'P')

If you look up object types, you will find a whole list for views, triggers, etc.

Now, if you want to search for this in each database, you will have to iterate through the databases. You can do one of the following:

If you want to search through each database without any clauses, then use the sp_MSforeachdb as shown in an answer here.

If you only want to search specific databases, use the "USE DBName" and then search command.

You will benefit greatly from having it parameterized in that case. Note that the name of the database you are searching in will have to be replaced in each query (DatabaseOne, DatabaseTwo...). Check this out:

Declare @ObjectName VarChar (100)

Set @ObjectName = '%Customer%'

Select 'DatabaseOne' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseOne.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

UNION ALL

Select 'DatabaseTwo' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseTwo.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

UNION ALL

Select 'DatabaseThree' as DatabaseName, [name] as ObjectName, Type as ObjectType
From DatabaseThree.Sys.Objects
Where 1=1
    and [Name] like @ObjectName
    and Type in ('U', 'P')

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

JSON.parse() doesn't recognize That data as string. For example {objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"[email protected]",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}

Which is like this: JSON.parse({objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"[email protected]",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}); That will output SyntaxError: missing " ' " instead of "{" on line...

So correctly wrap all data like this: '{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"[email protected]","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}' Which works perfectly well for me.

And not like this: "{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"[email protected]","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}" Which give the present error you are experiencing.

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works
>>> 

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

mongodb/mongoose findMany - find all documents with IDs listed in array

Use this format of querying

let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));

Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
  .where('category')
  .in(arr)
  .exec();

Import CSV to SQLite

Here's how I did it.

  • Make/Convert csv file to be seperated by tabs (\t) AND not enclosed by any quotes (sqlite interprets quotes literally - says old docs)
  • Enter the sqlite shell of the db to which the data needs to be added

    sqlite> .separator "\t" ---IMPORTANT! should be in double quotes sqlite> .import afile.csv tablename-to-import-to

How to validate IP address in Python?

I have to give a great deal of credit to Markus Jarderot for his post - the majority of my post is inspired from his.

I found that Markus' answer still fails some of the IPv6 examples in the Perl script referenced by his answer.

Here is my regex that passes all of the examples in that Perl script:

r"""^
     \s* # Leading whitespace
     # Zero-width lookaheads to reject too many quartets
     (?:
        # 6 quartets, ending IPv4 address; no wildcards
        (?:[0-9a-f]{1,4}(?::(?!:))){6}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-5 quartets, wildcard, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
        (?:::(?!:))
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-4 quartets, wildcard, 0-1 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:)))?
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-3 quartets, wildcard, 0-2 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,2}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-2 quartets, wildcard, 0-3 quartets, ending IPv4 address
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,3}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 0-1 quartets, wildcard, 0-4 quartets, ending IPv4 address
        (?:[0-9a-f]{1,4}){0,1}
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,4}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # wildcard, 0-5 quartets, ending IPv4 address
        (?:::(?!:))
        (?:[0-9a-f]{1,4}(?::(?!:))){0,5}
             (?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)
        (?:\.(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}
      |
        # 8 quartets; no wildcards
        (?:[0-9a-f]{1,4}(?::(?!:))){7}[0-9a-f]{1,4}
      |
        # 0-7 quartets, wildcard
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
        (?:::(?!:))
      |
        # 0-6 quartets, wildcard, 0-1 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:[0-9a-f]{1,4})?
      |
        # 0-5 quartets, wildcard, 0-2 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
      |
        # 0-4 quartets, wildcard, 0-3 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
      |
        # 0-3 quartets, wildcard, 0-4 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,2}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,3}[0-9a-f]{1,4})?
      |
        # 0-2 quartets, wildcard, 0-5 quartets
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,1}[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,4}[0-9a-f]{1,4})?
      |
        # 0-1 quartets, wildcard, 0-6 quartets
        (?:[0-9a-f]{1,4})?
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,5}[0-9a-f]{1,4})?
      |
        # wildcard, 0-7 quartets
        (?:::(?!:))
        (?:(?:[0-9a-f]{1,4}(?::(?!:))){0,6}[0-9a-f]{1,4})?
     )
     (?:/(?:1(?:2[0-7]|[01]\d)|\d\d?))? # With an optional CIDR routing prefix (0-128)
     \s* # Trailing whitespace
    $"""

I also put together a Python script to test all of those IPv6 examples; it's here on Pastebin because it was too large to post here.

You can run the script with test result and example arguments in the form of "[result]=[example]", so like:

python script.py Fail=::1.2.3.4: pass=::127.0.0.1 false=::: True=::1

or you can simply run all of the tests by specifying no arguments, so like:

python script.py

Anyway, I hope this helps somebody else!

How to call Stored Procedure in Entity Framework 6 (Code-First)?

Using your example, here are two ways to accomplish this:

1 - Use Stored procedure mapping

Note that this code will work with or without mapping. If you turn off mapping on the entity, EF will generate an insert + select statement.

protected void btnSave_Click(object sender, EventArgs e)
{
     using (var db = DepartmentContext() )
     {
        var department = new Department();

        department.Name = txtDepartment.text.trim();

        db.Departments.add(department);
        db.SaveChanges();

        // EF will populate department.DepartmentId
        int departmentID = department.DepartmentId;
     }
}

2 - Call the stored procedure directly

protected void btnSave_Click(object sender, EventArgs e)
{
     using (var db = DepartmentContext() )
     {
        var name = new SqlParameter("@name", txtDepartment.text.trim());

        //to get this to work, you will need to change your select inside dbo.insert_department to include name in the resultset
        var department = db.Database.SqlQuery<Department>("dbo.insert_department @name", name).SingleOrDefault();

       //alternately, you can invoke SqlQuery on the DbSet itself:
       //var department = db.Departments.SqlQuery("dbo.insert_department @name", name).SingleOrDefault();

        int departmentID = department.DepartmentId;
     }
}

I recommend using the first approach, as you can work with the department object directly and not have to create a bunch of SqlParameter objects.

Implement a loading indicator for a jQuery AJAX call

I solved the same problem following this example:

This example uses the jQuery JavaScript library.

First, create an Ajax icon using the AjaxLoad site.
Then add the following to your HTML :

<img src="/images/loading.gif" id="loading-indicator" style="display:none" />

And the following to your CSS file:

#loading-indicator {
  position: absolute;
  left: 10px;
  top: 10px;
}

Lastly, you need to hook into the Ajax events that jQuery provides; one event handler for when the Ajax request begins, and one for when it ends:

$(document).ajaxSend(function(event, request, settings) {
    $('#loading-indicator').show();
});

$(document).ajaxComplete(function(event, request, settings) {
    $('#loading-indicator').hide();
});

This solution is from the following link. How to display an animated icon during Ajax request processing

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.

How to Detect Browser Back Button event - Cross Browser

This will definitely work (For detecting back button click)

$(window).on('popstate', function(event) {
 alert("pop");
});

Multi-dimensional arrays in Bash

If you want to use a bash script and keep it easy to read recommend putting the data in structured JSON, and then use lightweight tool jq in your bash command to iterate through the array. For example with the following dataset:

[

    {"specialId":"123",
    "specialName":"First"},

    {"specialId":"456",
    "specialName":"Second"},

    {"specialId":"789",
    "specialName":"Third"}
]

You can iterate through this data with a bash script and jq like this:

function loopOverArray(){

    jq -c '.[]' testing.json | while read i; do
        # Do stuff here
        echo "$i"
    done
}

loopOverArray

Outputs:

{"specialId":"123","specialName":"First"}
{"specialId":"456","specialName":"Second"}
{"specialId":"789","specialName":"Third"}

docker-compose up for only certain containers

You usually don't want to do this. With Docker Compose you define services that compose your app. npm and manage.py are just management commands. You don't need a container for them. If you need to, say create your database tables with manage.py, all you have to do is:

docker-compose run client python manage.py create_db

Think of it as the one-off dynos Heroku uses.

If you really need to treat these management commands as separate containers (and also use Docker Compose for these), you could create a separate .yml file and start Docker Compose with the following command:

docker-compose up -f my_custom_docker_compose.yml

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I had the same problem, but with small difference. I had added NetworkConnectionCallback to check situation when internet connection had changed at runtime, and checking like this before sending all requests:

private fun isConnected(): Boolean {
    val activeNetwork = cManager.activeNetworkInfo
    return activeNetwork != null && activeNetwork.isConnected
}

There can be state like CONNECTING (you can see i? when you turn on wifi, icon starts blinking, after connecting to network, image is static). So, we have two different states: one CONNECT another CONNECTING, and when Retrofit tried to send request internet connection is disabled and it throws UnknownHostException. I forgot to add another type of exception in function which was responsible for sending requests.

try{
//for example, retrofit call
}
catch (e: Exception) {
        is UnknownHostException -> "Unknown host!"
        is ConnectException -> "No internet!"
        else -> "Unknown exception!"
    }

It's just a tricky moment that can by related with this problem.

Hope, I will help somebody)

How can I schedule a daily backup with SQL Server Express?

Eduardo Molteni had a great answer:

Using Windows Scheduled Tasks:

In the batch file

"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" -S 
(local)\SQLExpress -i D:\dbbackups\SQLExpressBackups.sql

In SQLExpressBackups.sql

BACKUP DATABASE MyDataBase1 TO  DISK = N'D:\DBbackups\MyDataBase1.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase1 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

BACKUP DATABASE MyDataBase2 TO  DISK = N'D:\DBbackups\MyDataBase2.bak' 
WITH NOFORMAT, INIT,  NAME = N'MyDataBase2 Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10

GO

Create a simple HTTP server with Java?

I wrote a tutorial explaining how to write a simple HTTP server a while back in Java. Explains what the code is doing and why the server is written that way as the tutorial progresses. Might be useful http://kcd.sytes.net/articles/simple_web_server.php

C# equivalent of C++ vector, with contiguous memory?

First of all, stay away from Arraylist or Hashtable. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.

Now, what you are looking for is the List<T> class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.

How to insert a data table into SQL Server database table?

From my understanding of the question,this can use a fairly straight forward solution.Anyway below is the method i propose ,this method takes in a data table and then using SQL statements to insert into a table in the database.Please mind that my solution is using MySQLConnection and MySqlCommand replace it with SqlConnection and SqlCommand.

public void InsertTableIntoDB_CreditLimitSimple(System.Data.DataTable tblFormat)
    {
        for (int i = 0; i < tblFormat.Rows.Count; i++)
        {

            String InsertQuery = string.Empty;

            InsertQuery = "INSERT INTO customercredit " +
                          "(ACCOUNT_CODE,NAME,CURRENCY,CREDIT_LIMIT) " +
                          "VALUES ('" + tblFormat.Rows[i]["AccountCode"].ToString() + "','" + tblFormat.Rows[i]["Name"].ToString() + "','" + tblFormat.Rows[i]["Currency"].ToString() + "','" + tblFormat.Rows[i]["CreditLimit"].ToString() + "')";



            using (MySqlConnection destinationConnection = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
            using (var dbcm = new MySqlCommand(InsertQuery, destinationConnection))
            {
                destinationConnection.Open();
                dbcm.ExecuteNonQuery();
            }
        }
    }//CreditLimit

'module' object has no attribute 'DataFrame'

There may be two causes:

  1. It is case-sensitive: DataFrame .... Dataframe, dataframe will not work.

  2. You have not install pandas (pip install pandas) in the python path.

Where does Android emulator store SQLite database?

Since the question is not restricted to Android Studio, So I am giving the path for Visual Studio 2015 (worked for Xamarin).

Tools-Android-Android Device Monitor

enter image description here

  • Locate the database file mentioned in above image, and click on Pull button as it shown in image 2.
  • Save the file in your desired location.
  • You can open that file using SQLite Studio or DB Browser for SQLite.

Special Thanks to other answerers of this question.

How to convert a byte array to its numeric value (Java)?

public static long byteArrayToLong(byte[] bytes) {
    return ((long) (bytes[0]) << 56)
            + (((long) bytes[1] & 0xFF) << 48)
            + ((long) (bytes[2] & 0xFF) << 40)
            + ((long) (bytes[3] & 0xFF) << 32)
            + ((long) (bytes[4] & 0xFF) << 24)
            + ((bytes[5] & 0xFF) << 16)
            + ((bytes[6] & 0xFF) << 8)
            + (bytes[7] & 0xFF);
}

convert bytes array (long is 8 bytes) to long

How does HttpContext.Current.User.Identity.Name know which usernames exist?

The HttpContext.Current.User.Identity.Name returns null

This depends on whether the authentication mode is set to Forms or Windows in your web.config file.

For example, if I write the authentication like this:

<authentication mode="Forms"/>

Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:

<authentication mode="Windows"/>

I can run the application again and check for the username, and I will get the username successfully.

For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.

Preferred way of loading resources in Java

Well, it partly depends what you want to happen if you're actually in a derived class.

For example, suppose SuperClass is in A.jar and SubClass is in B.jar, and you're executing code in an instance method declared in SuperClass but where this refers to an instance of SubClass. If you use this.getClass().getResource() it will look relative to SubClass, in B.jar. I suspect that's usually not what's required.

Personally I'd probably use Foo.class.getResourceAsStream(name) most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo, that's the most robust way of doing it IMO.

Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

during train test split you might have done a mistake

x_train,x_test,y_train,y_test=sklearn.model_selection.train_test_split(X,Y,test_size)

The above code is correct

You might have done like below which is wrong

x_train,y_train,x_test,y_test=sklearn.model_selection.train_test_split(X,Y,test_size)

How to get length of a list of lists in python

This saves the data in a list of lists.

text = open("filetest.txt", "r")
data = [ ]
for line in text:
    data.append( line.strip().split() )

print "number of lines ", len(data)
print "number of columns ", len(data[0])

print "element in first row column two ", data[0][1]

iOS: UIButton resize according to text length

To be honest I think that it's really shame that there is no simple checkbox in storyboard to say that you want to resize buttons to accommodate the text. Well... whatever.

Here is the simplest solution using storyboard.

  1. Place UIView and put constraints for it. Example: enter image description here
  2. Place UILabel inside UIView. Set constraints to attach it to edges of UIView.

  3. Place your UIButton inside UIView. Set the same constraints to attach it to the edges of UIView.

  4. Set 0 for UILabel's number of lines. enter image description here

  5. Set up the outlets.

    @IBOutlet var button: UIButton!
    @IBOutlet var textOnTheButton: UILabel!
  1. Get some long, long, long title.

    let someTitle = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
  1. On viewDidLoad set the title both for UILabel and UIButton.

    override func viewDidLoad() {
        super.viewDidLoad()
        textOnTheButton.text = someTitle
        button.setTitle(someTitle, for: .normal)
        button.titleLabel?.numberOfLines = 0
    }
  1. Run it to make sure that button is resized and can be pressed.

enter image description here

CSS vertical alignment text inside li

Define the parent with display: table and the element itself with vertical-align: middle and display: table-cell.

MySQL stored procedure vs function, which would I use when?

Stored procedure can be called recursively but stored function can not

Is it possible to overwrite a function in PHP

You could use the PECL extension

but that is bad practise in my opinion. You are using functions, but check out the Decorator design pattern. Can borrow the basic idea from it.

How can I find the link URL by link text with XPath?

Think of the phrase in the square brackets as a WHERE clause in SQL.

So this query says, "select the "href" attribute (@) of an "a" tag that appears anywhere (//), but only where (the bracketed phrase) the textual contents of the "a" tag is equal to 'programming questions site'".

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

You can also do this in the Visual Studio debugger without modifying the code.

  1. Create a breakpoint where you want to see the stack trace.
  2. Right-click the breakpoint and select "Actions..." in VS2015. In VS2010, select "When Hit...", then enable "Print a message".
  3. Make sure "Continue execution" is selected.
  4. Type in some text you would like to print out.
  5. Add $CALLSTACK wherever you want to see the stack trace.
  6. Run the program in the debugger.

Of course, this doesn't help if you're running the code on a different machine, but it can be quite handy to be able to spit out a stack trace automatically without affecting release code or without even needing to restart the program.

Duplicate keys in .NET dictionaries?

If you are using strings as both the keys and the values, you can use System.Collections.Specialized.NameValueCollection, which will return an array of string values via the GetValues(string key) method.

How to configure static content cache per folder and extension in IIS7?

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

Split a large dataframe into a list of data frames based on common value in column

From version 0.8.0, dplyr offers a handy function called group_split():

# On sample data from @Aus_10

df %>%
  group_split(g)

[[1]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     2.04      0.627 A    
 2     0.530    -0.703 A    
 3    -0.475     0.541 A    
 4     1.20     -0.565 A    
 5    -0.380    -0.126 A    
 6     1.25     -1.69  A    
 7    -0.153    -1.02  A    
 8     1.52     -0.520 A    
 9     0.905    -0.976 A    
10     0.517    -0.535 A    
# … with 15 more rows

[[2]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     1.61      0.858 B    
 2     1.05     -1.25  B    
 3    -0.440    -0.506 B    
 4    -1.17      1.81  B    
 5     1.47     -1.60  B    
 6    -0.682    -0.726 B    
 7    -2.21      0.282 B    
 8    -0.499     0.591 B    
 9     0.711    -1.21  B    
10     0.705     0.960 B    
# … with 15 more rows

To not include the grouping column:

df %>%
 group_split(g, keep = FALSE)

notifyDataSetChanged example

For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.

When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.

Your choices are:

  1. Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
  2. Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
  3. Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
  4. Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.

Understanding implicit in Scala

I had the exact same question as you had and I think I should share how I started to understand it by a few really simple examples (note that it only covers the common use cases).

There are two common use cases in Scala using implicit.

  • Using it on a variable
  • Using it on a function

Examples are as follows

Using it on a variable. As you can see, if the implicit keyword is used in the last parameter list, then the closest variable will be used.

// Here I define a class and initiated an instance of this class
case class Person(val name: String)
val charles: Person = Person("Charles")

// Here I define a function
def greeting(words: String)(implicit person: Person) = person match {
  case Person(name: String) if name != "" => s"$name, $words"
    case _ => "$words"
}

greeting("Good morning") // Charles, Good moring

val charles: Person = Person("")
greeting("Good morning") // Good moring

Using it on a function. As you can see, if the implicit is used on the function, then the closest type conversion method will be used.

val num = 10 // num: Int (of course)

// Here I define a implicit function
implicit def intToString(num: Int) = s"$num -- I am a String now!"

val num = 10 // num: Int (of course). Nothing happens yet.. Compiler believes you want 10 to be an Int

// Util...
val num: String = 10 // Compiler trust you first, and it thinks you have `implicitly` told it that you had a way to covert the type from Int to String, which the function `intToString` can do!
// So num is now actually "10 -- I am a String now!"
// console will print this -> val num: String = 10 -- I am a String now!

Hope this can help.

How to set background color of view transparent in React Native

Surprisingly no one told about this, which provides some !clarity:

style={{
backgroundColor: 'white',
opacity: 0.7
}}

How to retrieve field names from temporary table (SQL Server 2008)

select * 
from tempdb.INFORMATION_SCHEMA.COLUMNS
where table_name like '#MyTempTable%'

With MySQL, how can I generate a column containing the record index in a table?

I found the original answer incredibly helpful but I also wanted to grab a certain set of rows based on the row numbers I was inserting. As such, I wrapped the entire original answer in a subquery so that I could reference the row number I was inserting.

SELECT * FROM 
( 
    SELECT *, @curRow := @curRow + 1 AS "row_number"
    FROM db.tableName, (SELECT @curRow := 0) r
) as temp
WHERE temp.row_number BETWEEN 1 and 10;

Having a subquery in a subquery is not very efficient, so it would be worth testing whether you get a better result by having your SQL server handle this query, or fetching the entire table and having the application/web server manipulate the rows after the fact.

Personally my SQL server isn't overly busy, so having it handle the nested subqueries was preferable.

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

Fastest way to convert JavaScript NodeList to Array?

Here's a new cool way to do it using the ES6 spread operator:

let arr = [...nl];

Python's "in" set operator

Yes, but it also means hash(b) == hash(x), so equality of the items isn't enough to make them the same.

How to use goto statement correctly

The Java keyword list specifies the goto keyword, but it is marked as "not used".

This was probably done in case it were to be added to a later version of Java.

If goto weren't on the list, and it were added to the language later on, existing code that used the word goto as an identifier (variable name, method name, etcetera) would break. But because goto is a keyword, such code will not even compile in the present, and it remains possible to make it actually do something later on, without breaking existing code.

How to set variable from a SQL query?

There are three approaches:

  1. DECLARE
  2. SET -- Microsoft Recommended approach
  3. SELECT

Below query details the advantage and disadvantage of each:

-- First way, 
DECLARE @test int = (SELECT 1)
       , @test2 int = (SELECT a from (values (1),(2)) t(a)) -- throws error

-- advantage: declare and set in the same place
-- Disadvantage: can be used only during declaration. cannot be used later

-- Second way
DECLARE @test int  
       , @test2 int 

SET @test = (select 1)
SET @test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error

-- Advantage: ANSI standard. 
-- Disadvantage: cannot set more than one variable at a time

-- Third way
DECLARE @test int, @test2 int 
SELECT @test = (select 1)
      ,@test2 = (SELECT a from (values (1),(2)) t(a)) -- throws error

-- Advantage: Can set more than one variable at a time
-- Disadvantage: Not ANSI standard

Excel Define a range based on a cell value

Old post but this is exactly what I needed, simple question, how to change it to count column rather than Row. Thankyou in advance. Novice to Excel.

=SUM(A1:INDIRECT(CONCATENATE("A",C5)))

I.e My data is A1 B1 C1 D1 etc rather then A1 A2 A3 A4.

How to exit when back button is pressed?

First of all, Android does not recommend you to do that within the back button, but rather using the lifecycle methods provided. The back button should not destroy the Activity.

Activities are being added to the stack, accessible from the Overview (square button since they introduced the Material design in 5.0) when the back button is pressed on the last remaining Activity from the UI stack. If the user wants to close down your app, they should swipe it off (close it) from the Overview menu.

Your app is responsible to stop any background tasks and jobs you don't want to run, on onPause(), onStop() and onDestroy() lifecycle methods. Please read more about the lifecycles and their proper implementation here: http://developer.android.com/training/basics/activity-lifecycle/stopping.html

But to answer your question, you can do hacks to implement the exact behaviour you want, but as I said, it is not recommended:

@Override
 public void onBackPressed() {

// make sure you have this outcommented
// super.onBackPressed();
 Intent intent = new Intent(Intent.ACTION_MAIN);
 intent.addCategory(Intent.CATEGORY_HOME);
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 startActivity(intent);
}

How to write a caption under an image?

Put the image — let's say it's width is 140px — inside of a link:

<a><img src='image link' style='width: 140px'></a>

Next, put the caption in a and give it a width less than your image, while centering it:

<a>
  <img src='image link' style='width: 140px'>
  <div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>

Next, in the link tag, style the link so that it no longer looks like a link. You can give it any color you want, but just remove any text decoration your links may carry.

<a style='text-decoration: none; color: orange;'>
  <img src='image link' style='width: 140px'>
  <div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>

I wrapped the image with it's caption in a link so that no text could push the caption out of the way: The caption is tied to the picture by the link. Here's an example: http://www.alphaeducational.com/p/okay.html

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

What does "connection reset by peer" mean?

It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

Switching the order of block elements with CSS

I managed to do it with CSS display: table-*. I haven't tested with more than 3 blocks though.

fiddle

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

I had a similar problem when posting to the WebAPI endpoint. By turning the CustomErrors=Off, i was able to see the actual error which is one of the dlls was missing.

GCM with PHP (Google Cloud Messaging)

Here's a library I forked from CodeMonkeysRU.

The reason I forked was because Google requires exponential backoff. I use a redis server to queue messages and resend after a set time.

I've also updated it to support iOS.

https://github.com/stevetauber/php-gcm-queue

Compare two DataFrames and output their differences side-by-side

pandas >= 1.1: DataFrame.compare

With pandas 1.1, you could essentially replicate Ted Petrou's output with a single function call. Example taken from the docs:

pd.__version__
# '1.1.0'

df1.compare(df2)

  score       isEnrolled       Comment             
   self other       self other    self        other
1  1.11  1.21        NaN   NaN     NaN          NaN
2   NaN   NaN        1.0   0.0     NaN  On vacation

Here, "self" refers to the LHS dataFrame, while "other" is the RHS DataFrame. By default, equal values are replaced with NaNs so you can focus on just the diffs. If you want to show values that are equal as well, use

df1.compare(df2, keep_equal=True, keep_shape=True) 

  score       isEnrolled           Comment             
   self other       self  other       self        other
1  1.11  1.21      False  False  Graduated    Graduated
2  4.12  4.12       True  False        NaN  On vacation

You can also change the axis of comparison using align_axis:

df1.compare(df2, align_axis='index')

         score  isEnrolled      Comment
1 self    1.11         NaN          NaN
  other   1.21         NaN          NaN
2 self     NaN         1.0          NaN
  other    NaN         0.0  On vacation

This compares values row-wise, instead of column-wise.

Testing if a site is vulnerable to Sql Injection

The easiest way to protect yourself is to use stored procedures instead of inline SQL statements.

Then use "least privilege" permissions and only allow access to stored procedures and not directly to tables.

How to handle notification when app in background in Firebase

Since the display-messages which are sent from Firebase Notification UI only works if your app is in foreground. For data-messages, there is a need to make a POST call to FCM

Steps

  1. Install Advanced Rest Client Google Chrome Extension enter image description here

  2. Add the following headers

    Key: Content-Type, Value: application/json

    Key: Authorization, Value: key="your server key" enter image description here

  3. Add the body

    • If using topics :

      {
          "to" : "/topics/topic_name",
          "data": {
          "key1" : "value1",
          "key2" : "value2",
          }
      }
      
    • If using registration id :

      {
          "registration_ids" : "[{"id"},{id1}]",
          "data": {
          "key1" : "value1",
          "key2" : "value2",
           }
      }
      

Thats it!. Now listen to onMessageReceived callback as usual.

@Override
public void onMessageReceived(RemoteMessage remoteMessage) { 
     Map<String, String> data = remoteMessage.getData();
     String value1 = data.get("key1");
     String value2 = data.get("key2");
}

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

Sum columns with null values in oracle

In some cases, nvl(sum(column_name),0) is also required. You may want to consider your scenarios.

For example, I am trying to fetch the sum of a particular column, from a particular table based on certain conditions. Based on the conditions,

  1. one or more rows exist in the table. In this case I want the sum.
  2. rows do not exist. In this case I want 0.

If you use sum(nvl(column_name,0)) here, it would give you null. What you might want is nvl(sum(column_name),0).

This may be required especially when you are passing this result to, say, java, have the datatype as number there because then this will not require special null handling.

scp files from local to remote machine error: no such file or directory

Be sure the folder from where you send the file does not contain space !

I was trying to send a file to a remote server from my windows machine from VS code terminal, and I got this error even if the file was here.

It's because the folder where the file was contained space in its name...

Setting a windows batch file variable to the day of the week

%DATE% is not your friend. Because the %DATE% environment variable (and the DATE command) returns the current date using the Windows short date format that is fully and endlessly customizable. One user may configure the system to return 07/06/2012 while another might choose Fri060712. Using %DATE% is a complete nightmare for a BAT programmer.

There are two possible approaches to solve this problem:

  1. You may be tempted to temporarily change the short date format, by changing the locale settings in the registry value HKCU\Control Panel\International\sShortDate, to your recognizable format. Then access %DATE% to get the date in the format you want; and finally restore the format back to the original user format. Something like this

    reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f >nul
    reg add "HKCU\Control Panel\International" /v sShortDate /d "ddd" /f >nul
    set DOW=%DATE%
    reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f >nul
    

    but this method has two problems:

    • it tampers with a global registry value for its local particular purpouses, so it may interfere with other processes or user tasks that at the very same time query the date in short date format, including itself if run simultaneously.

    • and it returns the three letter day of the week in the local language that may be different in different systems or different users.

  2. use WMIC Win32_LocalTime, that returns the date in a convenient way to directly parse it with a FOR command.

    FOR /F "skip=1" %%A IN ('WMIC Path Win32_LocalTime Get DayOfWeek' ) DO (
      set DOW=%%A
    )
    

    this is the method I recommend.

How to enable C++11 in Qt Creator?

Add this to your .pro file

QMAKE_CXXFLAGS += -std=c++11

or

CONFIG += c++11

How to get the path of current worksheet in VBA?

Always nice to have:

Dim myPath As String     
Dim folderPath As String 

folderPath = Application.ActiveWorkbook.Path    
myPath = Application.ActiveWorkbook.FullName

Django URL Redirect

In Django 1.8, this is how I did mine.

from django.views.generic.base import RedirectView

url(r'^$', views.comingSoon, name='homepage'),
# whatever urls you might have in here
# make sure the 'catch-all' url is placed last
url(r'^.*$', RedirectView.as_view(pattern_name='homepage', permanent=False))

Instead of using url, you can use the pattern_name, which is a bit un-DRY, and will ensure you change your url, you don't have to change the redirect too.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

To get past INSTALL_FAILED_MISSING_SHARED_LIBRARY error with Google Maps for Android:

  1. Install Google map APIs. This can be done in Eclipse Windows/Android SDK and AVD Manager -> Available Packages -> Third Party Add-ons -> Google Inc. -> Google APIs by Google Inc., Android API X

  2. From command line create new AVD. This can be done by listing targets (android list targets), then android create avd -n new_avd_api_233 -t "Google Inc.:Google APIs:X"

  3. Then create AVD (Android Virtual Device) in Eclipse Windows/Android SDK and AVD Manager -> New... -> (Name: new_avd_X, Target: Google APIs (Google Inc.) - API Level X)

    IMPORTANT : You must create your AVD with Target as Google APIs (Google Inc.) otherwise it will again failed.

  4. Create Android Project in Eclipse File/New/Android Project and select Google APIs Build Target.

  5. add <uses-library android:name="com.google.android.maps" /> between <application> </application> tags.

  6. Run Project as Android Application.

If error persists, then you still have problems, if it works, then this error is forever behind you.

Angularjs on page load call function

<section ng-controller="testController as ctrl" class="test_cls"  data-ng-init="fn_load()">

$scope.fn_load = function () {
  console.log("page load")
};

Find a value in an array of objects in Javascript

function getValue(){
    for(var i = 0 ; i< array.length; i++){
        var obj = array[i];
        var arr = array["types"];
        for(var j = 0; j<arr.length;j++ ){
            if(arr[j] == "value"){
                return obj;
            }
        }

    }
}

How do you run a single test/spec file in RSpec?

Although many great answers were written to this question, none of them uses the Rspec tags approach.

I use tags to run one or more specs in different files -- only those related to my current development task.

For example, I add the tag "dev" with the value "current":

it "creates an user", dev: :current do
  user = create(:user)
  expect(user.persisted?).to be_truthy
end

then I run

bundle exec rspec . --tag dev:current

Different tags/values can be set in individual specs or groups.

How to place object files in separate subdirectory

You can specify the -o $@ option to your compile command to force the output of the compile command to take on the name of the target. For example, if you have:

  • sources: cpp/class.cpp and cpp/driver.cpp
  • headers: headers/class.h

...and you want to place the object files in:

  • objects: obj/class.o obj/driver.o

...then you can compile cpp/class.cpp and cpp/driver.cpp separately into obj/class.o and obj/driver.o, and then link, with the following Makefile:

CC=c++
FLAGS=-std=gnu++11

INCS=-I./headers
SRC=./cpp
OBJ=./obj
EXE=./exe

${OBJ}/class.o:    ${SRC}/class.cpp
                   ${CC} ${FLAGS} ${INCS} -c $< -o $@

${OBJ}/driver.o:    ${SRC}/driver.cpp ${SRC}/class.cpp
                    ${CC} ${FLAGS} ${INCS} -c $< -o $@

driver: ${OBJ}/driver.o ${OBJ}/class.o
        ${CC} ${FLAGS} ${OBJ}/driver.o ${OBJ}/class.o -o ${EXE}/driver

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

std::wstring VS std::string

A good question! I think DATA ENCODING (sometimes a CHARSET also involved) is a MEMORY EXPRESSION MECHANISM in order to save data to a file or transfer data via a network, so I answer this question as:

1. When should I use std::wstring over std::string?

If the programming platform or API function is a single-byte one, and we want to process or parse some Unicode data, e.g read from Windows'.REG file or network 2-byte stream, we should declare std::wstring variable to easily process them. e.g.: wstring ws=L"??a"(6 octets memory: 0x4E2D 0x56FD 0x0061), we can use ws[0] to get character '?' and ws[1] to get character '?' and ws[2] to get character 'a', etc.

2. Can std::string hold the entire ASCII character set, including the special characters?

Yes. But notice: American ASCII, means each 0x00~0xFF octet stands for one character, including printable text such as "123abc&*_&" and you said special one, mostly print it as a '.' avoid confusing editors or terminals. And some other countries extend their own "ASCII" charset, e.g. Chinese, use 2 octets to stand for one character.

3.Is std::wstring supported by all popular C++ compilers?

Maybe, or mostly. I have used: VC++6 and GCC 3.3, YES

4. What is exactly a "wide character"?

a wide character mostly indicates using 2 octets or 4 octets to hold all countries' characters. 2 octet UCS2 is a representative sample, and further e.g. English 'a', its memory is 2 octet of 0x0061(vs in ASCII 'a's memory is 1 octet 0x61)

Custom checkbox image android

If you have Android open source code, you can find the styles definition under:
src/frameworks/base/core/res/res/values

<style name="Widget.CompoundButton.CheckBox">
    <item name="android:background">
        @android:drawable/btn_check_label_background
    </item>
    <item name="android:button">
        ?android:attr/listChoiceIndicatorMultiple
    </item>
</style>

Javascript: Load an Image from url and display

When the button is clicked, get the value of the input and use it to create an image element which is appended to the body (or anywhere else) :

<html>
<body>
<form>
    <input type="text" id="imagename" value="" />
    <input type="button" id="btn" value="GO" />
</form>
    <script type="text/javascript">
        document.getElementById('btn').onclick = function() {
            var val = document.getElementById('imagename').value,
                src = 'http://webpage.com/images/' + val +'.png',
                img = document.createElement('img');

            img.src = src;
            document.body.appendChild(img);
        }
    </script>
</body>
</html>

FIDDLE

the same in jQuery:

$('#btn').on('click', function() {
    var img = $('<img />', {src : 'http://webpage.com/images/' + $('#imagename').val() +'.png'});
    img.appendTo('body');
});

Locate current file in IntelliJ

I am using IntelliJ IDEA 2016.2 Ultimate.

Alt+F1, then press 1

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can set environment variables in the notebook using os.environ. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"

You can double check that you have the correct devices visible to TF

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

I tend to use it from utility module like notebook_util

import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf

Export HTML table to pdf using jspdf

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Is it "safe" to use $_SERVER['HTTP_HOST'] for all links on a site without having to worry about XSS attacks, even when used in forms?

Yes, it's safe to use $_SERVER['HTTP_HOST'], (and even $_GET and $_POST) as long as you verify them before accepting them. This is what I do for secure production servers:

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
$reject_request = true;
if(array_key_exists('HTTP_HOST', $_SERVER)){
    $host_name = $_SERVER['HTTP_HOST'];
    // [ need to cater for `host:port` since some "buggy" SAPI(s) have been known to return the port too, see http://goo.gl/bFrbCO
    $strpos = strpos($host_name, ':');
    if($strpos !== false){
        $host_name = substr($host_name, $strpos);
    }
    // ]
    // [ for dynamic verification, replace this chunk with db/file/curl queries
    $reject_request = !array_key_exists($host_name, array(
        'a.com' => null,
        'a.a.com' => null,
        'b.com' => null,
        'b.b.com' => null
    ));
    // ]
}
if($reject_request){
    // log errors
    // display errors (optional)
    exit;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
echo 'Hello World!';
// ...

The advantage of $_SERVER['HTTP_HOST'] is that its behavior is more well-defined than $_SERVER['SERVER_NAME']. Contrast ??:

Contents of the Host: header from the current request, if there is one.

with:

The name of the server host under which the current script is executing.

Using a better defined interface like $_SERVER['HTTP_HOST'] means that more SAPIs will implement it using reliable well-defined behavior. (Unlike the other.) However, it is still totally SAPI dependent ??:

There is no guarantee that every web server will provide any of these [$_SERVER entries]; servers may omit some, or provide others not listed here.

To understand how to properly retrieve the host name, first and foremost you need to understand that a server which contains only code has no means of knowing (pre-requisite for verifying) its own name on the network. It needs to interface with a component that supplies it its own name. This can be done via:

  • local config file

  • local database

  • hardcoded source code

  • external request (curl)

  • client/attacker's Host: request

  • etc

Usually its done via the local (SAPI) config file. Note that you have configured it correctly, e.g. in Apache ??:

A couple of things need to be 'faked' to make the dynamic virtual host look like a normal one.

The most important is the server name which is used by Apache to generate self-referential URLs, etc. It is configured with the ServerName directive, and it is available to CGIs via the SERVER_NAME environment variable.

The actual value used at run time is controlled by the UseCanonicalName setting.

With UseCanonicalName Off the server name comes from the contents of the Host: header in the request. With UseCanonicalName DNS it comes from a reverse DNS lookup of the virtual host's IP address. The former setting is used for name-based dynamic virtual hosting, and the latter is used for** IP-based hosting.

If Apache cannot work out the server name because there is no Host: header or the DNS lookup fails then the value configured with ServerName is used instead.

How to convert string values from a dictionary, into int/float datatypes?

for sub in the_list:
    for key in sub:
        sub[key] = int(sub[key])

Gives it a casting as an int instead of as a string.

How to check the first character in a string in Bash or UNIX shell?

Many ways to do this. You could use wildcards in double brackets:

str="/some/directory/file"
if [[ $str == /* ]]; then echo 1; else echo 0; fi

You can use substring expansion:

if [[ ${str:0:1} == "/" ]] ; then echo 1; else echo 0; fi

Or a regex:

if [[ $str =~ ^/ ]]; then echo 1; else echo 0; fi

How to convert comma-separated String to List?

Arrays.asList returns a fixed-size List backed by the array. If you want a normal mutable java.util.ArrayList you need to do this:

List<String> list = new ArrayList<String>(Arrays.asList(string.split(" , ")));

Or, using Guava:

List<String> list = Lists.newArrayList(Splitter.on(" , ").split(string));

Using a Splitter gives you more flexibility in how you split the string and gives you the ability to, for example, skip empty strings in the results and trim results. It also has less weird behavior than String.split as well as not requiring you to split by regex (that's just one option).

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

How to compute the similarity between two text documents?

I am combining the solutions from answers of @FredFoo and @Renaud. My solution is able to apply @Renaud's preprocessing on the text corpus of @FredFoo and then display pairwise similarities where the similarity is greater than 0. I ran this code on Windows by installing python and pip first. pip is installed as part of python but you may have to explicitly do it by re-running the installation package, choosing modify and then choosing pip. I use the command line to execute my python code saved in a file "similarity.py". I had to execute the following commands:

>set PYTHONPATH=%PYTHONPATH%;C:\_location_of_python_lib_
>python -m pip install sklearn
>python -m pip install nltk
>py similarity.py

The code for similarity.py is as follows:

from sklearn.feature_extraction.text import TfidfVectorizer
import nltk, string
import numpy as np
nltk.download('punkt') # if necessary...

stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)

def stem_tokens(tokens):
    return [stemmer.stem(item) for item in tokens]

def normalize(text):
    return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))

corpus = ["I'd like an apple", 
           "An apple a day keeps the doctor away", 
           "Never compare an apple to an orange", 
           "I prefer scikit-learn to Orange", 
           "The scikit-learn docs are Orange and Blue"]  

vect = TfidfVectorizer(tokenizer=normalize, stop_words='english')
tfidf = vect.fit_transform(corpus)   
                                                                                                                                                                                                                    
pairwise_similarity = tfidf * tfidf.T

#view the pairwise similarities 
print(pairwise_similarity)

#check how a string is normalized
print(normalize("The scikit-learn docs are Orange and Blue"))

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

select2 changing items dynamically

I'm successfully using the following to update options dynamically:

$control.select2('destroy').empty().select2({data: [{id: 1, text: 'new text'}]});

Inserting multiple rows in a single SQL query?

NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.

You can use INSERT with SELECT UNION ALL:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

Only for small datasets though, which should be fine for your 4 records.

Android activity life cycle - what are all these methods for?

From the Android Developers page,

onPause():

Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.

onStop():

Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.

Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.

The paused Activity gets a Resume and Stopped gets Restarted.

When you call this.finish(), onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.

I hope it's clear enough.

Error inflating class android.support.design.widget.NavigationView

This error can be caused due to reasons as mentioned below.

  1. This problem will likely occur when the version of your appcompat library and design support library doesn't match. Example of matching condition

     compile 'com.android.support:appcompat-v7:24.2.0' // appcompat library
    
     compile 'com.android.support:design:24.2.0' //design support library
    
  2. If your theme file in styles have only these two,

     <item name="colorPrimary">#4A0958</item>
     <item name="colorPrimaryDark">#4A0958</item>
    

then add ColorAccent too. It should look somewhat like this.

 <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">

  <item name="colorPrimary">#4A0958</item>
  <item name="colorPrimaryDark">#4A0958</item>
  <item name="colorAccent">#4A0958</item>

 </style>

Get a list of checked checkboxes in a div using jQuery

 var agencias = [];
 $('#Div input:checked').each(function(index, item){
 agencias.push(item.nextElementSibling.attributes.for.nodeValue);
 });

How can I test if a letter in a string is uppercase or lowercase using JavaScript?

This is straightforward, readable solution using a simple regex.

// Get specific char in string
const char = string.charAt(index);

const isLowerCaseLetter = (/[a-z]/.test(char));
const isUpperCaseLetter = (/[A-Z]/.test(char));

Java 8 optional: ifPresent return object orElseThrow exception

I'd prefer mapping after making sure the value is available

private String getStringIfObjectIsPresent(Optional<Object> object) {
   Object ob = object.orElseThrow(MyCustomException::new);
    // do your mapping with ob
   String result = your-map-function(ob);
  return result;
}

or one liner

private String getStringIfObjectIsPresent(Optional<Object> object) {
   return your-map-function(object.orElseThrow(MyCustomException::new));
}

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

  1. Anything but ECB.
  2. If using CTR, it is imperative that you use a different IV for each message, otherwise you end up with the attacker being able to take two ciphertexts and deriving a combined unencrypted plaintext. The reason is that CTR mode essentially turns a block cipher into a stream cipher, and the first rule of stream ciphers is to never use the same Key+IV twice.
  3. There really isn't much difference in how difficult the modes are to implement. Some modes only require the block cipher to operate in the encrypting direction. However, most block ciphers, including AES, don't take much more code to implement decryption.
  4. For all cipher modes, it is important to use different IVs for each message if your messages could be identical in the first several bytes, and you don't want an attacker knowing this.

AngularJS - Trigger when radio button is selected

i prefer to use ng-value with ng-if, [ng-value] will handle trigger changes

<input type="radio"  name="isStudent" ng-model="isStudent" ng-value="true" />

//to show and hide input by removing it from the DOM, that's make me secure from malicious data

<input type="text" ng-if="isStudent"  name="textForStudent" ng-model="job">

Fetch API with Cookie

In addition to @Khanetor's answer, for those who are working with cross-origin requests: credentials: 'include'

Sample JSON fetch request:

fetch(url, {
  method: 'GET',
  credentials: 'include'
})
  .then((response) => response.json())
  .then((json) => {
    console.log('Gotcha');
  }).catch((err) => {
    console.log(err);
});

https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

What is the best way to concatenate two vectors?

In the direction of Bradgonesurfing's answer, many times one doesn't really need to concatenate two vectors (O(n)), but instead just work with them as if they were concatenated (O(1)). If this is your case, it can be done without the need of Boost libraries.

The trick is to create a vector proxy: a wrapper class which manipulates references to both vectors, externally seen as a single, contiguous one.

USAGE

std::vector<int> A{ 1, 2, 3, 4, 5};
std::vector<int> B{ 10, 20, 30 };

VecProxy<int> AB(A, B);  // ----> O(1). No copies performed.

for (size_t i = 0; i < AB.size(); ++i)
    std::cout << AB[i] << " ";  // 1 2 3 4 5 10 20 30

IMPLEMENTATION

template <class T>
class VecProxy {
private:
    std::vector<T>& v1, v2;
public:
    VecProxy(std::vector<T>& ref1, std::vector<T>& ref2) : v1(ref1), v2(ref2) {}
    const T& operator[](const size_t& i) const;
    const size_t size() const;
};

template <class T>
const T& VecProxy<T>::operator[](const size_t& i) const{
    return (i < v1.size()) ? v1[i] : v2[i - v1.size()];
};

template <class T>
const size_t VecProxy<T>::size() const { return v1.size() + v2.size(); };

MAIN BENEFIT

It's O(1) (constant time) to create it, and with minimal extra memory allocation.

SOME STUFF TO CONSIDER

  • You should only go for it if you really know what you're doing when dealing with references. This solution is intended for the specific purpose of the question made, for which it works pretty well. To employ it in any other context may lead to unexpected behavior if you are not sure on how references work.
  • In this example, AB does not provide a non-const access operator ([ ]). Feel free to include it, but keep in mind: since AB contains references, to assign it values will also affect the original elements within A and/or B. Whether or not this is a desirable feature, it's an application-specific question one should carefully consider.
  • Any changes directly made to either A or B (like assigning values, sorting, etc.) will also "modify" AB. This is not necessarily bad (actually, it can be very handy: AB does never need to be explicitly updated to keep itself synchronized to both A and B), but it's certainly a behavior one must be aware of. Important exception: to resize A and/or B to sth bigger may lead these to be reallocated in memory (for the need of contiguous space), and this would in turn invalidate AB.
  • Because every access to an element is preceded by a test (namely, "i < v1.size()"), VecProxy access time, although constant, is also a bit slower than that of vectors.
  • This approach can be generalized to n vectors. I haven't tried, but it shouldn't be a big deal.

How to create a sticky footer that plays well with Bootstrap 3

What worked for me was adding the position relative to the html tag.

html {
  min-height:100%;
  position:relative;
}
body {
  margin-bottom:60px;
}
footer {
  position:absolute;
  bottom:0;
  height:60px;
}

REST, HTTP DELETE and parameters

I think this is non-restful. I do not think the restful service should handle the requirement of forcing the user to confirm a delete. I would handle this in the UI.

Does specifying force_delete=true make sense if this were a program's API? If someone was writing a script to delete this resource, would you want to force them to specify force_delete=true to actually delete the resource?

How do I remove the space between inline/inline-block elements?

Unfortunately, it is 2019 and white-space-collapse is still not implemented.

In the meantime, give the parent element font-size: 0; and set the font-size on the children. This should do the trick

Else clause on Python while statement

As far as I know the main reason for adding else to loops in any language is in cases when the iterator is not on in your control. Imagine the iterator is on a server and you just give it a signal to fetch the next 100 records of data. You want the loop to go on as long as the length of the data received is 100. If it is less, you need it to go one more times and then end it. There are many other situations where you have no control over the last iteration. Having the option to add an else in these cases makes everything much easier.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

You have to dispatch after the async request ends.

This would work:

export function bindComments(postId) {
    return function(dispatch) {
        return API.fetchComments(postId).then(comments => {
            // dispatch
            dispatch({
                type: BIND_COMMENTS,
                comments,
                postId
            });
        });
    };
}

Declaring a custom android UI element using XML

The Android Developer Guide has a section called Building Custom Components. Unfortunately, the discussion of XML attributes only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:

1. Declare attributes in values\attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="android:text"/>
        <attr name="android:textColor"/>            
        <attr name="extraInformation" format="string" />
    </declare-styleable>
</resources>

Notice the use of an unqualified name in the declare-styleable tag. Non-standard android attributes like extraInformation need to have their type declared. Tags declared in the superclass will be available in subclasses without having to be redeclared.

2. Create constructors

Since there are two constructors that use an AttributeSet for initialisation, it is convenient to create a separate initialisation method for the constructors to call.

private void init(AttributeSet attrs) { 
    TypedArray a=getContext().obtainStyledAttributes(
         attrs,
         R.styleable.MyCustomView);

    //Use a
    Log.i("test",a.getString(
         R.styleable.MyCustomView_android_text));
    Log.i("test",""+a.getColor(
         R.styleable.MyCustomView_android_textColor, Color.BLACK));
    Log.i("test",a.getString(
         R.styleable.MyCustomView_extraInformation));

    //Don't forget this
    a.recycle();
}

R.styleable.MyCustomView is an autogenerated int[] resource where each element is the ID of an attribute. Attributes are generated for each property in the XML by appending the attribute name to the element name. For example, R.styleable.MyCustomView_android_text contains the android_text attribute for MyCustomView. Attributes can then be retrieved from the TypedArray using various get functions. If the attribute is not defined in the defined in the XML, then null is returned. Except, of course, if the return type is a primitive, in which case the second argument is returned.

If you don't want to retrieve all of the attributes, it is possible to create this array manually.The ID for standard android attributes are included in android.R.attr, while attributes for this project are in R.attr.

int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};

Please note that you should not use anything in android.R.styleable, as per this thread it may change in the future. It is still in the documentation as being to view all these constants in the one place is useful.

3. Use it in a layout files such as layout\main.xml

Include the namespace declaration xmlns:app="http://schemas.android.com/apk/res-auto" in the top level xml element. Namespaces provide a method to avoid the conflicts that sometimes occur when different schemas use the same element names (see this article for more info). The URL is simply a manner of uniquely identifying schemas - nothing actually needs to be hosted at that URL. If this doesn't appear to be doing anything, it is because you don't actually need to add the namespace prefix unless you need to resolve a conflict.

<com.mycompany.projectname.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:text="Test text"
    android:textColor="#FFFFFF"
    app:extraInformation="My extra information"
/> 

Reference the custom view using the fully qualified name.

Android LabelView Sample

If you want a complete example, look at the android label view sample.

LabelView.java

 TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);
 CharSequences=a.getString(R.styleable.LabelView_text);

attrs.xml

<declare-styleable name="LabelView">
    <attr name="text"format="string"/>
    <attr name="textColor"format="color"/>
    <attr name="textSize"format="dimension"/>
</declare-styleable>

custom_view_1.xml

<com.example.android.apis.view.LabelView
    android:background="@drawable/blue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    app:text="Blue" app:textSize="20dp"/>

This is contained in a LinearLayout with a namespace attribute: xmlns:app="http://schemas.android.com/apk/res-auto"

Links

Convert pyQt UI to python

Update for anyone using PyQt5 with python 3.x:

  1. Open terminal (eg. Powershell, cmd etc.)
  2. cd into the folder with your .ui file.
  3. Type: "C:\python\Lib\site-packages\PyQt5\pyuic5.bat" -x Trial.ui -o trial_gui.py for cases where PyQt5 is not a path variable. The path in quotes " " represents where the pyuic5.bat file is.

This should work!

glob exclude pattern

How about skipping the particular file while iterating over all the files in the folder! Below code would skip all excel files that start with 'eph'

import glob
import re
for file in glob.glob('*.xlsx'):
    if re.match('eph.*\.xlsx',file):
        continue
    else:
        #do your stuff here
        print(file)

This way you can use more complex regex patterns to include/exclude a particular set of files in a folder.

Get screenshot on Windows with Python?

You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:

from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

Show dialog from fragment?

 public void showAlert(){


     AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
     LayoutInflater inflater = getActivity().getLayoutInflater();
     View alertDialogView = inflater.inflate(R.layout.test_dialog, null);
     alertDialog.setView(alertDialogView);

     TextView textDialog = (TextView) alertDialogView.findViewById(R.id.text_testDialogMsg);
     textDialog.setText(questionMissing);

     alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             dialog.cancel();
         }
     });
     alertDialog.show();

}

where .test_dialog is of xml custom

C#: How do you edit items and subitems in a listview?

If you're looking for "in-place" editing of a ListView's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.

By default, the best you can achieve with a "standard" ListView is to set it's LabelEdit property to true to allow the user to edit the text of the first column of the ListView (assuming you want to allow a free-format text edit).

Some examples (including full source-code) of customized ListView's that allow "in-place" editing of sub-items are:

C# Editable ListView
In-place editing of ListView subitems

Confused by python file mode "w+"

I suspect there are two ways to handle what I think you'r trying to achieve.

1) which is obvious, is open the file for reading only, read it into memory then open the file with t, then write your changes.

2) use the low level file handling routines:

# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
 fd = os.open(filename, os.O_RDWR | os.O_CREAT)

Hope this helps..

How to run Gradle from the command line on Mac bash

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

You can install gradle with homebrew with the following command:

$ brew install gradle

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

$ gradle test 

diff to output only the file names

You can also use rsync

rsync -rv --size-only --dry-run /my/source/ /my/dest/ > diff.out

Order of items in classes: Fields, Properties, Constructors, Methods

Usually I try to follow the next pattern:

  • static members (have usually an other context, must be thread-safe, etc.)
  • instance members

Each part (static and instance) consists of the following member types:

  • operators (are always static)
  • fields (initialized before constructors)
  • constructors
  • destructor (is a tradition to follow the constructors)
  • properties
  • methods
  • events

Then the members are sorted by visibility (from less to more visible):

  • private
  • internal
  • internal protected
  • protected
  • public

The order is not a dogma: simple classes are easier to read, however, more complex classes need context-specific grouping.

How to find the installed pandas version

Simplest Solution

Code:

import pandas as pd
pd.__version__

**Its double underscore before and after the word "version".

Output:

'0.14.1'

Which passwordchar shows a black dot (•) in a winforms textbox?

Below are some different ways to achieve this. Pick the one suits you

  1. In fonts like 'Tahoma' and 'Times new Roman' this common password character '?' which is called 'Black circle' has a unicode value 0x25CF. Set the PasswordChar property with either the value 0x25CF or copy paste the actual character itself.

  2. If you want to display the Black Circle by default then enable visual styles which should replace the default password character from '*' to '?' by default irrespective of the font.

  3. Another alternative is to use 'Wingdings 2' font on the TextBox and set the password character to 0x97. This should work even if the application is not unicoded. Refer to charMap.exe to get better idea on different fonts and characters supported.

Display current path in terminal only

If you just want to get the information of current directory, you can type:

pwd

and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.

Apply a theme to an activity in Android?

Before you call setContentView(), call setTheme(android.R.style...) and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).

Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)

Need to install urllib2 for Python 3.5.1

WARNING: Security researches have found several poisoned packages on PyPI, including a package named urllib, which will 'phone home' when installed. If you used pip install urllib some time after June 2017, remove that package as soon as possible.

You can't, and you don't need to.

urllib2 is the name of the library included in Python 2. You can use the urllib.request library included with Python 3, instead. The urllib.request library works the same way urllib2 works in Python 2. Because it is already included you don't need to install it.

If you are following a tutorial that tells you to use urllib2 then you'll find you'll run into more issues. Your tutorial was written for Python 2, not Python 3. Find a different tutorial, or install Python 2.7 and continue your tutorial on that version. You'll find urllib2 comes with that version.

Alternatively, install the requests library for a higher-level and easier to use API. It'll work on both Python 2 and 3.

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

For me, I had set my project to run on the latest version of .Net Framework (a change from .Net Framework 4.6.1 to 4.7.2).

Everything worked, no errors and published without issue, and it was only by chance that I came across the System.Net.Http error message, shown in a small, hard-to-notice, but quite important API request over the website I'm working on.

I rolled back to 4.6.1 and everything is fine again.

Add swipe to delete UITableViewCell

It's new feature in iOS11 and Swift 4.

Reference link :

Trailing Swipe :

@available(iOS 11.0, *)
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let delete = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
        print("index path of delete: \(indexPath)")
        completionHandler(true)
    }

    let rename = UIContextualAction(style: .normal, title: "Edit") { (action, sourceView, completionHandler) in
        print("index path of edit: \(indexPath)")
        completionHandler(true)
    }
    let swipeActionConfig = UISwipeActionsConfiguration(actions: [rename, delete])
    swipeActionConfig.performsFirstActionWithFullSwipe = false
    return swipeActionConfig
}

enter image description here

How to use Bootstrap 4 in ASP.NET Core

BS4 is now available on .NET Core 2.2. On the SDK 2.2.105 x64 installer for sure. I'm running Visual Studio 2017 with it. So far so good for new web application projects.

Get Current date in epoch from Unix shell script

The Unix Date command will display in epoch time

the command is

date +"%s"

https://linux.die.net/man/1/date

Edit: Some people have observed you asked for days, so it's the result of that command divided by 86,400

How can I convert a char to int in Java?

I you have the char '9', it will store its ASCII code, so to get the int value, you have 2 ways

char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10

And it fact, this works also :

char x = 9;
System.out.println(">" + x + "<");     //>  < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String, bu you can also use it as int as you see above

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

How to get highcharts dates in the x axis?

You write like this-:

xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: {
           day: '%d %b %Y'    //ex- 01 Jan 2016
        }
}

also check for other datetime format

http://api.highcharts.com/highcharts#xAxis.dateTimeLabelFormats

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

What is a classpath and how do I set it?

Setting the CLASSPATH System Variable

To display the current CLASSPATH variable, use these commands in Windows and UNIX (Bourne shell): In Windows: C:\> set CLASSPATH In UNIX: % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use these commands: In Windows: C:\> set CLASSPATH= In UNIX: % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable, use these commands (for example): In Windows: C:\> set CLASSPATH=C:\users\george\java\classes In UNIX: % CLASSPATH=/home/george/java/classes; export CLASSPATH

How to make a simple popup box in Visual C#?

System.Windows.Forms.MessageBox.Show("My message here");

Make sure the System.Windows.Forms assembly is referenced your project.

Split Div Into 2 Columns Using CSS

Divide a division in two columns is very easy, just specify the width of your column better if you put this (like width:50%) and set the float:left for left column and float:right for right column.

Can I set an opacity only to the background image of a div?

So here is an other way:

background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");

Property [title] does not exist on this collection instance

When you're using get() you get a collection. In this case you need to iterate over it to get properties:

@foreach ($collection as $object)
    {{ $object->title }}
@endforeach

Or you could just get one of objects by it's index:

{{ $collection[0]->title }}

Or get first object from collection:

{{ $collection->first() }}

When you're using find() or first() you get an object, so you can get properties with simple:

{{ $object->title }}

How to calculate difference in hours (decimal) between two dates in SQL Server?

DATEDIFF but note it returns an integer so if you need fractions of hours use something like this:-

CAST(DATEDIFF(ss, startDate, endDate) AS decimal(precision, scale)) / 3600

jQuery event handlers always execute in order they were bound - any way around this?

The standard principle is separate event handlers shouldn't depend upon the order they are called. If they do depend upon the order they should not be separate.

Otherwise, you register one event handler as being 'first' and someone else then registers their event handler as 'first' and you're back in the same mess as before.

What is a user agent stylesheet?

Some browsers use their own way to read .css files. So the right way to beat this: If you type the command line directly in the .html source code, this beats the .css file, in that way, you told the browser directly what to do and the browser is at position not to read the commands from the .css file. Remember that the commands writen in the .html file is stronger than the command in the .css.

How to create a POJO?

A POJO is just a plain, old Java Bean with the restrictions removed. Java Beans must meet the following requirements:

  1. Default no-arg constructor
  2. Follow the Bean convention of getFoo (or isFoo for booleans) and setFoo methods for a mutable attribute named foo; leave off the setFoo if foo is immutable.
  3. Must implement java.io.Serializable

POJO does not mandate any of these. It's just what the name says: an object that compiles under JDK can be considered a Plain Old Java Object. No app server, no base classes, no interfaces required to use.

The acronym POJO was a reaction against EJB 2.0, which required several interfaces, extended base classes, and lots of methods just to do simple things. Some people, Rod Johnson and Martin Fowler among them, rebelled against the complexity and sought a way to implement enterprise scale solutions without having to write EJBs.

Martin Fowler coined a new acronym.

Rod Johnson wrote "J2EE Without EJBs", wrote Spring, influenced EJB enough so version 3.1 looks a great deal like Spring and Hibernate, and got a sweet IPO from VMWare out of it.

Here's an example that you can wrap your head around:

public class MyFirstPojo
{
    private String name;

    public static void main(String [] args)
    {
       for (String arg : args)
       {
          MyFirstPojo pojo = new MyFirstPojo(arg);  // Here's how you create a POJO
          System.out.println(pojo); 
       }
    }

    public MyFirstPojo(String name)
    {    
        this.name = name;
    }

    public String getName() { return this.name; } 

    public String toString() { return this.name; } 
}

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

It if helps someone, ours was an issue with missing certificate. Environment is Windows Server 2016 Standard with .Net 4.6.

There is a self hosted WCF service https URI, for which Service.Open() would execute without errors. Another thread would keep accessing https://OurIp:443/OurService?wsdl to ensure that the service was available. Accessing the WSDL used to fail with:

The underlying connection was closed: An unexpected error occurred on a send.

Using ServicePointManager.SecurityProtocol with applicable settings did not work. Playing with server roles and features did not help either. Then stepped in Jaise George, the SE, resolving the issue in a couple of minutes. Jaise installed a self signed certificate in the IIS, poofing the issue. This is what he did to address the issue:

(1) Open IIS manager (inetmgr) (2) Click on the server node in the left panel, and double click "Server certificates". (3) Click on "Create Self-Signed Certificate" on the right panel and type in anything you want for the friendly name. (4) Click on “Default Web site” in the left panel, click "Bindings" on the right panel, click "Add", select "https", select the certificate you just created, and click "OK" (5) Access the https URL, it should be accessible.

Adding minutes to date time in PHP

$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);

result is

2011-11-17 05:21:00

Live demo is here

If you are no familiar with strtotime yet, you better head to php.net to discover it's great power :-)

Jquery checking success of ajax post

I was wondering, why they didnt provide in jquery itself, so i made a few changes in jquery file ,,, here are the changed code block:

original Code block:

    post: function( url, data, callback, type ) {
    // shift arguments if data argument was omited
    if ( jQuery.isFunction( data ) ) {
        type = type || callback;
        callback = data;
        data = {};
    }

    return jQuery.ajax({
        type: "POST",
        url: url,
        data: data,
        success: callback,
        dataType: type
    });  

Changed Code block:

        post: function (url, data, callback, failcallback, type) {
        if (type === undefined || type === null) {
            if (!jQuery.isFunction(failcallback)) { 
            type=failcallback
        }
        else if (!jQuery.isFunction(callback)) {
            type = callback
        }
        }
        if (jQuery.isFunction(data) && jQuery.isFunction(callback)) {
            failcallback = callback;

        }
        // shift arguments if data argument was omited
        if (jQuery.isFunction(data)) {
            type = type || callback;
            callback = data;
            data = {};

        }


        return jQuery.ajax({
            type: "POST",
            url: url,
            data: data,
            success: callback,
            error:failcallback,
            dataType: type
        });
    },

This should help the one trying to catch error on $.Post in jquery.

Updated: Or there is another way to do this is :

   $.post(url,{},function(res){
        //To do write if call is successful
   }).error(function(p1,p2,p3){
             //To do Write if call is failed
          });

How to synchronize or lock upon variables in Java?

That's pretty easy:

class Sample {
    private String message = null;
    private final Object lock = new Object();

    public void newMessage(String x) {
        synchronized (lock) {
            message = x;
        }
    }

    public String getMessage() {
        synchronized (lock) {
            String temp = message;
            message = null;
            return temp;
        }
    }
}

Note that I didn't either make the methods themselves synchronized or synchronize on this. I firmly believe that it's a good idea to only acquire locks on objects which only your code has access to, unless you're deliberately exposing the lock. It makes it a lot easier to reassure yourself that nothing else is going to acquire locks in a different order to your code, etc.