Programs & Examples On #Async safe

LINQ to SQL - Left Outer Join with multiple join conditions

this works too, ...if you have multiple column joins

from p in context.Periods
join f in context.Facts 
on new {
    id = p.periodid,
    p.otherid
} equals new {
    f.id,
    f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value

How to display PDF file in HTML?

The simplest way is to use,

<iframe src="pdf-link">
</iframe>

and if its still getting downloaded instead of viewing, check the server response header, it should have, Content-Disposition:Inline and not, Content-Disposition:Attachment.

CSS div 100% height

Set the html tag, too. This way no weird position hacks are required.

html, body {height: 100%}

Removing Data From ElasticSearch

You can delete one or more indices, which really deletes their files from disk. For example:

curl -XDELETE localhost:9200/$INDEXNAME

Where $INDEXNAME can be an index name (e.g. users_v2), N indices separated by comma (e.g. users_v2,users_v3). An index pattern (e.g. users_*) or _all, also works, unless it's blocked in the config via action.destructive_requires_name: true.

Deleting individual documents is possible, but this won't immediately purge them. A delete is only a soft delete, and documents are really removed during segment merges. You'll find lots of details about segments and merges in this presentation. It's about Solr, but merges are from Lucene, so you have the same options in Elasticsearch.

Back to the API, you can either delete individual documents by ID (provide a routing value if you index with routing):

curl -XDELETE localhost:9200/users_v2/_doc/user1

Or by query:

curl -XPOST -H 'Content-Type: application/json' localhost:9200/users_v2/_delete_by_query -d '{
  "query": {
    "match": {
      "description_field": "bad user"
    }
  }
}'

You don't have permission to access / on this server

Try to use the following: chmod +rx /home/*

Inserting HTML into a div

I think this is what you want:

document.getElementById('tag-id').innerHTML = '<ol><li>html data</li></ol>';

Keep in mind that innerHTML is not accessible for all types of tags when using IE. (table elements for example)

How to get Toolbar from fragment?

toolbar = (Toolbar) getView().findViewById(R.id.toolbar);
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);

Can I write into the console in a unit test? If yes, why doesn't the console window open?

First of all unit tests are, by design, supposed to run completely without interaction.

With that aside, I don't think there's a possibility that was thought of.

You could try hacking with the AllocConsole P/Invoke which will open a console even when your current application is a GUI application. The Console class will then post to the now opened console.

How to download files using axios

The trick is to make an invisible anchor tag in the render() and add a React ref allowing to trigger a click once we have the axios response:

class Example extends Component {
    state = {
        ref: React.createRef()
    }

    exportCSV = () => {
        axios.get(
            '/app/export'
        ).then(response => {
            let blob = new Blob([response.data], {type: 'application/octet-stream'})
            let ref = this.state.ref
            ref.current.href = URL.createObjectURL(blob)
            ref.current.download = 'data.csv'
            ref.current.click()
        })
    }

    render(){
        return(
            <div>
                <a style={{display: 'none'}} href='empty' ref={this.state.ref}>ref</a>
                <button onClick={this.exportCSV}>Export CSV</button>
            </div>
        )
    }
}

Here is the documentation: https://reactjs.org/docs/refs-and-the-dom.html. You can find a similar idea here: https://thewebtier.com/snippets/download-files-with-axios/.

Difference between Width:100% and width:100vw?

Havengard's answer doesn't seem to be strictly true. I've found that vw fills the viewport width, but doesn't account for the scrollbars. So, if your content is taller than the viewport (so that your site has a vertical scrollbar), then using vw results in a small horizontal scrollbar. I had to switch out width: 100vw for width: 100% to get rid of the horizontal scrollbar.

possible EventEmitter memory leak detected

I was facing the same issue, but i have successfully handled with async await.
Please check if it helps.

let dataLength = 25;
Before:
  for (let i = 0; i < dataLength; i++) {
      sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
  }

After:
  for (let i = 0; i < dataLength; i++) {
      await sftp.get(remotePath, fs.createWriteStream(xyzProject/${data[i].name}));
  }

How to write a foreach in SQL Server?

Your select count and select max should be from your table variable instead of the actual table

DECLARE @i int
DECLARE @PractitionerId int
DECLARE @numrows int
DECLARE @Practitioner TABLE (
    idx smallint Primary Key IDENTITY(1,1)
    , PractitionerId int
)

INSERT @Practitioner
SELECT distinct PractitionerId FROM Practitioner

SET @i = 1
SET @numrows = (SELECT COUNT(*) FROM @Practitioner)
IF @numrows > 0
    WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))
    BEGIN

        SET @PractitionerId = (SELECT PractitionerId FROM @Practitioner WHERE idx = @i)

        --Do something with Id here
        PRINT @PractitionerId

        SET @i = @i + 1
    END

center image in div with overflow hidden

this seems to work on our site, using your ideas and a little math based upon the left edge of wrapper div. It seems redundant to go left 50% then take out 50% extra margin, but it seems to work.

div.ImgWrapper {
    width: 160px;
    height: 160px
    overflow: hidden;
    text-align: center;
}

img.CropCenter {
    left: 50%;
    margin-left: -100%;
    position: relative;
    width: auto !important;
    height: 160px !important;
}

<div class="ImgWrapper">
<a href="#"><img class="CropCenter" src="img.png"></a>
</div>

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

How to get an object's properties in JavaScript / jQuery?

I hope this doesn't count as spam. I humbly ended up writing a function after endless debug sessions: http://github.com/halilim/Javascript-Simple-Object-Inspect

function simpleObjInspect(oObj, key, tabLvl)
{
    key = key || "";
    tabLvl = tabLvl || 1;
    var tabs = "";
    for(var i = 1; i < tabLvl; i++){
        tabs += "\t";
    }
    var keyTypeStr = " (" + typeof key + ")";
    if (tabLvl == 1) {
        keyTypeStr = "(self)";
    }
    var s = tabs + key + keyTypeStr + " : ";
    if (typeof oObj == "object" && oObj !== null) {
        s += typeof oObj + "\n";
        for (var k in oObj) {
            if (oObj.hasOwnProperty(k)) {
                s += simpleObjInspect(oObj[k], k, tabLvl + 1);
            }
        }
    } else {
        s += "" + oObj + " (" + typeof oObj + ") \n";
    }
    return s;
}

Usage

alert(simpleObjInspect(anyObject));

or

console.log(simpleObjInspect(anyObject));

How can I read a text file from the SD card in Android?

In your layout you'll need something to display the text. A TextView is the obvious choice. So you'll have something like this:

<TextView 
    android:id="@+id/text_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/>

And your code will look like this:

//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text);

This could go in the onCreate() method of your Activity, or somewhere else depending on just what it is you want to do.

Apache POI error loading XSSFWorkbook class

Add commons-collections4-x.x.jar file in your build path and try it again. It will work.

You can download it from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0

How can I change the color of AlertDialog title and the color of the line under it

If you don't want a "library" for that, you can use this badly hack:

((ViewGroup)((ViewGroup)getDialog().getWindow().getDecorView()).getChildAt(0)) //ie LinearLayout containing all the dialog (title, titleDivider, content)
.getChildAt(1) // ie the view titleDivider
.setBackgroundColor(getResources().getColor(R.color.yourBeautifulColor));

This was tested and work on 4.x; not tested under, but if my memory is good it should work for 2.x and 3.x

Capturing browser logs with Selenium WebDriver using Java

A less elegant solution is taking the log 'manually' from the user data dir:

  1. Set the user data dir to a fixed place:

    options = new ChromeOptions();
    capabilities = DesiredCapabilities.chrome();
    options.addArguments("user-data-dir=/your_path/");
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);
    
  2. Get the text from the log file chrome_debug.log located in the path you've entered above.

I use this method since RemoteWebDriver had problems getting the console logs remotely. If you run your test locally that can be easy to retrieve.

How to set <iframe src="..."> without causing `unsafe value` exception?

This works me to Angular 5.2.0

sarasa.Component.ts

import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-sarasa',
  templateUrl: './sarasa.component.html',
  styleUrls: ['./sarasa.component.scss']
})

export class Sarasa implements OnInit {
  @Input()
  url: string = "https://www.mmlpqtpkasjdashdjahd.com";
  urlSafe: SafeResourceUrl;

  constructor(public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
  }

}

sarasa.Component.html

<iframe width="100%" height="100%" frameBorder="0" [src]="urlSafe"></iframe>

thats all folks!!!

How do I enable C++11 in gcc?

As previously mentioned - in case of a project, Makefile or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.

But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out?

Well, I would much like to have some #pragma to turn in on at source level, or maybe a default extension - say .cxx or .C11 or whatever, trigger it by default. But as of today, there is no such feature.

But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc (or whatever):

alias g++11="g++ -std=c++0x"

or, for newer G++ (and when you want to feel "real C++11")

alias g++11="g++ -std=c++11"

You can even alias to g++ itself, if you hate C++03 that much ;)

How to customize <input type="file">?

Here is one way I recently discovered, with a bit of jQuery

HTML Code:

<form action="">
    <input type="file" name="file_upload" style="display:none" id="myFile">

    <a onclick="fileUpload()"> Upload a file </a>
</form>

For the javascript/jQuery part :

<script>
function fileUpload() {
    $("#myFile").click();
}
</script>

In this example, I have put an "anchor" tag to trigger the file upload. You can replace with anything you want, just remember to put the "onclick" attribute with the proper function.

Hope this helps!

P.S. : Do not forget to include jQuery from CDN or any other source

How to repair COMException error 80040154?

Move excel variables which are global declare in your form to local like in my form I have:

Dim xls As New MyExcel.Interop.Application  
Dim xlb As MyExcel.Interop.Workbook

above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.

Convert String array to ArrayList

Using Collections#addAll()

String[] words = {"ace","boom","crew","dog","eon"};
List<String> arrayList = new ArrayList<>(); 
Collections.addAll(arrayList, words); 

Remove characters from a String in Java

Can't you use

id = id.substring(0, id.length()-4);

And what Eric said, ofcourse.

How to change ProgressBar's progress indicator color in Android

If you want to set primary and secondary progress color to horizontal progress bar programmatically in android then use below snippet

int[][] states = new int[][] {
                        new int[] {-android.R.attr.state_checked},
                        new int[] {android.R.attr.state_checked},
                };

                int[] secondaryColor = new int[] {
                        context.getResources().getColor(R.color.graph_line_one),
                        Color.RED,
                };

                int[] primaryColor = new int[] {
                        context.getResources().getColor(R.color.middle_progress),
                        Color.BLUE,
                };
                progressbar.setProgressTintList(new ColorStateList(states, primaryColor));
                progressbar.setSecondaryProgressTintList(new ColorStateList(states, secondaryColor));

How to keep a VMWare VM's clock in sync?

I added the following job to crontab. It is hacky but i think should work.

*/5 * * * * service ntpd stop && ntpdate pool.ntp.org && service ntpd start

It stops ntpd service updates from service and starts ntpd again

Reference alias (calculated in SELECT) in WHERE clause

As a workaround to force the evaluation of the SELECT clause before the WHERE clause, you could put the former in a sub-query while the latter remains in the main query:

SELECT * FROM (
  SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
  FROM Invoices) AS temp
WHERE BalanceDue > 0
  

Remove all elements contained in another array

Use the Array.filter() method:

myArray = myArray.filter( function( el ) {
  return toRemove.indexOf( el ) < 0;
} );

Small improvement, as browser support for Array.includes() has increased:

myArray = myArray.filter( function( el ) {
  return !toRemove.includes( el );
} );

Next adaptation using arrow functions:

myArray = myArray.filter( ( el ) => !toRemove.includes( el ) );

Static method in a generic class?

Something like the following would get you closer

class Clazz
{
   public static <U extends Clazz> void doIt(U thing)
   {
   }
}

EDIT: Updated example with more detail

public abstract class Thingo 
{

    public static <U extends Thingo> void doIt(U p_thingo)
    {
        p_thingo.thing();
    }

    protected abstract void thing();

}

class SubThingoOne extends Thingo
{
    @Override
    protected void thing() 
    {
        System.out.println("SubThingoOne");
    }
}

class SubThingoTwo extends Thingo
{

    @Override
    protected void thing() 
    {
        System.out.println("SuThingoTwo");
    }

}

public class ThingoTest 
{

    @Test
    public void test() 
    {
        Thingo t1 = new SubThingoOne();
        Thingo t2 = new SubThingoTwo();

        Thingo.doIt(t1);
        Thingo.doIt(t2);

        // compile error -->  Thingo.doIt(new Object());
    }
}

How to set adaptive learning rate for GradientDescentOptimizer?

Gradient descent algorithm uses the constant learning rate which you can provide in during the initialization. You can pass various learning rates in a way showed by Mrry.

But instead of it you can also use more advanced optimizers which have faster convergence rate and adapts to the situation.

Here is a brief explanation based on my understanding:

  • momentum helps SGD to navigate along the relevant directions and softens the oscillations in the irrelevant. It simply adds a fraction of the direction of the previous step to a current step. This achieves amplification of speed in the correct dirrection and softens oscillation in wrong directions. This fraction is usually in the (0, 1) range. It also makes sense to use adaptive momentum. In the beginning of learning a big momentum will only hinder your progress, so it makse sense to use something like 0.01 and once all the high gradients disappeared you can use a bigger momentom. There is one problem with momentum: when we are very close to the goal, our momentum in most of the cases is very high and it does not know that it should slow down. This can cause it to miss or oscillate around the minima
  • nesterov accelerated gradient overcomes this problem by starting to slow down early. In momentum we first compute gradient and then make a jump in that direction amplified by whatever momentum we had previously. NAG does the same thing but in another order: at first we make a big jump based on our stored information, and then we calculate the gradient and make a small correction. This seemingly irrelevant change gives significant practical speedups.
  • AdaGrad or adaptive gradient allows the learning rate to adapt based on parameters. It performs larger updates for infrequent parameters and smaller updates for frequent one. Because of this it is well suited for sparse data (NLP or image recognition). Another advantage is that it basically illiminates the need to tune the learning rate. Each parameter has its own learning rate and due to the peculiarities of the algorithm the learning rate is monotonically decreasing. This causes the biggest problem: at some point of time the learning rate is so small that the system stops learning
  • AdaDelta resolves the problem of monotonically decreasing learning rate in AdaGrad. In AdaGrad the learning rate was calculated approximately as one divided by the sum of square roots. At each stage you add another square root to the sum, which causes denominator to constantly decrease. In AdaDelta instead of summing all past square roots it uses sliding window which allows the sum to decrease. RMSprop is very similar to AdaDelta
  • Adam or adaptive momentum is an algorithm similar to AdaDelta. But in addition to storing learning rates for each of the parameters it also stores momentum changes for each of them separately

    A few visualizations: enter image description here enter image description here

Extract a substring using PowerShell

The Substring method provides us a way to extract a particular string from the original string based on a starting position and length. If only one argument is provided, it is taken to be the starting position, and the remainder of the string is outputted.

PS > "test_string".Substring(0,4)
Test
PS > "test_string".Substring(4)
_stringPS >

link text

But this is easier...

 $s = 'Hello World is in here Hello World!'
 $p = 'Hello World'
 $s -match $p

And finally, to recurse through a directory selecting only the .txt files and searching for occurrence of "Hello World":

dir -rec -filter *.txt | Select-String 'Hello World'

My Routes are Returning a 404, How can I Fix Them?

Don't forget the "RewriteBase" in your public/.htaccess :

For example :

Options +FollowSymLinks
RewriteEngine On
RewriteBase /your/folder/public

Adding a caption to an equation in LaTeX

The \caption command is restricted to floats: you will need to place the equation in a figure or table environment (or a new kind of floating environment). For example:

\begin{figure}
\[ E = m c^2 \]
\caption{A famous equation}
\end{figure}

The point of floats is that you let LaTeX determine their placement. If you want to equation to appear in a fixed position, don't use a float. The \captionof command of the caption package can be used to place a caption outside of a floating environment. It is used like this:

\[ E = m c^2 \]
\captionof{figure}{A famous equation}

This will also produce an entry for the \listoffigures, if your document has one.

To align parts of an equation, take a look at the eqnarray environment, or some of the environments of the amsmath package: align, gather, multiline,...

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

Printing HashMap In Java

To print both key and value, use the following:

for (Object objectName : example.keySet()) {
   System.out.println(objectName);
   System.out.println(example.get(objectName));
 }

How to replace NaN value with zero in a huge data frame?

The following should do what you want:

x <- data.frame(X1=sample(c(1:3,NaN), 200, replace=TRUE), X2=sample(c(4:6,NaN), 200, replace=TRUE))
head(x)
x <- replace(x, is.na(x), 0)
head(x)

Use Robocopy to copy only changed files?

You can use robocopy to copy files with an archive flag and reset the attribute. Use /M command line, this is my backup script with few extra tricks.

This script needs NirCmd tool to keep mouse moving so that my machine won't fall into sleep. Script is using a lockfile to tell when backup script is completed and mousemove.bat script is closed. You may leave this part out.

Another is 7-Zip tool for splitting virtualbox files smaller than 4GB files, my destination folder is still FAT32 so this is mandatory. I should use NTFS disk but haven't converted backup disks yet.

backup-robocopy.bat

@REM https://technet.microsoft.com/en-us/library/cc733145.aspx
@REM http://www.skonet.com/articles_archive/robocopy_job_template.aspx

set basedir=%~dp0
del /Q %basedir%backup-robocopy-log.txt

set dt=%date%_%time:~0,8%
echo "%dt% robocopy started" > %basedir%backup-robocopy-lock.txt
start "Keep system awake" /MIN /LOW  cmd.exe /C %basedir%backup-robocopy-movemouse.bat

set dest=E:\backup

call :BACKUP "Program Files\MariaDB 5.5\data"
call :BACKUP "projects"
call :BACKUP "Users\Myname"

:SPLIT
@REM Split +4GB file to multiple files to support FAT32 destination disk,
@REM splitted files must be stored outside of the robocopy destination folder.
set srcfile=C:\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile=%dest%\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
set dstfile2=%dest%\non-robocopy\Users\Myname\VirtualBox VMs\Ubuntu\Ubuntu.vdi
IF NOT EXIST "%dstfile%" (
  IF NOT EXIST "%dstfile2%.7z.001" attrib +A "%srcfile%"
  dir /b /aa "%srcfile%" && (
    del /Q "%dstfile2%.7z.*"
    c:\apps\commands\7za.exe -mx0 -v4000m u "%dstfile2%.7z"  "%srcfile%"
    attrib -A "%srcfile%"
    @set dt=%date%_%time:~0,8%
    @echo %dt% Splitted %srcfile% >> %basedir%backup-robocopy-log.txt
  )
)

del /Q %basedir%backup-robocopy-lock.txt
GOTO :END


:BACKUP
TITLE Backup %~1
robocopy.exe "c:\%~1" "%dest%\%~1" /JOB:%basedir%backup-robocopy-job.rcj
GOTO :EOF


:END
@set dt=%date%_%time:~0,8%
@echo %dt% robocopy completed >> %basedir%backup-robocopy-log.txt
@echo %dt% robocopy completed
@pause

backup-robocopy-job.rcj

:: Robocopy Job Parameters
:: robocopy.exe "c:\projects" "E:\backup\projects" /JOB:backup-robocopy-job.rcj


:: Source Directory (this is given in command line)
::/SD:c:\examplefolder

:: Destination Directory (this is given in command line)
::/DD:E:\backup\examplefolder

:: Include files matching these names
/IF
    *.*

/M      :: copy only files with the Archive attribute and reset it.
/XJD    :: eXclude Junction points for Directories.

:: Exclude Directories
/XD
    C:\projects\bak
    C:\projects\old
    C:\project\tomcat\logs
    C:\project\tomcat\work
    C:\Users\Myname\.eclipse
    C:\Users\Myname\.m2
    C:\Users\Myname\.thumbnails
    C:\Users\Myname\AppData
    C:\Users\Myname\Favorites
    C:\Users\Myname\Links
    C:\Users\Myname\Saved Games
    C:\Users\Myname\Searches

:: Exclude files matching these names
/XF 
    C:\Users\Myname\ntuser.dat  
    *.~bpl

:: Exclude files with any of the given Attributes set
:: S=System, H=Hidden
/XA:SH      

:: Copy options
/S          :: copy Subdirectories, but not empty ones.
/E          :: copy subdirectories, including Empty ones.
/COPY:DAT   :: what to COPY for files (default is /COPY:DAT).
/DCOPY:T    :: COPY Directory Timestamps.
/PURGE      :: delete dest files/dirs that no longer exist in source.

:: Retry Options
/R:0        :: number of Retries on failed copies: default 1 million.
/W:1        :: Wait time between retries: default is 30 seconds.

:: Logging Options (LOG+ append)
/NDL        :: No Directory List - don't log directory names.
/NP         :: No Progress - don't display percentage copied.
/TEE        :: output to console window, as well as the log file.
/LOG+:c:\apps\commands\backup-robocopy-log.txt :: append to logfile

backup-robocopy-movemouse.bat

@echo off
@REM Move mouse to prevent maching from sleeping 
@rem while running a backup script

echo Keep system awake while robocopy is running,
echo this script moves a mouse once in a while.

set basedir=%~dp0
set IDX=0

:LOOP
IF NOT EXIST "%basedir%backup-robocopy-lock.txt" GOTO :EOF
SET /A IDX=%IDX% + 1
IF "%IDX%"=="240" (
  SET IDX=0
  echo Move mouse to keep system awake
  c:\apps\commands\nircmdc.exe sendmouse move 5 5
  c:\apps\commands\nircmdc.exe sendmouse move -5 -5
)
c:\apps\commands\nircmdc.exe wait 1000
GOTO :LOOP

Why does multiplication repeats the number several times?

In [58]: price = 1 *9
In [59]: price
Out[59]: 9

How to make blinking/flashing text with CSS 3

Change duration and opacity to suit.

.blink_text { 
    -webkit-animation-name: blinker;
    -webkit-animation-duration: 3s;
    -webkit-animation-timing-function: linear;
    -webkit-animation-iteration-count: infinite;
    -moz-animation-name: blinker;
    -moz-animation-duration: 3s;
    -moz-animation-timing-function: linear;
    -moz-animation-iteration-count: infinite;
    animation-name: blinker;
    animation-duration: 3s;
    animation-timing-function: linear; 
    animation-iteration-count: infinite; color: red; 
} 

@-moz-keyframes blinker {
    0% { opacity: 1.0; }
    50% { opacity: 0.3; }
    100% { opacity: 1.0; } 
}

@-webkit-keyframes blinker { 
    0% { opacity: 1.0; }
    50% { opacity: 0.3; }
    100% { opacity: 1.0; } 
} 

@keyframes blinker { 
    0% { opacity: 1.0; } 
    50% { opacity: 0.3; } 
    100% { opacity: 1.0; } 
}

Test for multiple cases in a switch, like an OR (||)

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}

Saving changes after table edit in SQL Server Management Studio

This is a risk to turning off this option. You can lose changes if you have change tracking turned on (your tables).

Chris

http://chrisbarba.wordpress.com/2009/04/15/sql-server-2008-cant-save-changes-to-tables/

How do you count the number of occurrences of a certain substring in a SQL varchar?

In SQL 2017 or higher, you can use this:

declare @hits int = 0
set @hits = (select value from STRING_SPLIT('F609,4DFA,8499',','));
select count(@hits)

SSH Key - Still asking for password and passphrase

Use ssh remote url provided by Github not https.

How to copy selected lines to clipboard in vim

If you are using vim in MAC OSX, unfortunately it comes with older verion, and not complied with clipboard options. Luckily, homebrew can easily solve this problem.

install vim:

brew install vim --with-lua --with-override-system-vim

install gui verion of vim:

brew install macvim --with-lua --with-override-system-vim

restart the terminal to take effect.

append the following line to ~/.vimrc

set clipboard=unnamed

now you can copy the line in vim withyy and paste it system-wide.

gcc-arm-linux-gnueabi command not found

If you are on a 64bit build of ubuntu or debian (see e.g. 'cat /proc/version') you should simply use the 64bit cross compilers, if you cloned

git clone https://github.com/raspberrypi/tools

then the 64bit tools are in

tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64

use that directory for the gcc-toolchain. A useful tutorial for compiling that I followed is available here Building and compiling Raspberry PI Kernel (use the -x64 path from above as ${CCPREFIX})

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

You can also set these values programatically in the class library, this will avoid unnecessary movement of the config files across the library. The example code for simple BasciHttpBinding is -

BasicHttpBinding basicHttpbinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
basicHttpbinding.Name = "BasicHttpBinding_YourName";
basicHttpbinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
basicHttpbinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

EndpointAddress endpointAddress = new EndpointAddress("http://<Your machine>/Service1/Service1.svc");
Service1Client proxyClient = new Service1Client(basicHttpbinding,endpointAddress);

Magento - Retrieve products with a specific attribute value

create attribute name is "price_screen_tab_name". and access using this simple formula.

<?php $_product = $this->getProduct(); ?>
<?php echo $_product->getData('price_screen_tab_name');?>

Convert alphabet letters to number in Python

If you are going to use this conversion a lot, consider calculating once and putting the results in a dictionary:

>>> import string
>>> di=dict(zip(string.letters,[ord(c)%32 for c in string.letters]))
>>> di['c'] 
3

The advantage is dictionary lookups are very fast vs iterating over a list on every call.

>>> for c in sorted(di.keys()):
>>>    print "{0}:{1}  ".format(c, di[c])
# what you would expect....

How to view DB2 Table structure

to get all tables: (You may want to restrict schema to your schema)

select * from syscat.tables

to get all columns: (where tabname = your_tabname)

select * from syscat.columns

Transparent ARGB hex value

BE AWARE

In HTML/CSS (browser code) the format is #RRGGBBAA with the alpha channel as last two hexadecimal digits.

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

Try adding a reference to the missing dll's from your service/web project directly. Adding the references to a different project didn't work for me.

I only had to do this when publishing my web app because it wasn't copying all the required dll's.

C# how to wait for a webpage to finish loading before continuing

I think the DocumentCompleted event of the WebBrowser control should get you where you need to go.

error: Your local changes to the following files would be overwritten by checkout

You can force checkout your branch, if you do not want to commit your local changes.

git checkout -f branch_name

How to know what the 'errno' means?

#include <errno.h> 
#include <stdio.h> 
#include <stdlib.h> 

int main(int i, char *c[]) { 
  if (i != 2)  
    fprintf(stderr, "Usage: perror errno\n"); 
  else { 
    errno = atoi(c[1]); 
    perror(""); 
  } 
  exit(0); 
}    

Works on Solaris.
cc perror.c -o perror << use this line to compile it

Responsive width Facebook Page Plugin

Don't forget the data-href field! For me comments were working without it but were not responsive. And of course data-width='100%'

Easiest way to convert int to string in C++

C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.

#include <string> 

std::string s = std::to_string(42);

is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:

auto s = std::to_string(42);

Note: see [string.conversions] (21.5 in n3242)

jQuery - Increase the value of a counter when a button is clicked

You are trying to set "++" on a jQuery element!

YOu could declare a js variable

var counter = 0;

and in jQuery code do:

$("#counter").html(counter++);

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

Difference between "while" loop and "do while" loop

While Loop:

while(test-condition)
{
      statements;
      increment/decrement;
}
  1. Lower Execution Time and Speed
  2. Entry Conditioned Loop
  3. No fixed number of iterations

Do While Loop:

do
{
      statements;
      increment/decrement;
}while(test-condition);
  1. Higher Execution Time and Speed
  2. Exit Conditioned Loop
  3. Minimum one number of iteration

Find out more on this topic here: Difference Between While and Do While Loop

This is valid for C programming, Java programming and other languages as well because the concepts remain the same, only the syntax changes.

Also, another small but a differentiating factor to note is that the do while loop consists of a semicolon at the end of the while condition.

How to get share counts using graph API

The facebook like button does two things that the API does not do. This might create confusion when you compare the two.

  1. If the URL you use in your like button has a redirect the button will actually show the count of the redirect URL versus the count of the URL you are using.

  2. If the page has a og:url property the like button will show the likes of that url instead of the url in the browser.

Hope this helps someone

MySQL Workbench not displaying query results

I'm using MySqlWorkbench 6.3.9 on macOS and has this problem. I removed the app and installed 6.3.10 which solves the problem.

Adding a slide effect to bootstrap dropdown

I'm doing something like that but on hover instead of on click.. This is the code I'm using, you might be able to tweak it up a bit to get it to work on click

$('.navbar .dropdown').hover(function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
  $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp()
});

How can I inject a property value into a Spring Bean which was configured using annotations?

If you need more Flexibility for the configurations, try the Settings4jPlaceholderConfigurer: http://settings4j.sourceforge.net/currentrelease/configSpringPlaceholder.html

In our application we use:

  • Preferences to configure the PreProd- and Prod-System
  • Preferences and JNDI Environment variables (JNDI overwrites the preferences) for "mvn jetty:run"
  • System Properties for UnitTests (@BeforeClass annotation)

The default order which key-value-Source is checked first, is described in:
http://settings4j.sourceforge.net/currentrelease/configDefault.html
It can be customized with a settings4j.xml (accurate to log4j.xml) in your classpath.

Let me know your opinion: [email protected]

with friendly regards,
Harald

how to determine size of tablespace oracle 11g

One of the way is Using below sql queries

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

Redirect to Action in another controller

Use this:

    return this.RedirectToAction<AccountController>(m => m.LogIn());

What is the meaning of single and double underscore before an object name?

Since so many people are referring to Raymond's talk, I'll just make it a little easier by writing down what he said:

The intention of the double underscores was not about privacy. The intention was to use it exactly like this

class Circle(object):

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        p = self.__perimeter()
        r = p / math.pi / 2.0
        return math.pi * r ** 2.0

    def perimeter(self):
        return 2.0 * math.pi * self.radius

    __perimeter = perimeter  # local reference


class Tire(Circle):

    def perimeter(self):
        return Circle.perimeter(self) * 1.25

It's actually the opposite of privacy, it's all about freedom. It makes your subclasses free to override any one method without breaking the others.

Say you don't keep a local reference of perimeter in Circle. Now, a derived class Tire overrides the implementation of perimeter, without touching area. When you call Tire(5).area(), in theory it should still be using Circle.perimeter for computation, but in reality it's using Tire.perimeter, which is not the intended behavior. That's why we need a local reference in Circle.

But why __perimeter instead of _perimeter? Because _perimeter still gives derived class the chance to override:

class Tire(Circle):

    def perimeter(self):
        return Circle.perimeter(self) * 1.25

    _perimeter = perimeter

Double underscores has name mangling, so there's a very little chance that the local reference in parent class get override in derived class. thus "makes your subclasses free to override any one method without breaking the others".

If your class won't be inherited, or method overriding does not break anything, then you simply don't need __double_leading_underscore.

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

how to change php version in htaccess in server

just FYI in GoDaddy it's this:

AddHandler x-httpd-php5-3 .php

Creating a simple configuration file and parser in C++

Why not trying something simple and human-readable, like JSON (or XML) ?

There are many pre-made open-source implementations of JSON (or XML) for C++ - I would use one of them.

And if you want something more "binary" - try BJSON or BSON :)

Is there a /dev/null on Windows?

Jon Skeet is correct. Here is the Nul Device Driver page in the Windows Embedded documentation (I have no idea why it's not somewhere else...).

Here is another:

Override browser form-filling and input highlighting with HTML/CSS

Since the browser searches for password type fields, another workaround is to include a hidden field at the beginning of your form:

<!-- unused field to stop browsers from overriding form style -->
<input type='password' style = 'display:none' />

JavaScript Array to Set

What levi said about passing it into the constructor is correct, but you could also use an object.

I think what Veverke is trying to say is that you could easily use the delete keyword on an object to achieve the same effect.

I think you're confused by the terminology; properties are components of the object that you can use as named indices (if you want to think of it that way).

Try something like this:

var obj = {
    "bob": "dole",
    "mr.": "peabody",
    "darkwing": "duck"
};

Then, you could just do this:

delete obj["bob"];

The structure of the object would then be this:

{
    "mr.": "peabody",
    "darkwing": "duck"
}

Which has the same effect.

Get user's current location

<?php
$query = @unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
echo 'Hey user from ' . $query['country'] . ', ' . $query['city'] . '!';
}
foreach ($query as $data) {
    echo $data . "<br>";
}
?>

Try this code using this source. it works!

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

In a Object Relational Mapping context, every object needs to have a unique identifier. You use the @Id annotation to specify the primary key of an entity.

The @GeneratedValue annotation is used to specify how the primary key should be generated. In your example you are using an Identity strategy which

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

There are other strategies, you can see more here.

Convert Difference between 2 times into Milliseconds?

Try:

DateTime first;
DateTime second;

int milliSeconds = (int)((TimeSpan)(second - first)).TotalMilliseconds;

Lock, mutex, semaphore... what's the difference?

Most problems can be solved using (i) just locks, (ii) just semaphores, ..., or (iii) a combination of both! As you may have discovered, they're very similar: both prevent race conditions, both have acquire()/release() operations, both cause zero or more threads to become blocked/suspected... Really, the crucial difference lies solely on how they lock and unlock.

  • A lock (or mutex) has two states (0 or 1). It can be either unlocked or locked. They're often used to ensure only one thread enters a critical section at a time.
  • A semaphore has many states (0, 1, 2, ...). It can be locked (state 0) or unlocked (states 1, 2, 3, ...). One or more semaphores are often used together to ensure that only one thread enters a critical section precisely when the number of units of some resource has/hasn't reached a particular value (either via counting down to that value or counting up to that value).

For both locks/semaphores, trying to call acquire() while the primitive is in state 0 causes the invoking thread to be suspended. For locks - attempts to acquire the lock is in state 1 are successful. For semaphores - attempts to acquire the lock in states {1, 2, 3, ...} are successful.

For locks in state state 0, if same thread that had previously called acquire(), now calls release, then the release is successful. If a different thread tried this -- it is down to the implementation/library as to what happens (usually the attempt ignored or an error is thrown). For semaphores in state 0, any thread can call release and it will be successful (regardless of which thread previous used acquire to put the semaphore in state 0).

From the preceding discussion, we can see that locks have a notion of an owner (the sole thread that can call release is the owner), whereas semaphores do not have an owner (any thread can call release on a semaphore).


What causes a lot of confusion is that, in practice they are many variations of this high-level definition.

Important variations to consider:

  • What should the acquire()/release() be called? -- [Varies massively]
  • Does your lock/semaphore use a "queue" or a "set" to remember the threads waiting?
  • Can your lock/semaphore be shared with threads of other processes?
  • Is your lock "reentrant"? -- [Usually yes].
  • Is your lock "blocking/non-blocking"? -- [Normally non-blocking are used as blocking locks (aka spin-locks) cause busy waiting].
  • How do you ensure the operations are "atomic"?

These depends on your book / lecturer / language / library / environment.
Here's a quick tour noting how some languages answer these details.


C, C++ (pthreads)

  • A mutex is implemented via pthread_mutex_t. By default, they can't be shared with any other processes (PTHREAD_PROCESS_PRIVATE), however mutex's have an attribute called pshared. When set, so the mutex is shared between processes (PTHREAD_PROCESS_SHARED).
  • A lock is the same thing as a mutex.
  • A semaphore is implemented via sem_t. Similar to mutexes, semaphores can be shared between threasds of many processes or kept private to the threads of one single process. This depends on the pshared argument provided to sem_init.

python (threading.py)

  • A lock (threading.RLock) is mostly the same as C/C++ pthread_mutex_ts. Both are both reentrant. This means they may only be unlocked by the same thread that locked it. It is the case that sem_t semaphores, threading.Semaphore semaphores and theading.Lock locks are not reentrant -- for it is the case any thread can perform unlock the lock / down the semaphore.
  • A mutex is the same as a lock (the term is not used often in python).
  • A semaphore (threading.Semaphore) is mostly the same as sem_t. Although with sem_t, a queue of thread ids is used to remember the order in which threads became blocked when attempting to lock it while it is locked. When a thread unlocks a semaphore, the first thread in the queue (if there is one) is chosen to be the new owner. The thread identifier is taken off the queue and the semaphore becomes locked again. However, with threading.Semaphore, a set is used instead of a queue, so the order in which threads became blocked is not stored -- any thread in the set may be chosen to be the next owner.

Java (java.util.concurrent)

  • A lock (java.util.concurrent.ReentrantLock) is mostly the same as C/C++ pthread_mutex_t's, and Python's threading.RLock in that it also implements a reentrant lock. Sharing locks between processes is harder in Java because of the JVM acting as an intermediary. If a thread tries to unlock a lock it doesn't own, an IllegalMonitorStateException is thrown.
  • A mutex is the same as a lock (the term is not used often in Java).
  • A semaphore (java.util.concurrent.Semaphore) is mostly the same as sem_t and threading.Semaphore. The constructor for Java semaphores accept a fairness boolean parameter that control whether to use a set (false) or a queue (true) for storing the waiting threads.

In theory, semaphores are often discussed, but in practice, semaphores aren't used so much. A semaphore only hold the state of one integer, so often it's rather inflexible and many are needed at once -- causing difficulty in understanding code. Also, the fact that any thread can release a semaphore is sometimes undesired. More object-oriented / higher-level synchronization primitives / abstractions such as "condition variables" and "monitors" are used instead.

Android SQLite: Update Statement

I use this class to handle database.I hope it will help some one in future.

Happy coding.

public class Database {

private static class DBHelper extends SQLiteOpenHelper {

    /**
     * Database name
     */
    private static final String DB_NAME = "db_name";

    /**
     * Table Names
     */
    public static final String TABLE_CART = "DB_CART";


    /**
     *  Cart Table Columns
     */
    public static final String CART_ID_PK = "_id";// Primary key

    public static final String CART_DISH_NAME = "dish_name";
    public static final String CART_DISH_ID = "menu_item_id";
    public static final String CART_DISH_QTY = "dish_qty";
    public static final String CART_DISH_PRICE = "dish_price";

    /**
     * String to create reservation tabs table
     */
    private final String CREATE_TABLE_CART = "CREATE TABLE IF NOT EXISTS "
            + TABLE_CART + " ( "
            + CART_ID_PK + " INTEGER PRIMARY KEY, "
            + CART_DISH_NAME + " TEXT , "
            + CART_DISH_ID + " TEXT , "
            + CART_DISH_QTY + " TEXT , "
            + CART_DISH_PRICE + " TEXT);";


    public DBHelper(Context context) {
        super(context, DB_NAME, null, 2);

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_CART);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_CART);
        onCreate(db);
    }

}


     /**
      * CART handler
      */
      public static class Cart {


    /**
     * Check if Cart is available or not
     *
     * @param context
     * @return
     */
    public static boolean isCartAvailable(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART;
            Cursor cursor = db.rawQuery(query, null);
            exists = (cursor.getCount() > 0);
            cursor.close();
            db.close();
        } catch (SQLiteException e) {
            db.close();
        }

        return exists;
    }


    /**
     * Insert values in cart table
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean insertItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, "" + itemId);
        values.put(DBHelper.CART_DISH_NAME, "" + dishName);
        values.put(DBHelper.CART_DISH_PRICE, "" + dishPrice);
        values.put(DBHelper.CART_DISH_QTY, "" + dishQty);

        try {
            db.insert(DBHelper.TABLE_CART, null, values);
            db.close();
            return true;
        } catch (SQLiteException e) {
            db.close();
            return false;
        }
    }

    /**
     * Check for specific record by name
     *
     * @param context
     * @param dishName
     * @return
     */
    public static boolean isItemAvailable(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        boolean exists = false;

        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE "
                + DBHelper.CART_DISH_NAME + " = '" + String.valueOf(dishName) + "'";


        try {
            Cursor cursor = db.rawQuery(query, null);

            exists = (cursor.getCount() > 0);
            cursor.close();

        } catch (SQLiteException e) {

            e.printStackTrace();
            db.close();

        }

        return exists;
    }

    /**
     * Update cart item by item name
     *
     * @param context
     * @param dishName
     * @param dishPrice
     * @param dishQty
     * @return
     */
    public static boolean updateItem(Context context, String itemId, String dishName, String dishPrice, String dishQty) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(DBHelper.CART_DISH_ID, itemId);
        values.put(DBHelper.CART_DISH_NAME, dishName);
        values.put(DBHelper.CART_DISH_PRICE, dishPrice);
        values.put(DBHelper.CART_DISH_QTY, dishQty);

        try {

            String[] args = new String[]{dishName};
            db.update(DBHelper.TABLE_CART, values, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();


            return true;
        } catch (SQLiteException e) {
            db.close();

            return false;
        }
    }

    /**
     * Get cart list
     *
     * @param context
     * @return
     */
    public static ArrayList<CartModel> getCartList(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        ArrayList<CartModel> cartList = new ArrayList<>();

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);


            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                cartList.add(new CartModel(
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_ID)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_NAME)),
                        cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)),
                        Integer.parseInt(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE)))
                ));
            }

            db.close();

        } catch (SQLiteException e) {
            db.close();
        }
        return cartList;
    }

   /**
     * Get total amount of cart items
     *
     * @param context
     * @return
     */
    public static String getTotalAmount(Context context) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        double totalAmount = 0.0;

        try {
            String query = "SELECT * FROM " + DBHelper.TABLE_CART + ";";

            Cursor cursor = db.rawQuery(query, null);


            for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {

                totalAmount = totalAmount + Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_PRICE))) *
                        Double.parseDouble(cursor.getString(cursor.getColumnIndex(DBHelper.CART_DISH_QTY)));
            }

            db.close();


        } catch (SQLiteException e) {
            db.close();
        }


        if (totalAmount == 0.0)
            return "";
        else
            return "" + totalAmount;
    }


    /**
     * Get item quantity
     *
     * @param context
     * @param dishName
     * @return
     */
    public static String getItemQty(Context context, String dishName) {

        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        Cursor cursor = null;
        String query = "SELECT * FROM " + DBHelper.TABLE_CART + " WHERE " + DBHelper.CART_DISH_NAME + " = '" + dishName + "';";
        String quantity = "0";

        try {
            cursor = db.rawQuery(query, null);

            if (cursor.getCount() > 0) {

                cursor.moveToFirst();
                quantity = cursor.getString(cursor
                        .getColumnIndex(DBHelper.CART_DISH_QTY));

                return quantity;
            }


        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        return quantity;
    }


    /**
     * Delete cart item by name
     *
     * @param context
     * @param dishName
     */
    public static void deleteCartItem(Context context, String dishName) {
        DBHelper dbHelper = new DBHelper(context);
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        try {

            String[] args = new String[]{dishName};
            db.delete(DBHelper.TABLE_CART, DBHelper.CART_DISH_NAME + "=?", args);

            db.close();
        } catch (SQLiteException e) {
            db.close();
            e.printStackTrace();
        }

    }


}//End of cart class

/**
 * Delete database table
 *
 * @param context
 */
public static void deleteCart(Context context) {
    DBHelper dbHelper = new DBHelper(context);
    SQLiteDatabase db = dbHelper.getReadableDatabase();

    try {

        db.execSQL("DELETE FROM " + DBHelper.TABLE_CART);

    } catch (SQLiteException e) {
        e.printStackTrace();
    }

}

}

Usage:

  if(Database.Cart.isCartAvailable(context)){

       Database.deleteCart(context);

   }

Possible to perform cross-database queries with PostgreSQL?

Just to add a bit more information.

There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave.

contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.

PostgreSQL FAQ

How to extract a value from a string using regex and a shell?

you can use the shell(bash for example)

$ string="12 BBQ ,45 rofl, 89 lol"
$ echo ${string% rofl*}
12 BBQ ,45
$ string=${string% rofl*}
$ echo ${string##*,}
45

Received fatal alert: handshake_failure through SSLHandshakeException

Mine was a TLS version incompatible error.

Previously it was TLSv1 I changed it TLSV1.2 this solved my problem.

How to exclude a directory in find . command

The -path -prune approach also works with wildcards in the path. Here is a find statement that will find the directories for a git server serving multiple git repositiories leaving out the git internal directories:

find . -type d \
   -not \( -path */objects -prune \) \
   -not \( -path */branches -prune \) \
   -not \( -path */refs -prune \) \
   -not \( -path */logs -prune \) \
   -not \( -path */.git -prune \) \
   -not \( -path */info -prune \) \
   -not \( -path */hooks -prune \)  

How can one run multiple versions of PHP 5.x on a development LAMP server?

Having multiple instances of apache + php never really tickled my fancy, but it probably the easiest way to do it. If you don't feel like KISS ... here's an idea.

Get your apache up and running, and try do configure it like debian and ubuntu do it, eg, have directories for loaded modules. Your apache conf can use lines like this:

Include /etc/apache2/mods-enabled/*.load
Include /etc/apache2/mods-enabled/*.conf

Then build your first version of php, and give it a prefix that has the version number explicitly contained, eg, /usr/local/php/5.2.8, /usr/local/php/5.2.6 ...

The conf/load would look something like this:

php5.2.6.load

LoadModule php5_module /usr/local/php/5.2.6/libphp5.so

php5.2.8.load

LoadModule php5_module /usr/local/php/5.2.8/libphp5.so

To switch versions, all you have to do is change the load and conf files from the directory apache does the include on for the ones for another version. You can automate that with a simple bash script (delete the actual file, copy the alternate versions file in place, and restart apache.

One advantage of this setup is the everything is consitent, so long you keep the php.ini's the same in terms of options and modules (which you would have to do with CGI anyway). They're all going through SAPI. Your applications won't need any changes whatsoever, nor need to use relative URLs.

I think this should work, but then again, i haven't tried it, nor am i likely to do so as i don't have the same requirements as you. Do comment if you ever do try though.

Trim Whitespaces (New Line and Tab space) in a String in Oracle

If at all anyone is looking to convert data in 1 variable that lies in 2 or 3 different lines like below

'Data1

Data2'

And you want to display data as 'Data1 Data2' then use below

select TRANSLATE ('Data1

Data2', ''||CHR(10), ' ') from dual;

it took me hrs to get the right output. Thanks to me I just saved you 1 or 2 hrs :)

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Hide the browse button on a input type=file

No, what you can do is a (ugly) workaround, but largely used

  1. Create a normal input and a image
  2. Create file input with opacity 0
  3. When the user click on the image, you simulate a click on the file input
  4. When file input change, you pass it's value to the normal input (so user can see the path)

Here you can see a full explanation, along with code:

http://www.quirksmode.org/dom/inputfile.html

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

I found another solution to get the data. according to the documentation Please check documentation link

In service file add following.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class MoviesService {

  constructor(private db: AngularFireDatabase) {}
  getMovies() {
    this.db.list('/movies').valueChanges();
  }
}

In Component add following.

import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
  movies$;

  constructor(private moviesDb: MoviesService) { 
   this.movies$ = moviesDb.getMovies();
 }

In your html file add following.

<li  *ngFor="let m of movies$ | async">{{ m.name }} </li>

How do I force Kubernetes to re-pull an image?

One has to group imagePullPolicy inside the container data instead of inside the spec data. However, I filed an issue about this because I find it odd. Besides, there is no error message.

So, this spec snippet works:

spec:
  containers:
  - name: myapp
    image: myregistry.com/myapp:5c3dda6b
    ports:
    - containerPort: 80
    imagePullPolicy: Always
  imagePullSecrets:
    - name: myregistry.com-registry-key

Disable Transaction Log

What's your problem with Tx logs? They grow? Then just set truncate on checkpoint option.

From Microsoft documentation:

In SQL Server 2000 or in SQL Server 2005, the "Simple" recovery model is equivalent to "truncate log on checkpoint" in earlier versions of SQL Server. If the transaction log is truncated every time a checkpoint is performed on the server, this prevents you from using the log for database recovery. You can only use full database backups to restore your data. Backups of the transaction log are disabled when the "Simple" recovery model is used.

How to get row data by clicking a button in a row in an ASP.NET gridview

<asp:TemplateField>
   <ItemTemplate>
  <asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click"   > 
 </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>

  protected void LnKB_Click(object sender, System.EventArgs e)
  {
        LinkButton lb = sender as LinkButton;

        GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
        int x = clickedRow.RowIndex;
        int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
        lbl.Text = yourgridviewname.Rows[x].Cells[2].Text; 
   }

How to add a Java Properties file to my Java Project in Eclipse

  1. Create Folder “resources” under Java Resources folder if your project doesn’t have it.
    1. create config.properties file with below value.

enter image description here

/Java Resources/resources/config.properties

for loading properties.

Properties prop = new Properties();
InputStream input = null;

try {

      input = getClass().getClassLoader().getResourceAsStream("config.properties");


    // load a properties file
    prop.load(input);

    // get the property value and print it out
    System.out.println(prop.getProperty("database"));
    System.out.println(prop.getProperty("dbuser"));
    System.out.println(prop.getProperty("dbpassword"));

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Make REST API call in Swift

func getAPICalling(mainUrl:String) {
    //create URL
    guard let url = URL(string: mainUrl) else {
      print("Error: cannot create URL")
      return
    }
    //create request
    let urlRequest = URLRequest(url: url)
    
    // create the session
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    
    // make the request
    let task = session.dataTask(with: urlRequest) {
      (data, response, error) in
        
      // check for any errors
      guard error == nil else {
        print("error calling GET")
        print(error!.localizedDescription)
        return
      }
        
      // make sure we got data
      guard let responseData = data else {
        print("error: did not receive data")
        return
      }
        
      // convert Data in JSON && parse the result as JSON, since that's what the API provides
      do {
        guard let object = try JSONSerialization.jsonObject(with: responseData, options: [])
          as? [String: Any] else {
            print("error trying to convert data to JSON")
            return
        }
        //JSON Response
        guard let todoTitle = object["response"] as? NSDictionary else {
          print("Could not get todo title from JSON")
          return
        }
        
        //Get array in response
        let responseList = todoTitle.value(forKey: "radioList") as! NSArray
        
        for item in responseList {
            let dic = item as! NSDictionary
            let str = dic.value(forKey: "radio_des") as! String
            self.arrName.append(str)
            print(item)
        }
        
        DispatchQueue.main.async {
            self.tblView.reloadData()
        }
        
      } catch  {
        print("error trying to convert data to JSON")
        return
      }
    }
    task.resume()
}

Usage:

getAPICalling(mainUrl:"https://dousic.com/api/radiolist?user_id=16")

How do I obtain crash-data from my Android application?

For an alternate crash reporting/exception tracking service check out Raygun.io - it's got a bunch of nice logic for handling Android crashes, including decent user experience when plugging it in to your app (two lines of code in your main Activity and a few lines of XML pasted into AndroidManifest).

When your app crashes, it'll automatically grab the stack trace, environment data for hard/software, user tracking info, any custom data you specify etc. It posts it to the API asynchronously so no blocking of the UI thread, and caches it to disk if there's no network available.

Disclaimer: I built the Android provider :)

Why do python lists have pop() but not push()

Probably because the original version of Python (CPython) was written in C, not C++.

The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.

What's the actual use of 'fail' in JUnit test case?

I, for example, use fail() to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.

This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.

Git pull a certain branch from GitHub

The best way is:

git checkout -b <new_branch> <remote repo name>/<new_branch>

Remove Rows From Data Frame where a Row matches a String

if you wish to using dplyr, for to remove row "Foo":

df %>%
 filter(!C=="Foo")

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

I got this error:

System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions

when the port was used by another program.

How to select only the first rows for each unique value of a column?

In SQL 2k5+, you can do something like:

;with cte as (
  select CName, AddressLine,
  rank() over (partition by CName order by AddressLine) as [r]
  from MyTable
)
select CName, AddressLine
from cte
where [r] = 1

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

Correct format specifier to print pointer or address?

p is the conversion specifier to print pointers. Use this.

int a = 42;

printf("%p\n", (void *) &a);

Remember that omitting the cast is undefined behavior and that printing with p conversion specifier is done in an implementation-defined manner.

Java keytool easy way to add server cert from url/port

I use openssl, but if you prefer not to, or are on a system (particularly Windows) that doesn't have it, since java 7 in 2011 keytool can do the whole job:

 keytool -printcert -sslserver host[:port] -rfc >tempfile
 keytool -import [-noprompt] -alias nm -keystore file [-storepass pw] [-storetype ty] <tempfile 
 # or with noprompt and storepass (so nothing on stdin besides the cert) piping works:
 keytool -printcert -sslserver host[:port] -rfc | keytool -import -noprompt -alias nm -keystore file -storepass pw [-storetype ty]

Conversely, for java 9 up always, and for earlier versions in many cases, Java can use a PKCS12 file for a keystore instead of the traditional JKS file, and OpenSSL can create a PKCS12 without any assistance from keytool:

openssl s_client -connect host:port </dev/null | openssl pkcs12 -export -nokeys [-name nm] [-passout option] -out p12file
# <NUL on Windows
# default is to prompt for password, but -passout supports several options 
# including actual value, envvar, or file; see the openssl(1ssl) man page 

How to make a simple collection view with Swift

For swift 4.2 --

//MARK: UICollectionViewDataSource

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    return 1     //return number of sections in collection view
}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 10    //return number of rows in section
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath as IndexPath)
    configureCell(cell: cell, forItemAtIndexPath: indexPath)
    return cell      //return your cell
}

func configureCell(cell: UICollectionViewCell, forItemAtIndexPath: NSIndexPath) {
    cell.backgroundColor = UIColor.black


    //Customise your cell

}

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    let view =  collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "collectionCell", for: indexPath as IndexPath) as UICollectionReusableView
    return view
}

//MARK: UICollectionViewDelegate
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    // When user selects the cell
}

func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) {
    // When user deselects the cell
}

How to Generate a random number of fixed length using JavaScript?


Only fully reliable answer that offers full randomness, without loss. The other ones prior to this answer all looses out depending on how many characters you want. The more you want, the more they lose randomness.

They achieve it by limiting the amount of numbers possible preceding the fixed length.

So for instance, a random number of fixed length 2 would be 10 - 99. For 3, 100 - 999. For 4, 1000 - 9999. For 5 10000 - 99999 and so on. As can be seen by the pattern, it suggests 10% loss of randomness because numbers prior to that are not possible. Why?

For really large numbers ( 18, 24, 48 ) 10% is still a lot of numbers to loose out on.

function generate(n) {
        var add = 1, max = 12 - add;   // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.   

        if ( n > max ) {
                return generate(max) + generate(n - max);
        }

        max        = Math.pow(10, n+add);
        var min    = max/10; // Math.pow(10, n) basically
        var number = Math.floor( Math.random() * (max - min + 1) ) + min;

        return ("" + number).substring(add); 
}

The generator allows for ~infinite length without lossy precision and with minimal performance cost.

Example:

generate(2)
"03"
generate(2)
"72"
generate(2)
"20"
generate(3)
"301"
generate(3)
"436"
generate(3)
"015"

As you can see, even the zero are included initially which is an additional 10% loss just that, besides the fact that numbers prior to 10^n are not possible.

That's now a total of 20%.

Also, the other options have an upper limit on how many characters you can actually generate.

Example with cost:

var start = new Date(); var num = generate(1000); console.log('Time: ', new Date() - start, 'ms for', num)

Logs:

Time: 0 ms for 7884381040581542028523049580942716270617684062141718855897876833390671831652069714762698108211737288889182869856548142946579393971303478191296939612816492205372814129483213770914444439430297923875275475120712223308258993696422444618241506074080831777597175223850085606310877065533844577763231043780302367695330451000357920496047212646138908106805663879875404784849990477942580056343258756712280958474020627842245866908290819748829427029211991533809630060693336825924167793796369987750553539230834216505824880709596544701685608502486365633618424746636614437646240783649056696052311741095247677377387232206206230001648953246132624571185908487227730250573902216708727944082363775298758556612347564746106354407311558683595834088577220946790036272364740219788470832285646664462382109714500242379237782088931632873392735450875490295512846026376692233811845787949465417190308589695423418373731970944293954443996348633968914665773009376928939207861596826457540403314327582156399232931348229798533882278769760

More hardcore:

generate(100000).length === 100000 -> true

Right Align button in horizontal LinearLayout

I have used a similar layout with 4 TextViews. Two TextViews should be aligned to left and two TextViews should be aligned to right. So, here is my solution, if you want to use LinearLayouts alone.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:baselineAligned="false"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="0dip"
        android:layout_weight="0.50"
        android:layout_height="match_parent"
        android:gravity="left"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textview_fragment_mtfstatus_level"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/level"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/textview_fragment_mtfstatus_level_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="0dip"
        android:layout_weight="0.50"
        android:layout_height="match_parent"
        android:gravity="right"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/textview_fragment_mtfstatus_time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/time"
            android:textAppearance="?android:attr/textAppearanceMedium"
             />

        <TextView
            android:id="@+id/textview_fragment_mtfstatus_time_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceMedium" 
            />
    </LinearLayout>

</LinearLayout>

Convert Rows to columns using 'Pivot' in SQL Server

This is what you can do:

SELECT * 
FROM yourTable
PIVOT (MAX(xCount) 
       FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt

DEMO

How to export and import a .sql file from command line with options?

Type the following command to import sql data file:

$ mysql -u username -p -h localhost DATA-BASE-NAME < data.sql

In this example, import 'data.sql' file into 'blog' database using vivek as username:

$ mysql -u vivek -p -h localhost blog < data.sql

If you have a dedicated database server, replace localhost hostname with with actual server name or IP address as follows:

$ mysql -u username -p -h 202.54.1.10 databasename < data.sql

To export a database, use the following:

mysqldump -u username -p databasename > filename.sql

Note the < and > symbols in each case.

Setting Icon for wpf application (VS 08)

You can try this also:

private void Page_Loaded_1(object sender, RoutedEventArgs e)
    {
        Uri iconUri = new Uri(@"C:\Apps\R&D\WPFNavigation\WPFNavigation\Images\airport.ico", UriKind.RelativeOrAbsolute);
        (this.Parent as Window).Icon = BitmapFrame.Create(iconUri);
    }

how to drop database in sqlite?

If you want to delete database programatically you can use deleteDatabase from Context class:

deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.

AngularJS - pass function to directive

@JorgeGRC Thanks for your answer. One thing though, the "maybe" part is very important. If you do have parameter(s), you must include it/them on your template as well and be sure to specify your locals e.g. updateFn({msg: "Directive Args"}.

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Copy and paste content from one file to another file in vi

Use the variations of d like dd to cut.

To write a range of lines to another file you can use:

:<n>,<m> w filename

Where <n> and <m> are numbers (or symbols) that designate a range of lines.

For using the desktop clipboard, take a look at the +g commands.

Python list subtraction operation

if duplicate and ordering items are problem :

[i for i in a if not i in b or b.remove(i)]

a = [1,2,3,3,3,3,4]
b = [1,3]
result: [2, 3, 3, 3, 4]

How to enable CORS in AngularJs

        var result=[];
        var app = angular.module('app', []);
        app.controller('myCtrl', function ($scope, $http) {
             var url="";// your request url    
             var request={};// your request parameters
             var headers = {
             // 'Authorization': 'Basic ' + btoa(username + ":" + password),
            'Access-Control-Allow-Origin': true,
            'Content-Type': 'application/json; charset=utf-8',
            "X-Requested-With": "XMLHttpRequest"
              }
             $http.post(url, request, {
                        headers
                 })
                 .then(function Success(response) {
                      result.push(response.data);             
                      $scope.Data = result;              
                 }, 
                  function Error(response) {
                      result.push(response.data);
                       $scope.Data = result;
                    console.log(response.statusText + " " + response.status)
               }); 
     });

And also add following code in your WebApiConfig file            
        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);

'cannot find or open the pdb file' Visual Studio C++ 2013

There are no problems here this is perfectly normal - it shows informational messages about what debug-info was loaded (and which wasn't) and also that your program executed and exited normally - a zero return code means success.

If you don't see anything on the screen thry running your program with CTRL-F5 instead of just F5.

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

This works the best for me:

.noSelect:hover {
  background-color: white;
}

Run PowerShell scripts on remote PC

The accepted answer didn't work for me but the following did:

>PsExec.exe \\<SERVER FQDN> -u <DOMAIN\USER> -p <PASSWORD> /accepteula cmd 
    /c "powershell -noninteractive -command gci c:\"

Example from here

Upgrading Node.js to latest version

If Node install script doesn't work for you (it didn't for me), here's the solution to update Node Js in Debian Jessie, taken from the reply from Thomas Ward at askubuntu.com (Thanks, buddy!).

1.- Create a new file: /etc/apt/sources.list.d/nodesource.list

You'll need to create this file with sudo, but when you create the file, put this inside it:

deb https://deb.nodesource.com/node_9.x jessie main
deb-src https://deb.nodesource.com/node_9.x jessie main

Then, save the file. (replace node_9.x with the desired version)

2.- Download the GPG Signing Key from Nodesource for the repository. Otherwise, you may get NO_PUBKEY errors with apt-get update:

curl -s https://deb.nodesource.com/gpgkey/nodesource.gpg.key | sudo apt-key add -

3.- Manually run sudo apt-get update.

This refreshes the data from the nodesource repo so apt knows a newer version exists.

If you get a NO_PUBKEY GPG error, then go back to Step 2

4.- Check apt-cache policy nodejs output.

This is not done by the script, but you want to make sure you see an entry that says something like this in the output:

Version table:
 *** 9.2.0-1nodesource1 0
        500 https://deb.nodesource.com/node_9.x/ jessie/main amd64 Packages
        100 /var/lib/dpkg/status
     0.10.29~dfsg-2 0
        500 http://ftp.debian.org/debian/ jessie/main amd64 Packages

If you do not see entries like this, and only see 0.10.29, start over. Otherwise, proceed.

5.- Install the nodejs binary. Now that you have confirmed 9.x is available on your system, you can install it: sudo apt-get install nodejs

nodejs -v should now show v9.2 or similar on output (as long as it starts with v9. you're on version 9 then).

How to center and crop an image to always appear in square shape with CSS?

HTML:

<div class="thumbnail">
</div>

CSS:

.thumbnail { 
background: url(image.jpg) 50% 50% no-repeat; /* 50% 50% centers image in div */
width: 250px;
height: 250px;
}

Equivalent of Math.Min & Math.Max for Dates?

Linq.Min() / Linq.Max() approach:

DateTime date1 = new DateTime(2000,1,1);
DateTime date2 = new DateTime(2001,1,1);

DateTime minresult = new[] { date1,date2 }.Min();
DateTime maxresult = new[] { date1,date2 }.Max(); 

Android fade in and fade out with ImageView

I'm using this kind of routine for programmatically chaining animations.

    final Animation anim_out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out); 
    final Animation anim_in  = AnimationUtils.loadAnimation(context, android.R.anim.fade_in); 

    anim_out.setAnimationListener(new AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation) {}

        @Override
        public void onAnimationRepeat(Animation animation) {}

        @Override
        public void onAnimationEnd(Animation animation)
        {
            ////////////////////////////////////////
            // HERE YOU CHANGE YOUR IMAGE CONTENT //
            ////////////////////////////////////////
            //ui_image.setImage...

            anim_in.setAnimationListener(new AnimationListener()
            {
                @Override
                public void onAnimationStart(Animation animation) {}

                @Override
                public void onAnimationRepeat(Animation animation) {}

                @Override
                public void onAnimationEnd(Animation animation) {}
            });

            ui_image.startAnimation(anim_in);
        }
    });

    ui_image.startAnimation(anim_out);

Get screenshot on Windows with Python?

Another approach that is really fast is the MSS module. It is different from other solutions in the way that it uses only the ctypes standard module, so it does not require big dependencies. It is OS independant and its use is made easy:

from mss import mss

with mss() as sct:
    sct.shot()

And just find the screenshot.png file containing the screen shot of the first monitor. There are a lot of possibile customizations, you can play with ScreenShot objects and OpenCV/Numpy/PIL/etc..

regex error - nothing to repeat

Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat is a bit confusing. I was trying to use r'?.*' as a pattern, and thought it was complaining for some strange reason about the *, but the problem is actually that ? is a way of saying "repeat zero or one times". So I needed to say r'\?.*'to match a literal ?

iterating and filtering two lists using java 8

See below, would welcome anyones feedback on the below code.

not common between two arrays:

List<String> l3 =list1.stream().filter(x -> !list2.contains(x)).collect(Collectors.toList());

Common between two arrays:

List<String> l3 =list1.stream().filter(x -> list2.contains(x)).collect(Collectors.toList());

Limit Get-ChildItem recursion depth

Use this to limit the depth to 2:

Get-ChildItem \*\*\*,\*\*,\*

The way it works is that it returns the children at each depth 2,1 and 0.


Explanation:

This command

Get-ChildItem \*\*\*

returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.

In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.

/etc/apt/sources.list" E212: Can't open file for writing

change user to root

sodu su -

browse to etc

vi sudoers

look for root user in user priviledge section. you will get it like

root ALL=(ALL:ALL) ALL 

make same entry for your user name. if you username is 'myuser' then add

myuser ALL=(ALL:ALL) ALL

it will look like

root ALL=(ALL:ALL) ALL 

myuser ALL=(ALL:ALL) ALL 

save it. change root user to your user. now try the same where you were getting the sudoers issue

How to transfer data from JSP to servlet when submitting HTML form

http://oreilly.com/catalog/javacook/chapter/ch18.html

Search for :

"Problem

You want to process the data from an HTML form in a servlet. "

How to change the color of an svg element?

To change the color of any SVG you can directly change the svg code by opening the svg file in any text editor. The code may look like the below code

<?xml version="1.0" encoding="utf-8"?>
    <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
         width="500px" height="500px" viewBox="0 0 500 500" enable-background="new 0 0 500 500" xml:space="preserve">
    <g>
        <path d="M114.26,436.584L99.023,483h301.953l-15.237-46.416H114.26z M161.629,474.404h-49.592l9.594-29.225h69.223
            C181.113,454.921,171.371,464.663,161.629,474.404z"/>
    /*Some more code goes on*/
    </g>
    </svg>

You can observe that there are some XML tags like path, circle, polygon etc. There you can add your own color with help of style attribute. Look at the below example

<path style="fill:#AB7C94;" d="M114.26,436.584L99.023,483h301.953l-15.237-46.416H114.26z M161.629,474.404h-49.592l9.594-29.225h69.223
                C181.113,454.921,171.371,464.663,161.629,474.404z"/>

Add the style attribute to all the tags so that you can get your SVG of your required color

Redis strings vs Redis hashes to represent JSON: efficiency?

It depends on how you access the data:

Go for Option 1:

  • If you use most of the fields on most of your accesses.
  • If there is variance on possible keys

Go for Option 2:

  • If you use just single fields on most of your accesses.
  • If you always know which fields are available

P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.

How do I iterate through lines in an external file with shell?

You'll be wanting to use the 'read' command

while read name
do
    echo "$name"
done < names.txt

Note that "$name" is quoted -- if it's not, it will be split using the characters in $IFS as delimiters. This probably won't be noticed if you're just echoing the variable, but if your file contains a list of file names which you want to copy, those will get broken down by $IFS if the variable is unquoted, which is not what you want or expect.

If you want to use Mike Clark's approach (loading into a variable rather than using read), you can do it without the use of cat:

NAMES="$(< scripts/names.txt)" #names from names.txt file
for NAME in $NAMES; do
    echo "$NAME"
done

The problem with this is that it loads the whole file into $NAMES, when you read it back out, you can either get the whole file (if quoted) or the file broken down by $IFS, if not quoted. By default, this will give you individual words, not individual lines. So if the name "Mary Jane" appeared on a line, you would get "Mary" and "Jane" as two separate names. Using read will get around this... although you could also change the value of $IFS

Bash script and /bin/bash^M: bad interpreter: No such file or directory

Your file has Windows line endings, which is confusing Linux.

Remove the spurious CR characters. You can do it with the following command:

 $ sed -i -e 's/\r$//' setup.sh

Using mysql concat() in WHERE clause?

Note that the search query is now case sensitive.

When using

SELECT * FROM table WHERE `first_name` LIKE '%$search_term%'

It will match both "Larry" and "larry". With this concat_ws, it will suddenly become case sensitive!

This can be fixed by using the following query:

SELECT * FROM table WHERE UPPER(CONCAT_WS(' ', `first_name`, `last_name`) LIKE UPPER('%$search_term%')

Edit: Note that this only works on non-binary elements. See also mynameispaulie's answer.

pass **kwargs argument to another function with **kwargs

Expanding on @gecco 's answer, the following is an example that'll show you the difference:

def foo(**kwargs):
    for entry in kwargs.items():
        print("Key: {}, value: {}".format(entry[0], entry[1]))

# call using normal keys:
foo(a=1, b=2, c=3)
# call using an unpacked dictionary:
foo(**{"a": 1, "b":2, "c":3})

# call using a dictionary fails because the function will think you are
# giving it a positional argument
foo({"a": 1, "b": 2, "c": 3})
# this yields the same error as any other positional argument
foo(3)
foo("string")

Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

Can dplyr package be used for conditional mutating?

dplyr now has a function case_when that offers a vectorised if. The syntax is a little strange compared to mosaic:::derivedFactor as you cannot access variables in the standard dplyr way, and need to declare the mode of NA, but it is considerably faster than mosaic:::derivedFactor.

df %>%
mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                     a %in% c(0,1,3,4) | c == 4 ~ 3L, 
                     TRUE~as.integer(NA)))

EDIT: If you're using dplyr::case_when() from before version 0.7.0 of the package, then you need to precede variable names with '.$' (e.g. write .$a == 1 inside case_when).

Benchmark: For the benchmark (reusing functions from Arun 's post) and reducing sample size:

require(data.table) 
require(mosaic) 
require(dplyr)
require(microbenchmark)

set.seed(42) # To recreate the dataframe
DT <- setDT(lapply(1:6, function(x) sample(7, 10000, TRUE)))
setnames(DT, letters[1:6])
DF <- as.data.frame(DT)

DPLYR_case_when <- function(DF) {
  DF %>%
  mutate(g = case_when(a %in% c(2,5,7) | (a==1 & b==4) ~ 2L, 
                       a %in% c(0,1,3,4) | c==4 ~ 3L, 
                       TRUE~as.integer(NA)))
}

DT_fun <- function(DT) {
  DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
  DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
  mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
                    ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

mosa_fun <- function(DF) {
  mutate(DF, g = derivedFactor(
    "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
    "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
    .method = "first",
    .default = NA
  ))
}

perf_results <- microbenchmark(
  dt_fun <- DT_fun(copy(DT)),
  dplyr_ifelse <- DPLYR_fun(copy(DF)),
  dplyr_case_when <- DPLYR_case_when(copy(DF)),
  mosa <- mosa_fun(copy(DF)),
  times = 100L
)

This gives:

print(perf_results)
Unit: milliseconds
           expr        min         lq       mean     median         uq        max neval
         dt_fun   1.391402    1.560751   1.658337   1.651201   1.716851   2.383801   100
   dplyr_ifelse   1.172601    1.230351   1.331538   1.294851   1.390351   1.995701   100
dplyr_case_when   1.648201    1.768002   1.860968   1.844101   1.958801   2.207001   100
           mosa 255.591301  281.158350 291.391586 286.549802 292.101601 545.880702   100

What are the differences between LDAP and Active Directory?

LDAP sits on top of the TCP/IP stack and controls internet directory access. It is environment agnostic.

AD & ADSI is a COM wrapper around the LDAP layer, and is Windows specific.

You can see Microsoft's explanation here.

Python: how to capture image from webcam on click using OpenCV

Here is a simple programe to capture a image from using laptop default camera.I hope that this will be very easy method for all.

import cv2

# 1.creating a video object
video = cv2.VideoCapture(0) 
# 2. Variable
a = 0
# 3. While loop
while True:
    a = a + 1
    # 4.Create a frame object
    check, frame = video.read()
    # Converting to grayscale
    #gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    # 5.show the frame!
    cv2.imshow("Capturing",frame)
    # 6.for playing 
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
# 7. image saving
showPic = cv2.imwrite("filename.jpg",frame)
print(showPic)
# 8. shutdown the camera
video.release()
cv2.destroyAllWindows 

You can see my github code here

Concatenating elements in an array to a string

String newString= Arrays.toString(oldString).replace("[","").replace("]","").replace(",","").trim();

Trigger insert old values- values that was updated

Here's an example update trigger:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

This will print:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

Alternative Windows shells, besides CMD.EXE?

  1. Hard to copy and paste.

    Not true. Enable QuickEdit, either in the properties of the shortcut, or in the properties of the CMD window (right-click on the title bar), and you can mark text directly. Right-click copies marked text into the clipboard. When no text is marked, a right-click pastes text from the clipboard.

    enter image description here

  2. Hard to resize the window.

    True. Console2 (see below) does not have this limitation.

  3. Hard to open another window (no menu options do this).

    Not true. Use start cmd or define an alias if that's too much hassle:

    doskey nw=start cmd /k $*
    
  4. Seems to always start in C:\Windows\System32, which is super useless.

    Not true. Or rather, not true if you define a start directory in the properties of the shortcut

    enter image description here

    or by modifying the AutoRun registry value. Shift-right-click on a folder allows you to launch a command prompt in that folder.

  5. Weird scrolling. Sometimes it scrolls down really far into blank space, and you have to scroll up to where the window is actually populated

    Never happened to me.

An alternative to plain CMD is Console2, which uses CMD under the hood, but provides a lot more configuration options.

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Eclipse shows errors but I can't find them

For me, this happens with Maven and Eclipse/STS whenever I update my IDE or import an existing Maven project. Go to the "Problems tab" (Window -> Show View -> Problems) and see what it says. Recently, the problems tab showed Project configuration is not up-to-date ... and suggested that I use Maven to update my project configuration, and this solved the "red X" problem. To do this, in the "Project Explorer" view, trigger the context menu and select Maven -> Update Project, as seen in this screenshot snippet:

trigger the context menu and select Maven -> Update Project

How to properly make a http web GET request

Adding to the responses already given, this is a complete example hitting JSON PlaceHolder site.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Publish
{
    class Program
    {
        static async Task Main(string[] args)
        {
            
            // Get Reqeust
            HttpClient req = new HttpClient();
            var content = await req.GetAsync("https://jsonplaceholder.typicode.com/users");
            Console.WriteLine(await content.Content.ReadAsStringAsync());

            // Post Request
            Post p = new Post("Some title", "Some body", "1");
            HttpContent payload = new StringContent(JsonConvert.SerializeObject(p));
            content = await req.PostAsync("https://jsonplaceholder.typicode.com/posts", payload);
            Console.WriteLine("--------------------------");
            Console.WriteLine(content.StatusCode);
            Console.WriteLine(await content.Content.ReadAsStringAsync());
        }
    }

    public struct Post {
        public string Title {get; set;}
        public string Body {get;set;}
        public string UserID {get; set;}

        public Post(string Title, string Body, string UserID){
            this.Title = Title;
            this.Body = Body;
            this.UserID = UserID;
        }
    }
}

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

ps command doesn't work in docker container

Firstly, run the command below:

apt-get update && apt-get install procps

and then run:

ps -ef

How to convert string to binary?

We just need to encode it.

'string'.encode('ascii')

Checking if a SQL Server login already exists

This is for Azure SQL:

IF (EXISTS(SELECT TOP 1 1 FROM sys.sql_logins WHERE [name] = '<login>'))
    DROP LOGIN [<login>];

Source: How to check whether database user already exists in Azure SQL Database

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Neither the question nor the answers really fit my simple way of thinking about it. I'm a consultant and have synchronized these definitions with a number of Dev teams and DevOps people, but am curious about how it matches with the industry at large:

Basically I think of the agile practice of continuous delivery like a continuum:

Not continuous (everything manual) 0% ----> 100% Continuous Delivery of Value (everything automated)

Steps towards continuous delivery:

Zero. Nothing is automated when devs check in code... You're lucky if they have compiled, run, or performed any testing prior to check-in.

  1. Continuous Build: automated build on every check-in, which is the first step, but does nothing to prove functional integration of new code.

  2. Continuous Integration (CI): automated build and execution of at least unit tests to prove integration of new code with existing code, but preferably integration tests (end-to-end).

  3. Continuous Deployment (CD): automated deployment when code passes CI at least into a test environment, preferably into higher environments when quality is proven either via CI or by marking a lower environment as PASSED after manual testing. I.E., testing may be manual in some cases, but promoting to next environment is automatic.

  4. Continuous Delivery: automated publication and release of the system into production. This is CD into production plus any other configuration changes like setup for A/B testing, notification to users of new features, notifying support of new version and change notes, etc.

EDIT: I would like to point out that there's a difference between the concept of "continuous delivery" as referenced in the first principle of the Agile Manifesto (http://agilemanifesto.org/principles.html) and the practice of Continuous Delivery, as seems to be referenced by the context of the question. The principle of continuous delivery is that of striving to reduce the Inventory waste as described in Lean thinking (http://www.miconleansixsigma.com/8-wastes.html). The practice of Continuous Delivery (CD) by agile teams has emerged in the many years since the Agile Manifesto was written in 2001. This agile practice directly addresses the principle, although they are different things and apparently easily confused.

How do I create a batch file timer to execute / call another batch throughout the day

The AT command would do that but that's what the Scheduled Tasks gui is for. Enter "help at" in a cmd window for details.

How can I make the Android emulator show the soft keyboard?

There is a bug in the new version of NOX app. Software keyboard doesn't work after switching to it in settings. To fix this, I installed Gboard using the Play Market.

Convert canvas to PDF

So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.

  // Download button
  $("#download-image").on('click', function () {
    let width = __CANVAS.width; 
    let height = __CANVAS.height;

    //set the orientation
    if(width > height){
      pdf = new jsPDF('l', 'px', [width, height]);
    }
    else{
      pdf = new jsPDF('p', 'px', [height, width]);
    }
    //then we get the dimensions from the 'pdf' file itself
    width = pdf.internal.pageSize.getWidth();
    height = pdf.internal.pageSize.getHeight();
    pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
    pdf.save("download.pdf");
  });

Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476

Parsing HTTP Response in Python

json works with Unicode text in Python 3 (JSON format itself is defined only in terms of Unicode text) and therefore you need to decode bytes received in HTTP response. r.headers.get_content_charset('utf-8') gets your the character encoding:

#!/usr/bin/env python3
import io
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r, \
     io.TextIOWrapper(r, encoding=r.headers.get_content_charset('utf-8')) as file:
    result = json.load(file)
print(result['headers']['User-Agent'])

It is not necessary to use io.TextIOWrapper here:

#!/usr/bin/env python3
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r:
    result = json.loads(r.read().decode(r.headers.get_content_charset('utf-8')))
print(result['headers']['User-Agent'])

How to force a component's re-rendering in Angular 2?

tx, found the workaround I needed:

  constructor(private zone:NgZone) {
    // enable to for time travel
    this.appStore.subscribe((state) => {
        this.zone.run(() => {
            console.log('enabled time travel');
        });
    });

running zone.run will force the component to re-render

Check if a given key already exists in a dictionary

You don't have to call keys:

if 'key1' in dict:
  print("blah")
else:
  print("boo")

That will be much faster as it uses the dictionary's hashing as opposed to doing a linear search, which calling keys would do.

How can I get a resource content from a static context?

I am using API level 27 and found a best solution after struggling for around two days. If you want to read a xml file from a class which doesn't derive from Activity or Application then do the following.

  1. Put the testdata.xml file inside the assets directory.

  2. Write the following code to get the testdata document parsed.

        InputStream inputStream = this.getClass().getResourceAsStream("/assets/testdata.xml");
    
        // create a new DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // use the factory to create a documentbuilder
        DocumentBuilder builder = factory.newDocumentBuilder();
        // create a new document from input stream
        Document doc = builder.parse(inputStream);
    

Route.get() requires callback functions but got a "object Undefined"

check your closing tags in your model, it may be that you have defined a callback in another callback

Turn a simple socket into an SSL socket

OpenSSL is quite difficult. It's easy to accidentally throw away all your security by not doing negotiation exactly right. (Heck, I've been personally bitten by a bug where curl wasn't reading the OpenSSL alerts exactly right, and couldn't talk to some sites.)

If you really want quick and simple, put stud in front of your program an call it a day. Having SSL in a different process won't slow you down: http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html

How to use SQL Select statement with IF EXISTS sub query?

You can also use ISNULL and a select statement to get this result

SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1

Getting first and last day of the current month

string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");

Bootstrap - dropdown menu not working?

Double importing jquery can cause Error

<script src="static/public/js/jquery/jquery.min.js"></script>

OR

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="" crossorigin="anonymous"></script>

how to read value from string.xml in android?

Solution 1

Context context;
String mess = context.getString(R.string.mess_1)

Solution 2

String mess = getString(R.string.mess_1)

Generating random numbers with normal distribution in Excel

IF you have excel 2007, you can use

=NORMSINV(RAND())*SD+MEAN

Because there was a big change in 2010 about excel's function

MySQLDump one INSERT statement for each data row

Use:

mysqldump --extended-insert=FALSE 

Be aware that multiple inserts will be slower than one big insert.

How can I get dict from sqlite query?

As mentioned by @gandalf's answer, one has to use conn.row_factory = sqlite3.Row, but the results are not directly dictionaries. One has to add an additional "cast" to dict in the last loop:

import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute('create table t (a text, b text, c text)')
conn.execute('insert into t values ("aaa", "bbb", "ccc")')
conn.execute('insert into t values ("AAA", "BBB", "CCC")')
conn.row_factory = sqlite3.Row
c = conn.cursor()
c.execute('select * from t')
for r in c.fetchall():
    print(dict(r))

# {'a': 'aaa', 'b': 'bbb', 'c': 'ccc'}
# {'a': 'AAA', 'b': 'BBB', 'c': 'CCC'}

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

  • LDPI: Portrait: 200 X 320px. Landscape: 320 X 200px.
  • MDPI: Portrait: 320 X 480px. Landscape: 480 X 320px.
  • HDPI: Portrait: 480 X 800px. Landscape: 800 X 480px.
  • XHDPI: Portrait: 720 X 1280px. Landscape: 1280 X 720px.
  • XXHDPI: Portrait: 960 X 1600px. Landscape: 1600 X 960px.
  • XXXHDPI: Portrait: 1280 X 1920px. Landscape: 1920 X 1280px.

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.

From Books Online, on MAXDOP:

Sets the maximum number of processors the query processor can use to execute a single index statement. Fewer processors may be used depending on the current system workload.

See Rickie Lee's blog on parallelism and CXPACKET wait type. It's quite interesting.

Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.

Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.

Accessing all items in the JToken

You can cast your JToken to a JObject and then use the Properties() method to get a list of the object properties. From there, you can get the names rather easily.

Something like this:

string json =
@"{
    ""ADDRESS_MAP"":{

        ""ADDRESS_LOCATION"":{
            ""type"":""separator"",
            ""name"":""Address"",
            ""value"":"""",
            ""FieldID"":40
        },
        ""LOCATION"":{
            ""type"":""locations"",
            ""name"":""Location"",
            ""keyword"":{
                ""1"":""LOCATION1""
            },
            ""value"":{
                ""1"":""United States""
            },
            ""FieldID"":41
        },
        ""FLOOR_NUMBER"":{
            ""type"":""number"",
            ""name"":""Floor Number"",
            ""value"":""0"",
            ""FieldID"":55
        },
        ""self"":{
            ""id"":""2"",
            ""name"":""Address Map""
        }
    }
}";

JToken outer = JToken.Parse(json);
JObject inner = outer["ADDRESS_MAP"].Value<JObject>();

List<string> keys = inner.Properties().Select(p => p.Name).ToList();

foreach (string k in keys)
{
    Console.WriteLine(k);
}

Output:

ADDRESS_LOCATION
LOCATION
FLOOR_NUMBER
self

Create a temporary table in a SELECT statement without a separate CREATE TABLE

ENGINE=MEMORY is not supported when table contains BLOB/TEXT columns

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

Django error - matching query does not exist

your line raising the error is here:

comment = Comment.objects.get(pk=comment_id)

you try to access a non-existing comment.

from django.shortcuts import get_object_or_404

comment = get_object_or_404(Comment, pk=comment_id)

Instead of having an error on your server, your user will get a 404 meaning that he tries to access a non existing resource.

Ok up to here I suppose you are aware of this.

Some users (and I'm part of them) let tabs running for long time, if users are authorized to delete data, it may happens. A 404 error may be a better error to handle a deleted resource error than sending an email to the admin.

Other users go to addresses from their history, (same if data have been deleted since it may happens).

Should I use <i> tag for icons instead of <span>?

My guess: Because Twitter sees the need to support legacy browsers, otherwise they would be using the :before / :after pseudo-elements.

Legacy browsers don't support those pseudo-elements I mentioned, so they need to use an actual HTML element for the icons, and since icons don't have an 'exclusive' tag, they just went with the <i> tag, and all browsers support that tag.

They could've certainly used a <span>, just like you are (which is TOTALLY fine), but probably for the reason I mentioned above plus the ones mentioned by Quentin, is also why Bootstrap is using the <i> tag.

It's a bad practice when you use extra markup for styling reasons, that's why pseudo-elements were invented, to separate content from style... but when you see the need to support legacy browsers, sometimes you're forced to do these kind of things.

PS. The fact that icons start with an 'i' and that there's an <i> tag, is completely coincidental.

Check if checkbox is NOT checked on click - jQuery

Try this:

if(!$(this).is(':checked'))

demo

Unique random string generation

  • not sure Microsoft's link are randomly generated
  • have a look to new Guid().ToString()

Export data from Chrome developer tool

To get this in excel or csv format- right click the folder and select "copy response"- paste to excel and use text to columns.

Debugging in Maven?

I found an easy way to do this -

Just enter a command like this -

>mvn -Dtest=TestClassName#methodname -Dmaven.surefire.debug test

It will start listening to 5005 port. Now just create a remote debugging in Eclipse through Debug Configurations for localhost(any host) and port 5005.

Source - https://doc.nuxeo.com/display/CORG/How+to+Debug+a+Test+Run+with+Maven

Bootstrap 4 Center Vertical and Horizontal Alignment

From the doc (bootsrap 4):

https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content

.justify-content-start
.justify-content-end
.justify-content-center
.justify-content-between
.justify-content-around
.justify-content-sm-start
.justify-content-sm-end
.justify-content-sm-center
.justify-content-sm-between
.justify-content-sm-around
.justify-content-md-start
.justify-content-md-end
.justify-content-md-center
.justify-content-md-between
.justify-content-md-around
.justify-content-lg-start
.justify-content-lg-end
.justify-content-lg-center
.justify-content-lg-between
.justify-content-lg-around
.justify-content-xl-start
.justify-content-xl-end
.justify-content-xl-center
.justify-content-xl-between
.justify-content-xl-around

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.

NuGet- > Install-Package Newtonsoft.Json

PHP ternary operator vs null coalescing operator

Both of them behave differently when it comes to dynamic data handling.

If the variable is empty ( '' ) the null coalescing will treat the variable as true but the shorthand ternary operator won't. And that's something to have in mind.

$a = NULL;
$c = '';

print $a ?? '1b';
print "\n";

print $a ?: '2b';
print "\n";

print $c ?? '1d';
print "\n";

print $c ?: '2d';
print "\n";

print $e ?? '1f';
print "\n";

print $e ?: '2f';

And the output:

1b
2b

2d
1f

Notice: Undefined variable: e in /in/ZBAa1 on line 21
2f

Link: https://3v4l.org/ZBAa1

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

public class MainActivity extends Activity
        implements View.OnClickListener {
    private Button btnForward, btnBackword, btnPause, btnPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initControl();
    }

    private void initControl() {
        btnForward = (Button) findViewById(R.id.btnForward);
        btnBackword = (Button) findViewById(R.id.btnBackword);
        btnPause = (Button) findViewById(R.id.btnPause);
        btnPlay = (Button) findViewById(R.id.btnPlay);
        btnForward.setOnClickListener(this);
        btnBackword.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnForward:
                break;
            case R.id.btnBackword:
                break;
            case R.id.btnPause:
                break;
            case R.id.btnPlay:
                break;
        }
    }
}

Array formula on Excel for Mac

Found a solution to Excel Mac2016 as having to paste the code into the relevant cell, enter, then go to the end of the formula within the header bar and enter the following:

Enter a formula as an array formula Image + SHIFT + RETURN or CONTROL + SHIFT + RETURN

Notice: Array to string conversion in

The problem is that $money is an array and you are treating it like a string or a variable which can be easily converted to string. You should say something like:

 '.... Money:'.$money['money']

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

How to sort an array in Bash

array=(a c b f 3 5)
new_array=($(echo "${array[@]}" | sed 's/ /\n/g' | sort))    
echo ${new_array[@]}

echo contents of new_array will be:

3 5 a b c f

C/C++ macro string concatenation

Hint: The STRINGIZE macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include the header file - then the compiler will happily put the purported macro name into the string with no error.

If you intend that the argument to STRINGIZE is always a macro with a normal C value, then

#define STRINGIZE(A) ((A),STRINGIZE_NX(A))

will expand it once and check it for validity, discard that, and then expand it again into a string.

It took me a while to figure out why STRINGIZE(ENOENT) was ending up as "ENOENT" instead of "2"... I hadn't included errno.h.

How to view the committed files you have not pushed yet?

The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.

So if you are like me who work in a branch, here are tips:

  1. Say you are already on a branch. If not, git checkout that branch
  2. git log # to show a list of commit such as x08d46ffb1369e603c46ae96, You need only the latest commit which comes first.
  3. git show --name-only x08d46ffb1369e603c46ae96 # to show the files commited
  4. git show x08d46ffb1369e603c46ae96 # show the detail diff of each changed file

Or more simply, just use HEAD:

  1. git show --name-only HEAD # to show a list of files committed
  2. git show HEAD # to show the detail diff.

Code not running in IE 11, works fine in Chrome

Follow this method if problem comes when working with angular2+ projects

I was looking for a solution when i got this error, and it got me here. But this question seems to be specific but the error is not, its a generic error. This is a common error for angular developers dealing with Internet Explorer.

I had the same issue while working with angular 2+, and it got resolved just by few simple steps.

In Angular latest versions, there are come commented codes in the polyfills.ts shows all the polyfills required for the smooth running in Internet Explorer versions IE09,IE10 and IE11

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
//import 'core-js/es6/symbol';
//import 'core-js/es6/object';
//import 'core-js/es6/function';
//import 'core-js/es6/parse-int';
//import 'core-js/es6/parse-float';
//import 'core-js/es6/number';
//import 'core-js/es6/math';
//import 'core-js/es6/string';
//import 'core-js/es6/date';
//import 'core-js/es6/array';
//import 'core-js/es6/regexp';
//import 'core-js/es6/map';
//import 'core-js/es6/weak-map';
//import 'core-js/es6/set';

Uncomment the codes and it would work perfectly in IE browsers

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';

But you might see a performance drop in IE browsers compared to others :(

C++ string to double conversion

If you are reading from a file then you should hear the advice given and just put it into a double.

On the other hand, if you do have, say, a string you could use boost's lexical_cast.

Here is a (very simple) example:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}

How can I make all images of different height and width the same via CSS?

Go to your CSS file and resize all your images as follows

img {
  width:  100px;
  height: 100px;
}

How to prevent scientific notation in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation (?options):

‘scipen’: integer.  A penalty to be applied when deciding to print
          numeric values in fixed or exponential notation.  Positive
          values bias towards fixed and negative towards scientific
          notation: fixed notation will be preferred unless it is more
          than ‘scipen’ digits wider.

So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999:

options(scipen=999)

Properly Handling Errors in VBA (Excel)

I keep things simple:
At the module level I define two variables and set one to the name of the module itself.

    Private Const ThisModuleName            As String = "mod_Custom_Functions"
    Public sLocalErrorMsg                   As String

Within each Sub/Function of the module I define a local variable

    Dim ThisRoutineName                     As String

I set ThisRoutineName to the name of the sub or function

' Housekeeping
    On Error Goto ERR_RTN
    ThisRoutineName = "CopyWorksheet"

I then send all errors to an ERR_RTN: when they occur, but I first set the sLocalErrorMsg to define what the error actually is and provide some debugging info.

    If Len(Trim(FromWorksheetName)) < 1 Then
        sLocalErrorMsg = "Parameter 'FromWorksheetName' Is Missing."
        GoTo ERR_RTN
    End If

At the bottom of each sub/function, I direct the logic flow as follows

    '
    ' The "normal" logic goes here for what the routine does
    '
    GoTo EXIT_RTN

    ERR_RTN:

        On Error Resume Next

    ' Call error handler if we went this far.
        ErrorHandler ThisModuleName, ThisRoutineName, sLocalErrorMsg, Err.Description, Err.Number, False

    EXIT_RTN:

        On Error Resume Next
     '
     ' Some closing logic
     '
    End If

I then have a seperate module I put in all projects called "mod_Error_Handler".

    '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Subroutine Name:     ErrorHandler                                                     '
    '                                                                                       '
    ' Description:                                                                          '
    '   This module will handle the common error alerts.                                    '
    '                                                                                       '
    ' Inputs:                                                                               '
    '   ModuleName                String    'The name of the module error is in.            '
    '   RoutineName               String    'The name of the routine error in in.           '
    '   LocalErrorMsg             String    'A local message to assist with troubleshooting.'
    '   ERRDescription            String    'The Windows Error Description.                 '
    '   ERRCode                   Long      'The Windows Error Code.                        '
    '   Terminate                 Boolean   'End program if error encountered?              '
    '                                                                                       '
    ' Revision History:                                                                     '
    ' Date (YYYYMMDD) Author                Change                                          '
    ' =============== ===================== =============================================== '
    ' 20140529        XXXXX X. XXXXX        Original                                        '
    '                                                                                       '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '
    Public Sub ErrorHandler(ModuleName As String, RoutineName As String, LocalErrorMsg As String, ERRDescription As String, ERRCode As Long, Terminate As Boolean)
        Dim sBuildErrorMsg                 As String

    ' Build Error Message To Display
        sBuildErrorMsg = "Error Information:" & vbCrLf & vbCrLf

        If Len(Trim(ModuleName)) < 1 Then
            ModuleName = "Unknown"
        End If

        If Len(Trim(RoutineName)) < 1 Then
           RoutineName = "Unknown"
        End If

        sBuildErrorMsg = sBuildErrorMsg & "Module Name:        " & ModuleName & vbCrLf & vbCrLf
        sBuildErrorMsg = sBuildErrorMsg & "Routine Name:       " & RoutineName & vbCrLf & vbCrLf

        If Len(Trim(LocalErrorMsg)) > 0 Then
            sBuildErrorMsg = sBuildErrorMsg & "Local Error Msg:    " & LocalErrorMsg & vbCrLf & vbCrLf
        End If

        If Len(Trim(ERRDescription)) > 0 Then
            sBuildErrorMsg = sBuildErrorMsg & "Program Error Msg:  " & ERRDescription & vbCrLf & vbCrLf
            If IsNumeric(ERRCode) Then
                sBuildErrorMsg = sBuildErrorMsg & "Program Error Code: " & Trim(Str(ERRCode)) & vbCrLf & vbCrLf
            End If
        End If

        MsgBox sBuildErrorMsg, vbOKOnly + vbExclamation, "Error Detected!"

        If Terminate Then
            End
        End If

    End Sub

The end result is a pop-up error message teling me in what module, what soubroutine, and what the error message specifically was. In addition, it also will insert the Windows error message and code.

Set Colorbar Range in matplotlib

Using vmin and vmax forces the range for the colors. Here's an example:

enter image description here

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )

def do_plot(n, f, title):
    #plt.clf()
    plt.subplot(1, 3, n)
    plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4)
    plt.title(title)
    plt.colorbar()

plt.figure()
do_plot(1, lambda x:x, "all")
do_plot(2, lambda x:np.clip(x, -4, 0), "<0")
do_plot(3, lambda x:np.clip(x, 0, 4), ">0")
plt.show()

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

Somewhere, you need to tell Apache that people are allowed to see contents of this directory.

<Directory "F:/bar/public">
    Order Allow,Deny
    Allow from All
    # Any other directory-specific stuff
</Directory>

More info

How do I change the formatting of numbers on an axis with ggplot?

x <- rnorm(10) * 100000
y <- seq(0, 1, length = 10)
p <- qplot(x, y)
library(scales)
p + scale_x_continuous(labels = comma)