Programs & Examples On #Perlsections

Can PHP cURL retrieve response headers AND body in a single request?

Try this if you are using GET:

$curl = curl_init($url);

curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Cache-Control: no-cache"
    ),
));

$response = curl_exec($curl);
curl_close($curl);

Representational state transfer (REST) and Simple Object Access Protocol (SOAP)

Well I'll begin with the second question: What are Web Services? , for obvious reasons.

WebServices are essentially pieces of logic(which you may vaguely refer to as a method) that expose certain functionality or data. The client implementing(technically speaking, consuming is the word) just needs to know what are the parameter(s) the method is going to accept and the type of data it is going to return(if at all it does).

The following Link says it all about REST & SOAP in an extremely lucid manner.

REST vs SOAP

If you also want to know when to choose what (REST or SOAP), all the more reason to go through it!

How to download and save an image in Android

public class testCrop extends AppCompatActivity {
    ImageView iv;
    String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testcrpop);
        iv = (ImageView) findViewById(R.id.testCrop);
        imageDownload image = new imageDownload(testCrop.this, iv);
        image.execute(imagePath);
    }
    class imageDownload extends AsyncTask<String, Integer, Bitmap> {
        Context context;
        ImageView imageView;
        Bitmap bitmap;
        InputStream in = null;
        int responseCode = -1;
//constructor.
        public imageDownload(Context context, ImageView imageView) {
            this.context = context;
            this.imageView = imageView;
        }
        @Override
        protected void onPreExecute() {
        }
        @Override
        protected Bitmap doInBackground(String... params) {
            try {
                URL url = new URL(params[0]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setDoOutput(true);
                httpURLConnection.connect();
                responseCode = httpURLConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    in = httpURLConnection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(in);
                    in.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }
        @Override
        protected void onPostExecute(Bitmap data) {
            imageView.setImageBitmap(data);
            saveImage(data);
        }

        private void saveImage(Bitmap data) {
            File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
            createFolder.mkdir();
            File saveImage = new File(createFolder,"downloadimage.jpg");
            try {
                OutputStream outputStream = new FileOutputStream(saveImage);
                data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
                outputStream.flush();
                outputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

OUTPUTenter image description here

Make sure you added permission to write data in memory

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Why do you use typedef when declaring an enum in C++?

In some C codestyle guide the typedef version is said to be preferred for "clarity" and "simplicity". I disagree, because the typedef obfuscates the real nature of the declared object. In fact, I don't use typedefs because when declaring a C variable I want to be clear about what the object actually is. This choice helps myself to remember faster what an old piece of code actually does, and will help others when maintaining the code in the future.

How to set the component size with GridLayout? Is there a better way?

In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.

First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.

JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));

I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.

for (int i = 0; i < numberOfParams; ++i) {
    yourSettingsPanel.add(labels[i]);
    yourSettingsPanel.add(components[i]);
}

To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.

JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);

Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.

JScrollPane scroll = new JScrollPane(northOnlyPanel,
                                     JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                     JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:

window.add(scroll, BorderLayout.CENTER);

In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.

JTextArea help = new JTextArea();
help.setLineWrap(true);
help.setWrapStyleWord(true);
help.setEditable(false);

JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));
split.add(scroll);
split.add(help);

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

How can I use a batch file to write to a text file?

echo "blahblah"> txt.txt will erase the txt and put blahblah in it's place

echo "blahblah">> txt.txt will write blahblah on a new line in the txt

I think that both will create a new txt if none exists (I know that the first one does)

Where "txt.txt" is written above, a file path can be inserted if wanted. e.g. C:\Users\<username>\desktop, which will put it on their desktop.

Default Xmxsize in Java 8 (max heap size)

On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize printed : uintx MaxHeapSize := 266338304, which is approx 266MB and is 1/4th of my total RAM.

Android: Align button to bottom-right of screen using FrameLayout?

If you want to try with java code. Here you go -

    final LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, 
                                             LayoutParams.WRAP_CONTENT);
    yourView.setLayoutParams(params);
    params.gravity = Gravity.BOTTOM; // set gravity

How to use a client certificate to authenticate and authorize in a Web API

I came upon a similar issue recently and following Fabian's advice actually led me to the solution. Turns out with client certs you have to ensure two things:

  1. The private key is actually being exported as part of the cert.

  2. The application pool identity running the app has access to said private key.

In our case I had to:

  1. Import the pfx file into the local server store while checking the export checkbox to ensure the private key was sent out.
  2. Using MMC console, grant the service account used access to the private key for the cert.

The trusted root issue explained in other answers is a valid one, it was just not the issue in our case.

SQL Plus change current directory

Could you use the SQLPATH environment variable to tell sqlplus where to look for the scripts you are trying to run? I believe you could use HOST to set SQLPATH in the script too.

There could potentially be problems if two scripts have the same name and both directories are in the SQLPATH.

How to remove trailing whitespace in code, using another script?

It's a bit surprising seeing multiple answers suggesting to use python for this task, as there's no need to write a multi-line program for this.

Standard Unix tools like sed, awk or perl can achieve this easily straight from the command-line.

e.g anywhere you have perl (Windows, Mac, Linux) the following should achieve what the OP asked:

perl -i -pe 's/[ \t]+$//;' files...

Explanation of the arguments to perl:

-i   # run the edit "in place" (modify the original file)
-p   # implies a loop with a final print over every input line
-e   # next arg is the perl expression to apply (to every line)

s/[ \t]$// is a substitution regex s/FROM/TO/: replace every trailing (end of line) non-empty space (spaces or tabs) with nothing.

Advantages:

  • One liner, no programming needed
  • Works on multiple (any number) of files
  • Works correctly on standard-input (no file arguments given)

Edit:

Newer versions of perl support \h (any horizontal-space character), so the solution becomes even shorter:

perl -i -pe 's/\h+$//;' files...

More generally, if you want to modify any number of files directly from the command line, replacing every appearance of FOO with BAR, you may always use this generic template:

perl -i -pe 's/FOO/BAR/' files...

How do I find ' % ' with the LIKE operator in SQL Server?

I would use

WHERE columnName LIKE '%[%]%'

SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.

The response to this Connect Item states

We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.

An example

CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)

CREATE NONCLUSTERED INDEX IX ON T(X)

INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT  TOP (100000)  'blah'
FROM master..spt_values v1,  master..spt_values v2


SET STATISTICS IO ON;
SELECT *
FROM T 
WHERE X LIKE '%[%]%'

SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'

Shows 457 logical reads for the first query and 33,335 for the second.

How to declare a vector of zeros in R

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

jquery fill dropdown with json data

If your data is already in array form, it's really simple using jQuery:

 $(data.msg).each(function()
 {
     alert(this.value);
     alert(this.label);

     //this refers to the current item being iterated over

     var option = $('<option />');
     option.attr('value', this.value).text(this.label);

     $('#myDropDown').append(option);
 });

.ajax() is more flexible than .getJSON() - for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().

Django request.GET

q = request.GET.get("q", None)
if q:
    message = 'q= %s' % q
else:
    message = 'Empty'

Input type "number" won't resize

What you want is maxlength.

Valid for text, search, url, tel, email, and password, it defines the maximum number of characters (as UTF-16 code units) the user can enter into the field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the field has no maximum length. This value must also be greater than or equal to the value of minlength.

You might consider using one of these input types.

What are forward declarations in C++?

int add(int x, int y); // forward declaration using function prototype

Can you explain "forward declaration" more further? What is the problem if we use it in the main() function?

It's same as #include"add.h". If you know,preprocessor expands the file which you mention in #include, in the .cpp file where you write the #include directive. That means, if you write #include"add.h", you get the same thing, it is as if you doing "forward declaration".

I'm assuming that add.h has this line:

int add(int x, int y); 

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

Can one do a for each loop in java in reverse order?

As of the comment: You should be able to use Apache Commons ReverseListIterator

Iterable<String> reverse 
    = new IteratorIterable(new ReverseListIterator(stringList));

for(String string: reverse ){
    //...do something
}

As @rogerdpack said, you need to wrap the ReverseListIterator as an Iterable.

How to find a number in a string using JavaScript?

_x000D_
_x000D_
var regex = /\d+/g;_x000D_
var string = "you can enter maximum 500 choices";_x000D_
var matches = string.match(regex);  // creates array from matches_x000D_
_x000D_
document.write(matches);
_x000D_
_x000D_
_x000D_


References:

    http://www.regular-expressions.info/javascript.html

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Splitting templated C++ classes into .hpp/.cpp files--is it possible?

You can do it in this way

// xyz.h
#ifndef _XYZ_
#define _XYZ_

template <typename XYZTYPE>
class XYZ {
  //Class members declaration
};

#include "xyz.cpp"
#endif

//xyz.cpp
#ifdef _XYZ_
//Class definition goes here

#endif

This has been discussed in Daniweb

Also in FAQ but using C++ export keyword.

Getting a machine's external IP address with Python

If the machine is being a firewall then your solution is a very sensible one: the alternative being able to query the firewall which ends-up being very dependent on the type of firewall (if at all possible).

Adding quotes to a string in VBScript

You have to use double double quotes to escape the double quotes (lol):

g = "abcd """ & a & """"

How to encode text to base64 in python

To compatibility with both py2 and py3

import six
import base64

def b64encode(source):
    if six.PY3:
        source = source.encode('utf-8')
    content = base64.b64encode(source).decode('utf-8')

.NET - Get protocol, host, and port

A more structured way to get this is to use UriBuilder. This avoids direct string manipulation.

var builder = new UriBuilder(Request.Url.Scheme, Request.Url.Host, Request.Url.Port);

How to set-up a favicon?

Below given some information about fav Icon

What Is FavIcon? ? FavIcon is nothing but small image which appears top left along with the application address bar title.Standard size specification for favicon.ico is 16 by 16 pixel. Please see below attached figure.

enter image description here

How It Works ? ? Usually we add our FavIcon.ico image in the route solution folder and automatically application picks it while running. But most of the time we might have to use below both link reference.

               <link rel="icon" href="favicon.ico" type="image/ico"/>
               <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>

Some browser expect one (rel="icon") Some other browser expect other rel="shortcut icon"

? Type=”image/x-icon” OR Type=”image/ico”: once expect exact ico image and one expect any image even formatted from .jpg or .pn ..etc.

? We have to use above two tags to the common pages like – Master page , Main frame which is getting used in all the pages

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Convert JSON String to JSON Object c#

You can try like following:

string output = JsonConvert.SerializeObject(jsonStr);

Run MySQLDump without Locking Tables

The answer varies depending on what storage engine you're using. The ideal scenario is if you're using InnoDB. In that case you can use the --single-transaction flag, which will give you a coherent snapshot of the database at the time that the dump begins.

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

The ngRoute module is no longer part of the core angular.js file. If you are continuing to use $routeProvider then you will now need to include angular-route.js in your HTML:

<script src="angular.js">
<script src="angular-route.js">

API Reference

You also have to add ngRoute as a dependency for your application:

var app = angular.module('MyApp', ['ngRoute', ...]);

If instead you are planning on using angular-ui-router or the like then just remove the $routeProvider dependency from your module .config() and substitute it with the relevant provider of choice (e.g. $stateProvider). You would then use the ui.router dependency:

var app = angular.module('MyApp', ['ui.router', ...]);

What is the intended use-case for git stash?

I will break answer on three paragraphs.

Part 1:

git stash (To save your un-committed changes in a "stash". Note: this removes changes from working tree!)

git checkout some_branch (change to intended branch -- in this case some_branch)

git stash list (list stashes)

You can see:
stash@{0}: WIP on {branch_name}: {SHA-1 of last commit} {last commit of you branch}
stash@{0}: WIP on master: 085b095c6 modification for test

git stash apply (to apply stash to working tree in current branch)

git stash apply stash@{12} (if you will have many stashes you can choose what stash will apply -- in this case we apply stash 12)

git stash drop stash@{0} (to remove from stash list -- in this case stash 0)

git stash pop stash@{1} (to apply selected stash and drop it from stash list)

Part 2:
You can hide your changes with this command but it is not necessary.
You can continue on the next day without stash.
This commands for hide your changes and work on different branches or for implementation some realisation of your code and save in stashes without branches and commitsor your custom case!
And later you can use some of stashes and check wich is better.

Part 3:
Stash command for local hide your changes.
If you want work remotely you must commit and push.

How to save as a new file and keep working on the original one in Vim?

The following command will create a copy in a new window. So you can continue see both original file and the new file.

:w {newfilename} | sp #

Comparing two byte arrays in .NET

This is almost certainly much slower than any other version given here, but it was fun to write.

static bool ByteArrayEquals(byte[] a1, byte[] a2) 
{
    return a1.Zip(a2, (l, r) => l == r).All(x => x);
}

Error:Unable to locate adb within SDK in Android Studio

In my case I had no SDK selected for my project(not sure why). Simply went to Project Structure dialog (alt+ctrl+shift+s or button 1 on the screen) and then to project-> Project SDK's was selected <no SDK>. Just changed it to the latest

Project Structure dialog

How to convert int[] into List<Integer> in Java?

Here is a solution:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));

List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);

Output:

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

Max or Default?

Another possibility would be grouping, similar to how you might approach it in raw SQL:

from y in context.MyTable
group y.MyCounter by y.MyField into GrpByMyField
where GrpByMyField.Key == value
select GrpByMyField.Max()

The only thing is (testing again in LINQPad) switching to the VB LINQ flavor gives syntax errors on the grouping clause. I'm sure the conceptual equivalent is easy enough to find, I just don't know how to reflect it in VB.

The generated SQL would be something along the lines of:

SELECT [t1].[MaxValue]
FROM (
    SELECT MAX([t0].[MyCounter) AS [MaxValue], [t0].[MyField]
    FROM [MyTable] AS [t0]
    GROUP BY [t0].[MyField]
    ) AS [t1]
WHERE [t1].[MyField] = @p0

The nested SELECT looks icky, like the query execution would retrieve all rows then select the matching one from the retrieved set... the question is whether or not SQL Server optimizes the query into something comparable to applying the where clause to the inner SELECT. I'm looking into that now...

I'm not well-versed in interpreting execution plans in SQL Server, but it looks like when the WHERE clause is on the outer SELECT, the number of actual rows resulting in that step is all rows in the table, versus only the matching rows when the WHERE clause is on the inner SELECT. That said, it looks like only 1% cost is shifted to the following step when all rows are considered, and either way only one row ever comes back from the SQL Server so maybe it's not that big of a difference in the grand scheme of things.

Finish an activity from another activity

This is a fairly standard communication question. One approach would be to use a ResultReceiver in Activity A:

Intent GotoB=new Intent(A.this,B.class);
GotoB.putExtra("finisher", new ResultReceiver(null) {
    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        A.this.finish();
    }
});
startActivityForResult(GotoB,1);

and then in Activity B you can just finish it on demand like so:

((ResultReceiver)getIntent().getExtra("finisher")).send(1, new Bundle());

Try something like that.

Cannot obtain value of local or argument as it is not available at this instruction pointer, possibly because it has been optimized away

If you compile with optimizations enabled, then many variables will be removed; for example:

SomeType value = GetValue();
DoSomething(value);

here the local variable value would typically get removed, keeping the value on the stack instead - a bit like as if you had written:

DoSomething(GetValue());

Also, if a return value isn't used at all, then it will be dropped via "pop" (rather than stored in a local via "stloc", and again; the local will not exist).

Because of this, in such a build the debugger can't get the current value of value because it doesn't exist - it only exists for the brief instant between GetValue() and DoSomething(...).

So; if you want to debug... don't use a release build! or at least, disable optimizations while you debug.

Using AND/OR in if else PHP statement

AND is && and OR is || like in C.

Forking / Multi-Threaded Processes | Bash

Based on what you all shared I was able to put this together:

#!/usr/bin/env bash

VAR1="192.168.1.20 192.168.1.126 192.168.1.36"

for a in $VAR1; do { ssh -t -t $a -l Administrator "sudo softwareupdate -l"; } & done;
WAITPIDS="$WAITPIDS "$!;...; wait $WAITPIDS
echo "Script has finished"

Exit 1

This lists all the updates on the mac on three machines at once. Later on I used it to perform a software update for all machines when i CAT my ipaddress.txt

Read text file into string. C++ ifstream

It looks like you are trying to parse each line. You've been shown by another answer how to use getline in a loop to seperate each line. The other tool you are going to want is istringstream, to seperate each token.

std::string line;
while(std::getline(file, line))
{
    std::istringstream iss(line);
    std::string token;
    while (iss >> token)
    {
        // do something with token
    }
}

JQuery - Set Attribute value

"True" and "False" do not work, to disable, set to value disabled.

$('.someElement').attr('disabled', 'disabled');

To enable, remove.

$('.someElement').removeAttr('disabled');

Also, don't worry about multiple items being selected, jQuery will operate on all of them that match. If you need just one you can use many things :first, :last, nth, etc.

You are using name and not id as other mention -- remember, if you use id valid xhtml requires the ids be unique.

How to grep a text file which contains some binary data?

You can also try Word Extractor tool. Word Extractor can be used with any file in your computer to separate the strings that contain human text / words from binary code (exe applications, DLLs).

How to debug "ImagePullBackOff"?

You can use the 'describe pod' syntax

For OpenShift use:

oc describe pod <pod-id>  

For vanilla Kubernetes:

kubectl describe pod <pod-id>  

Examine the events of the output. In my case it shows Back-off pulling image coredns/coredns:latest

In this case the image coredns/coredns:latest can not be pulled from the Internet.

Events:
  FirstSeen LastSeen    Count   From                SubObjectPath           Type        Reason      Message
  --------- --------    -----   ----                -------------           --------    ------      -------
  5m        5m      1   {default-scheduler }                        Normal      Scheduled   Successfully assigned coredns-4224169331-9nhxj to 192.168.122.190
  5m        1m      4   {kubelet 192.168.122.190}   spec.containers{coredns}    Normal      Pulling     pulling image "coredns/coredns:latest"
  4m        26s     4   {kubelet 192.168.122.190}   spec.containers{coredns}    Warning     Failed      Failed to pull image "coredns/coredns:latest": Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your internet connection or if you are behind a proxy.
  4m        26s     4   {kubelet 192.168.122.190}                   Warning     FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ErrImagePull: "Network timed out while trying to connect to https://index.docker.io/v1/repositories/coredns/coredns/images. You may want to check your Internet connection or if you are behind a proxy."

  4m    2s  7   {kubelet 192.168.122.190}   spec.containers{coredns}    Normal  BackOff     Back-off pulling image "coredns/coredns:latest"
  4m    2s  7   {kubelet 192.168.122.190}                   Warning FailedSync  Error syncing pod, skipping: failed to "StartContainer" for "coredns" with ImagePullBackOff: "Back-off pulling image \"coredns/coredns:latest\""

Additional debuging steps

  1. try to pull the docker image and tag manually on your computer
  2. Identify the node by doing a 'kubectl/oc get pods -o wide'
  3. ssh into the node (if you can) that can not pull the docker image
  4. check that the node can resolve the DNS of the docker registry by performing a ping.
  5. try to pull the docker image manually on the node
  6. If you are using a private registry, check that your secret exists and the secret is correct. Your secret should also be in the same namespace. Thanks swenzel
  7. Some registries have firewalls that limit ip address access. The firewall may block the pull
  8. Some CIs create deployments with temporary docker secrets. So the secret expires after a few days (You are asking for production failures...)

How to set String's font size, style in Java using the Font class?

Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29

JComponent has a setFont() method. You will control the font there, not on the String.

Such as

JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Sublime Text 3 how to change the font size of the file sidebar?

You need to change it at "class": "sidebar_label" Example, in your .sublime-theme file:

// Sidebar entry
{
    "class": "sidebar_label",
    "color": [212, 212, 213],
    "shadow_offset": [0, 0],
    "font.size":13
}

Credit

How to pass a user / password in ansible command

When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).

Never used the feature but the docs say you can.

How to draw a line in android

for horizontal line on the layout :

 <View
            android:id="@+id/View03"
            android:layout_width="fill_parent"
            android:layout_height="5dip"
            android:background="#0f0" />

for vertical line on the layout :

<View
        android:id="@+id/View04"
        android:layout_width="5dip"
        android:layout_height="fill_parent"
        android:background="#0f0" />

Select element based on multiple classes

Chain selectors are not limited just to classes, you can do it for both classes and ids.

Classes

.classA.classB {
/*style here*/
}

Class & Id

.classA#idB {
/*style here*/
}

Id & Id

#idA#idB {
/*style here*/
}

All good current browsers support this except IE 6, it selects based on the last selector in the list. So ".classA.classB" will select based on just ".classB".

For your case

li.left.ui-class-selector {
/*style here*/
}

or

.left.ui-class-selector {
/*style here*/
}

How do you set autocommit in an SQL Server session?

With SQLServer 2005 Express, what I found was that even with autocommit off, insertions into a Db table were committed without my actually issuing a commit command from the Management Studio session. The only difference was, when autocommit was off, I could roll back all the insertions; with *autocommit on, I could not.* Actually, I was wrong. With autocommit mode off, I see the changes only in the QA (Query Analyzer) window from which the commands were issued. If I popped a new QA (Query Analyzer) window, I do not see the changes made by the first window (session), i.e. they are NOT committed! I had to issue explicit commit or rollback commands to make changes visible to other sessions(QA windows) -- my bad! Things are working correctly.

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

In my case (Spring MVC + Hibernate project), I added Controller, Service, Dao, Model class & Thyme leaf page. Just didn't map new model class in "hibernate.cfg.xml" file. So that got this error. But after mapping new model class again got the error. Then deleted Controller, Service, Dao, Model class. Thyme leaf page and Created newly. Also mapped new model class. Then error has gone.

"VT-x is not available" when I start my Virtual machine

Are you sure your processor supports Intel Virtualization (VT-x) or AMD Virtualization (AMD-V)?

Here you can find Hardware-Assisted Virtualization Detection Tool ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ee2a17f-8538-4619-8d1c-05d27e11adb2&displaylang=en) which will tell you if your hardware supports VT-x.

Alternatively you can find your processor here: http://ark.intel.com/Default.aspx. All AMD processors since 2006 supports Virtualization.

Only get hash value using md5sum (without filename)

md5sum puts backslash before hash if there is backslash in file name. First 32 characters or anything before first space may not be a proper hash. It will not happen when using standard input (file name will be just -), so pixelbeat's answer will work, but many others will require adding something like | tail -c 32.

How to select between brackets (or quotes or ...) in Vim?

A simple keymap in vim would solve this issue. map viq F”lvf”hh This above command maps viq to the keys to search between quotes. Replace " with any character and create your keymaps. Stick this in vimrc during startup and you should be able to use it everytime.

ORA-01438: value larger than specified precision allows for this column

This indicates you are trying to put something too big into a column. For example, you have a VARCHAR2(10) column and you are putting in 11 characters. Same thing with number.

This is happening at line 176 of package UMAIN. You would need to go and have a look at that to see what it is up to. Hopefully you can look it up in your source control (or from user_source). Later versions of Oracle report this error better, telling you which column and what value.

How to expand/collapse a diff sections in Vimdiff?

Actually if you do Ctrl+W W, you won't need to add that extra Ctrl. Does the same thing.

AngularJS: Service vs provider vs factory

Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)

SERVICE:

Syntax:

app.js

 var app = angular.module('ServiceExample',[]);
 var serviceExampleController =
              app.controller('ServiceExampleController', ServiceExampleController);
 var serviceExample = app.service('NameOfTheService', NameOfTheService);

 ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files

function ServiceExampleController(NameOfTheService){
     serviceExampleController = this;
     serviceExampleController.data = NameOfTheService.getSomeData();
 }

function NameOfTheService(){
     nameOfTheService = this;
     nameOfTheService.data = "Some Data";
     nameOfTheService.getSomeData = function(){
           return nameOfTheService.data;
     }     
}

index.html

<div ng-controller = "ServiceExampleController as serviceExample">
   {{serviceExample.data}}
</div>

Features of Service:

  1. Lazily Instantiated: If it is not injected it won't be instantiated ever. So to use it will have to inject it to a module.
  2. Singleton: If injected to multiple modules, all will have access to only one particular instance. That is why very convenient to share data across different controllers.

FACTORY

First let's have a look at the syntax:

app.js:

var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);

//first implementation where it returns a function
function NameOfTheFactoryOne(){
   var factory = function(){
      return new SomeService();
    }
   return factory;
}

//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
   var factory = {
      getSomeService : function(){
          return new SomeService();
       }
    };
   return factory;
}

Now using the above two in the controller:

 var factoryOne = NameOfTheFactoryOne() //since it returns a function
 factoryOne.someMethod();

 var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
 factoryTwo.someMethod();

Features of Factory:

  1. Follows the factory design pattern. The factory is a central place that produces new objects or functions.
  2. Not only produces singleton, but customizable services.
  3. The .service() method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever.

PROVIDER

Let's again have a look at the Syntax first:

angular.module('ProviderModule', [])
.controller('ProviderModuleController', ProviderModuleController)
.provider('ServiceProvider', ServiceProvider)
.config(Config); //optional

Config.$inject = ['ServiceProvider'];
function Config(ServiceProvider) {
  ServiceProvider.defaults.maxItems = 10; //some default value
}


ProviderModuleController.$inject = ['ServiceProvider'];
function ProviderModuleController(ServiceProvider) {
  //some methods
}

function ServiceProvider() {
  var provider = this;

  provider.defaults = {
    maxItems: 10
  };

  provider.$get = function () {
    var someList = new someListService(provider.defaults.maxItems);

    return someList;
  };
}

}

Features of Provider:

  1. Provider is the most flexible method of creating services in Angular.
  2. Not only we can create a factory that's dynamically configurable, but at the time of using the factory, with the provider method, we could custom configure the factory just once at the bootstrapping of our entire application.
  3. The factory can then be used throughout the application with custom settings. In other words, we can configure this factory before the application starts. In fact in the angular documentation it is mentioned that the provider method is what actually gets executed behind the scenes when we configure our services with either .service or .factory methods.
  4. The $get is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factory method. In that function, we create our own service. This $get property, that's a function, is what makes the provider a provider. AngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.

How many threads can a Java VM support?

Um, lots.

There are several parameters here. The specific VM, plus there are usually run-time parameters on the VM as well. That's somewhat driven by the operating system: what support does the underlying OS have for threads and what limitations does it put on them? If the VM actually uses OS-level threads at all, the good old red thread/green thread thing.

What "support" means is another question. If you write a Java program that is just something like

   class DieLikeADog {
         public static void main(String[] argv){
             for(;;){
                new Thread(new SomeRunaable).start();
             }
         }
    }

(and don't complain about little syntax details, I'm on my first cup of coffee) then you should certainly expect to get hundreds or thousands of threads running. But creating a Thread is relatively expensive, and scheduler overhead can get intense; it's unclear that you could have those threads do anything useful.

Update

Okay, couldn't resist. Here's my little test program, with a couple embellishments:

public class DieLikeADog {
    private static Object s = new Object();
    private static int count = 0;
    public static void main(String[] argv){
        for(;;){
            new Thread(new Runnable(){
                    public void run(){
                        synchronized(s){
                            count += 1;
                            System.err.println("New thread #"+count);
                        }
                        for(;;){
                            try {
                                Thread.sleep(1000);
                            } catch (Exception e){
                                System.err.println(e);
                            }
                        }
                    }
                }).start();
        }
    }
}

On OS/X 10.5.6 on Intel, and Java 6 5 (see comments), here's what I got

New thread #2547
New thread #2548
New thread #2549
Can't create thread: 5
New thread #2550
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
        at java.lang.Thread.start0(Native Method)
        at java.lang.Thread.start(Thread.java:592)
        at DieLikeADog.main(DieLikeADog.java:6)

"No X11 DISPLAY variable" - what does it mean?

Initial Check.

1) When you are exporting the DISPLAY to other machine, ensure you entered the command xhost + on that machine. This command allows to other machine to export their DISPLAY on this machine. There may be security constraints, just know about it. Need to check ssh -X MachineIP will not require xhost + ?

2) Some times JCONSOLE won't show all its process, since those JVM process may run with different user and you are exporting the DISPLAY with another user. so better follow CD_DIR>sudo ./jconsole

3) In WAS (WEBSPHERE); jconsole won't be able to connect its java server process, that time just go till the link, then try connecting it. This worked for me. May be this page is initializing some variables to enable jconsole to connect with that server.

WAS console > Application servers > server1 > Process definition > Java Virtual Machine


I have faced the same issue with AIX (where command line interface only available, There is no DISPLAY UI) machine. I resolved by installing

NX Client for Windows

Step 1: Through that Windows machine, I connected with unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:NXClientPORTConnectedMentionedOnTitle"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

VNC

If you installed VNC on UNIX box where display is available; then Windows and NX Client is not required. Step 1: Use VNC to connect with Unix box where GUI console is available.
Step 2: SSH to the AIX box from that UNIX box.
Step 3: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 4: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

ELSE

Step 1: SSH to the AIX box from that UNIX box.
Step 2: set DISPLAY like "export DISPLAY=UNIXMACHINE:VNCPORT"
Step 3: Now if we launch any programs which requires DISPLAY; it will be launched on this UNIX box.

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

If you have private certs to deal with, like your orgs own CA root and intermediates part of the chain, then better to add the certs to the ca file viz. cacert.pem than bypassing the entire security apparatus (verify=False). Below code gets you going in both 2.7+ and 3+

Consider adding the whole cert chain and off course you need to do this only once.

import certifi

cafile=certifi.where() # cacert file
with open ('rootca.pem','rb') as infile:
    customca=infile.read()
    with open(cafile,'ab') as outfile:
        outfile.write(customca)
with open ('interca.pem','rb') as infile:
    customca=infile.read()
    with open(cafile,'ab') as outfile:
        outfile.write(customca)
with open ('issueca.pem','rb') as infile:
    customca=infile.read()
    with open(cafile,'ab') as outfile:
        outfile.write(customca)

Then this should get you going

import requests
response = requests.request("GET", 'https://yoursecuresite.com',  data = {})
print(response.text.encode('utf8'))

Hope this helps

Viewing localhost website from mobile device

In additional you should disable your antivirus or manage it to open 80 port on your system.

Best practice to look up Java Enum

Probably you can implement generic static lookup method.

Like so

public class LookupUtil {
   public static <E extends Enum<E>> E lookup(Class<E> e, String id) {   
      try {          
         E result = Enum.valueOf(e, id);
      } catch (IllegalArgumentException e) {
         // log error or something here

         throw new RuntimeException(
           "Invalid value for enum " + e.getSimpleName() + ": " + id);
      }

      return result;
   }
}

Then you can

public enum MyEnum {
   static public MyEnum lookup(String id) {
       return LookupUtil.lookup(MyEnum.class, id);
   }
}

or call explicitly utility class lookup method.

compareTo() vs. equals()

A difference is that "foo".equals((String)null) returns false while "foo".compareTo((String)null) == 0 throws a NullPointerException. So they are not always interchangeable even for Strings.

how to set width for PdfPCell in ItextSharp

aca definis los anchos

 float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};

aca se los insertas a la tabla que tiene las columnas

table.setWidths(anchoDeColumnas);

Split a List into smaller lists of N size

How about this one? The idea was to use only one loop. And, who knows, maybe you're using only IList implementations thorough your code and you don't want to cast to List.

private IEnumerable<IList<T>> SplitList<T>(IList<T> list, int totalChunks)
{
    IList<T> auxList = new List<T>();
    int totalItems = list.Count();

    if (totalChunks <= 0)
    {
        yield return auxList;
    }
    else 
    {
        for (int i = 0; i < totalItems; i++)
        {               
            auxList.Add(list[i]);           

            if ((i + 1) % totalChunks == 0)
            {
                yield return auxList;
                auxList = new List<T>();                
            }

            else if (i == totalItems - 1)
            {
                yield return auxList;
            }
        }
    }   
}

Creating a UIImage from a UIColor to use as a background image for UIButton

I suppose that 255 in 227./255 is perceived as an integer and divide is always return 0

C# - Create SQL Server table programmatically

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommend
{
    class sqlcreateapp
    {
        static void Main(string[] args)
        {
            try
            {
                SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
                SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
                conn.Open();
                cmd.ExecuteNonQuery();
                Console.WriteLine("Table Created Successfully...");
                conn.Close();
            }
            catch(Exception e)
            {
                Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
            }
            Console.ReadKey();
        }
    }
}

What is the difference between a stored procedure and a view?

@Patrick is correct with what he said, but to answer your other questions a View will create itself in Memory, and depending on the type of Joins, Data and if there is any aggregation done, it could be a quite memory hungry View.

Stored procedures do all their processing either using Temp Hash Table e.g #tmpTable1 or in memory using @tmpTable1. Depending on what you want to tell it to do.

A Stored Procedure is like a Function, but is called Directly by its name. instead of Functions which are actually used inside a query itself.

Obviously most of the time Memory tables are faster, if you are not retrieveing alot of data.

Scroll RecyclerView to show selected item on top

If you looking for vertical LinearLayout Manager you can achieve smooth scrolling using a custom LinearSmoothScroller:

import android.content.Context;
import android.graphics.PointF;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;

public class SnappingLinearLayoutManager extends LinearLayoutManager {

    public SnappingLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                       int position) {
        RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    private class TopSnappedSmoothScroller extends LinearSmoothScroller {
        public TopSnappedSmoothScroller(Context context) {
            super(context);

        }

        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return SnappingLinearLayoutManager.this
                    .computeScrollVectorForPosition(targetPosition);
        }

        @Override
        protected int getVerticalSnapPreference() {
            return SNAP_TO_START;
        }
    }
}

use an instance of the layoutmanager in recycle view and then calling recyclerView.smoothScrollToPosition(pos); will smooth scroll to selected position to top of the recycler view

Editing an item in a list<T>

After adding an item to a list, you can replace it by writing

list[someIndex] = new MyClass();

You can modify an existing item in the list by writing

list[someIndex].SomeProperty = someValue;

EDIT: You can write

var index = list.FindIndex(c => c.Number == someTextBox.Text);
list[index] = new SomeClass(...);

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.

Label word wrapping

Refer to Automatically Wrap Text in Label. It describes how to create your own growing label.

Here is the full source taken from the above reference:

using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

public class GrowLabel : Label {
  private bool mGrowing;
  public GrowLabel() {
    this.AutoSize = false;
  }
  private void resizeLabel() {
    if (mGrowing) return;
    try {
      mGrowing = true;
      Size sz = new Size(this.Width, Int32.MaxValue);
      sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
      this.Height = sz.Height;
    }
    finally {
      mGrowing = false;
    }
  }
  protected override void OnTextChanged(EventArgs e) {
    base.OnTextChanged(e);
    resizeLabel();
  }
  protected override void OnFontChanged(EventArgs e) {
    base.OnFontChanged(e);
    resizeLabel();
  }
  protected override void OnSizeChanged(EventArgs e) {
    base.OnSizeChanged(e);
    resizeLabel();
  }
}

When should I use Memcache instead of Memcached?

Memcached client library was just recently released as stable. It is being used by digg ( was developed for digg by Andrei Zmievski, now no longer with digg) and implements much more of the memcached protocol than the older memcache client. The most important features that memcached has are:

  1. Cas tokens. This made my life much easier and is an easy preventive system for stale data. Whenever you pull something from the cache, you can receive with it a cas token (a double number). You can than use that token to save your updated object. If no one else updated the value while your thread was running, the swap will succeed. Otherwise a newer cas token was created and you are forced to reload the data and save it again with the new token.
  2. Read through callbacks are the best thing since sliced bread. It has simplified much of my code.
  3. getDelayed() is a nice feature that can reduce the time your script has to wait for the results to come back from the server.
  4. While the memcached server is supposed to be very stable, it is not the fastest. You can use binary protocol instead of ASCII with the newer client.
  5. Whenever you save complex data into memcached the client used to always do serialization of the value (which is slow), but now with memcached client you have the option of using igbinary. So far I haven't had the chance to test how much of a performance gain this can be.

All of this points were enough for me to switch to the newest client, and can tell you that it works like a charm. There is that external dependency on the libmemcached library, but have managed to install it nonetheless on Ubuntu and Mac OSX, so no problems there so far.

If you decide to update to the newer library, I suggest you update to the latest server version as well as it has some nice features as well. You will need to install libevent for it to compile, but on Ubuntu it wasn't much trouble.

I haven't seen any frameworks pick up the new memcached client thus far (although I don't keep track of them), but I presume Zend will get on board shortly.

UPDATE

Zend Framework 2 has an adapter for Memcached which can be found here

java SSL and cert keystore

SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.

The specific keys you have to set are below:

javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.

javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).

javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes, /, in place of backslashes, \.

If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):

  1. $JAVA_HOME/lib/security/jssecacerts
  2. $JAVA_HOME/lib/security/cacerts

javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by javax.net.ssl.trustStore.

javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.

javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.

How to disable Home and other system buttons in Android?

Post ICS i.e. Android 4+, the overriding of the HomeButton has been removed for security reasons, to enable the user exit in case the application turns out to be a malware.

Plus, it is not a really good practice to not let the user navigate away from the application. But, since you are making a lock screen application, what you can do is declare the activity as a Launcher , so that when the HomeButton is pressed it will simply restart your application and remain there itself (the users would notice nothing but a slight flicker in the screen).

You can go through the following link:

http://dharmendra4android.blogspot.in/2012/05/override-home-button-in-android.html

How to add "required" attribute to mvc razor viewmodel text input editor

You can use the required html attribute if you want:

@Html.TextBoxFor(m => m.ShortName, 
new { @class = "form-control", placeholder = "short name", required="required"})

or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute can Validate on the front end and server side. If you want to go the MVC route, I'd suggest reading Data annotations MVC3 Required attribute.

OR

You can get really advanced:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = new Dictionary<string, object>(
    Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix));

 attributes.Add("class", "form-control");
 attributes.Add("placeholder", "short name");

  if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
  {
   attributes.Add("required", "required");
  }

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

or if you need it for multiple editor templates:

public static class ViewPageExtensions
{
  public static IDictionary<string, object> GetAttributes(this WebViewPage instance)
  {
    // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
    var attributes = new Dictionary<string, object>(
      instance.Html.GetUnobtrusiveValidationAttributes(
         instance.ViewData.TemplateInfo.HtmlFieldPrefix));

    if (ViewData.ModelMetadata.ContainerType
      .GetProperty(ViewData.ModelMetadata.PropertyName)
      .GetCustomAttributes(typeof(RequiredAttribute), true)
      .Select(a => a as RequiredAttribute)
      .Any(a => a != null))
    {
      attributes.Add("required", "required");
    }
  }
}

then in your templates:

@{
  // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor
  var attributes = this.GetAttributes();

  attributes.Add("class", "form-control");
  attributes.Add("placeholder", "short name");

  @Html.TextBoxFor(m => m.ShortName, attributes)

}

Update 1 (for Tomas who is unfamilar with ViewData).

What's the difference between ViewData and ViewBag?

Excerpt:

So basically it (ViewBag) replaces magic strings:

ViewData["Foo"]

with magic properties:

ViewBag.Foo

What is "X-Content-Type-Options=nosniff"?

Just to elaborate a bit on the meta-tag thing. I've heard a talk, where a statement was made, one should always insert the "no-sniff" meta tag in the html to prevent browser sniffing (just like OP did):

<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />

However, this is not a valid method for w3c compliant websites, the validator will raise an error:

Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.

And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the "no-sniff" option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.

To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:

Visualization of enabled no-sniff option

What is [Serializable] and when should I use it?

Some practical uses for the [Serializable] attribute:

  • Saving object state using binary serialisation; you can very easily 'save' entire object instances in your application to a file or network stream and then recreate them by deserialising - check out the BinaryFormatter class in System.Runtime.Serialization.Formatters.Binary
  • Writing classes whose object instances can be stored on the clipboard using Clipboard.SetData() - nonserialisable classes cannot be placed on the clipboard.
  • Writing classes which are compatible with .NET Remoting; generally, any class instance you pass between application domains (except those which extend from MarshalByRefObject) must be serialisable.

These are the most common usage cases that I have come across.

Where does git config --global get written to?

I was also looking for the global .gitconfig on my Windows machine and found this neat trick using git.

Do a: git config --global -e and then, if you are lucky, you will get a text editor loaded with your global .gitconfig file. Simply lookup the folder from there (or try a save as...), et voilà! :-)

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

I have looked at each of these solutions that also seem to work with one issue. Dark Mode and the background setting

The Background setting of the UITextField must match the background of the parent view or no line appears

So this will work on light mode To get to work in dark mode change the background color to black and it works Exclude back color and the line does not appear

let field = UITextField() 
field.backgroundColor = UIColor.white
field.bottomBorderColor = UIColor.red

This ended up being the best solution for me

extension UITextField {

    func addPadding() {
        let paddingView = UIView(frame: CGRect(x:0, y:0, width: 10, height: self.frame.height))
        self.leftView = paddingView
        self.leftViewMode = .always
      }

      @IBInspectable var placeHolderColor: UIColor? {
          get {
              return self.placeHolderColor
          }
          set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue!])
          }
      }

      @IBInspectable var bottomBorderColor: UIColor? {
          get {
              return self.bottomBorderColor
          }
          set {
            self.borderStyle = .none
            self.layer.masksToBounds = false
            self.layer.shadowColor = newValue?.cgColor
            self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
            self.layer.shadowOpacity = 1.0
            self.layer.shadowRadius = 0.0
          }
      }
    }

Selenium Webdriver move mouse to Point

Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.

Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .moveByOffset( 10, 25 );
   .click(someOtherElement)
   .keyUp(Keys.CONTROL).build().perform();

Where to get "UTF-8" string literal in Java?

In Java 1.7+

Do not use "UTF-8" string, instead use Charset type parameter:

import java.nio.charset.StandardCharsets

...

new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

I solved this problem using this command COMPOSER_MEMORY_LIMIT=-1

Example: COMPOSER_MEMORY_LIMIT=-1 composer requires larval/ui

Equivalent of LIMIT for DB2

Developed this method:

You NEED a table that has an unique value that can be ordered.

If you want rows 10,000 to 25,000 and your Table has 40,000 rows, first you need to get the starting point and total rows:

int start = 40000 - 10000;

int total = 25000 - 10000;

And then pass these by code to the query:

SELECT * FROM 
(SELECT * FROM schema.mytable 
ORDER BY userId DESC fetch first {start} rows only ) AS mini 
ORDER BY mini.userId ASC fetch first {total} rows only

Initial size for the ArrayList

if you want to use Collections.fill(list, obj); in order to fill the list with a repeated object alternatively you can use

ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10, 0));

the line copies 10 times 0 in to your ArrayList

Sublime Text 2 - Show file navigation in sidebar

Both of the previous answers from Matt York and Cyberbolt are right.

Basic idea is here that you want to get some kind of File explorer in Sublime.

Approach:

1) With File -> New Folder -> Click on Desired folder and Hit Open you will get new popup window in sublime which for me is very annoying

2) I use second option which is drag'n'drop from nautilus (a.k.a. Files) window. Simply drag'n'drop your file you want to explore from nautilus to sublime sidebar. That way you stay in the same window and everything is cool.

Don't forget to enable View -> Sidebar -> Show Sidebar and drag'n'drop there from nautilus and of course run it with root privleges. It works like charm

Iterating over all the keys of a map

https://play.golang.org/p/JGZ7mN0-U-

for k, v := range m { 
    fmt.Printf("key[%s] value[%s]\n", k, v)
}

or

for k := range m {
    fmt.Printf("key[%s] value[%s]\n", k, m[k])
}

Go language specs for for statements specifies that the first value is the key, the second variable is the value, but doesn't have to be present.

docker: executable file not found in $PATH

problem is glibc, which is not part of apline base iamge.

After adding it worked for me :)

Here are the steps to get the glibc

apk --no-cache add ca-certificates wget
wget -q -O /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub
wget https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk
apk add glibc-2.28-r0.apk

.htaccess: where is located when not in www base dir

. (dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess files, then they are probably in the root folder for the website.

If you are using a command line (terminal) to access, then they will only show up if you use:

ls -a

If you are using a GUI application, look for a setting to "show hidden files" or something similar.

If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):

cd /
find . -name ".htaccess"

This will list out any files it finds with that name.

How To Set A JS object property name from a variable

With ECMAScript 6, you can use variable property names with the object literal syntax, like this:

var keyName = 'myKey';
var obj = {
              [keyName]: 1
          };
obj.myKey;//1

This syntax is available in the following newer browsers:

Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+

(https://kangax.github.io/compat-table/es6/)

You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.

Sending email with PHP from an SMTP server

In cases where you are hosting a Wordpress site on Linux and have server access you can save some headaches by installing msmtp which allows you to send via smtp from the standard php mail() function. msmtp is a simpler alternative to postfix which requires a bit more configuration.

Here are the steps:

Install msmtp

sudo apt-get install msmtp-mta ca-certificates

Create a new configuration file:

sudo nano /etc/msmtprc

...with the following configuration information:

# Set defaults.    
defaults

# Enable or disable TLS/SSL encryption.
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

# Set up a default account's settings.
account default
host <smtp.example.net>
port 587
auth on
user <[email protected]>
password <password>
from <[email protected]>
syslog LOG_MAIL

You need to replace the configuration data represented by everything within "<" and ">" (inclusive, remove these). For host/username/password, use your normal credentials for sending mail through your mail provider.

Tell PHP to use it

sudo nano /etc/php5/apache2/php.ini

Add this single line:

sendmail_path = /usr/bin/msmtp -t

Complete documention can be found here:

https://marlam.de/msmtp/

How can I detect whether an iframe is loaded?

I imagine this like that:

<html>
<head>
<script>
var frame_loaded = 0;
function setFrameLoaded()
{
   frame_loaded = 1;
   alert("Iframe is loaded");
}
$('#click').click(function(){
   if(frame_loaded == 1)
    console.log('iframe loaded')
   } else {
    console.log('iframe not loaded')
   }
})
</script>
</head>
<button id='click'>click me</button>

<iframe id='MainPopupIframe' onload='setFrameLoaded();' src='http://...' />...</iframe>

PHP cURL GET request and request's body

The accepted answer is wrong. GET requests can indeed contain a body. This is the solution implemented by WordPress, as an example:

curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );

EDIT: To clarify, the initial curl_setopt is necessary in this instance, because libcurl will default the HTTP method to POST when using CURLOPT_POSTFIELDS (see documentation).

Show DataFrame as table in iPython Notebook

from IPython.display import display
display(df)  # OR
print df.to_html()

How to show the last queries executed on MySQL?

After reading Paul's answer, I went on digging for more information on https://dev.mysql.com/doc/refman/5.7/en/query-log.html

I found a really useful code by a person. Here's the summary of the context.

(Note: The following code is not mine)

This script is an example to keep the table clean which will help you to reduce your table size. As after a day, there will be about 180k queries of log. ( in a file, it would be 30MB per day)

You need to add an additional column (event_unix) and then you can use this script to keep the log clean... it will update the timestamp into a Unix-timestamp, delete the logs older than 1 day and then update the event_time into Timestamp from event_unix... sounds a bit confusing, but it's working great.

Commands for the new column:

SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
ALTER TABLE `general_log_temp`
ADD COLUMN `event_unix` int(10) NOT NULL AFTER `event_time`;
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';

Cleanup script:

SET GLOBAL general_log = 'OFF';
RENAME TABLE general_log TO general_log_temp;
UPDATE general_log_temp SET event_unix = UNIX_TIMESTAMP(event_time);
DELETE FROM `general_log_temp` WHERE `event_unix` < UNIX_TIMESTAMP(NOW()) - 86400;
UPDATE general_log_temp SET event_time = FROM_UNIXTIME(event_unix);
RENAME TABLE general_log_temp TO general_log;
SET GLOBAL general_log = 'ON';

Credit goes to Sebastian Kaiser (Original writer of the code).

Hope someone will find it useful as I did.

Why shouldn't `&apos;` be used to escape single quotes?

If you really need single quotes, apostrophes, you can use

html    | numeric | hex
&lsquo; | &#145;  | &#x91; // for the left/beginning single-quote and
&rsquo; | &#146;  | &#x92; // for the right/ending single-quote

Most pythonic way to delete a file which may not exist

Matt's answer is the right one for older Pythons and Kevin's the right answer for newer ones.

If you wish not to copy the function for silentremove, this functionality is exposed in path.py as remove_p:

from path import Path
Path(filename).remove_p()

INNER JOIN same table

You can also use UNION like

SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_id = $_GET[id]
UNION
SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_parent_id = $_GET[id]

How to flush output after each `echo` call?

I had a similar thing to do. Using

// ini_set("output_buffering", 0);  // off 
ini_set("zlib.output_compression", 0);  // off
ini_set("implicit_flush", 1);  // on   

did make the output flushing frequent in my case.

But I had to flush the output right at a particular point(in a loop that I run), so using both

ob_flush();
flush();

together worked for me.

I wasn't able to turn off "output_buffering" with ini_set(...), had to turn it directly in php.ini, phpinfo() shows its setting as "no value" when turned off, is that normal? .

Good ways to sort a queryset? - Django

Here's a way that allows for ties for the cut-off score.

author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')

You may get more than 30 authors in top_authors this way and the min(30,author_count) is there incase you have fewer than 30 authors.

How do I create an .exe for a Java program?

You could try exe4j. This is effectively what we use through its cousin install4j.

Bootstrap - How to add a logo to navbar class?

<a class="navbar-brand" href="#" style="padding:0px;">
  <img src="mylogo.png" style="height:100%;">
</a>

For including a text:

<a class="navbar-brand" href="#" style="padding:0px;">
  <img src="mylogo.png" style="height:100%;display:inline-block;"><span>text</span>
</a>

How do I get list of methods in a Python class?

methods = [(func, getattr(o, func)) for func in dir(o) if callable(getattr(o, func))]

gives an identical list as

methods = inspect.getmembers(o, predicate=inspect.ismethod)

does.

Generate JSON string from NSDictionary in iOS

In Swift (version 2.0):

class func jsonStringWithJSONObject(jsonObject: AnyObject) throws -> String? {
    let data: NSData? = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: NSJSONWritingOptions.PrettyPrinted)

    var jsonStr: String?
    if data != nil {
        jsonStr = String(data: data!, encoding: NSUTF8StringEncoding)
    }

    return jsonStr
}

Mockito - NullpointerException when stubbing Method

When using JUnit 5 or above. You have to inject the class annotated with @Mock in an @BeforeEach setup.

Is it possible to run JavaFX applications on iOS, Android or Windows Phone 8?

Desktop: first-class support

Oracle JavaFX from Java SE supports only OS X (macOS), GNU/Linux and Microsoft Windows. On these platforms, JavaFX applications are typically run on JVM from Java SE or OpenJDK.

Android: should work

There is also a JavaFXPorts project, which is an open-source project sponsored by a third-party. It aims to port JavaFX library to Android and iOS.

On Android, this library can be used like any other Java library; the JVM bytecode is compiled to Dalvik bytecode. It's what people mean by saying that "Android runs Java".

iOS: status not clear

On iOS, situation is a bit more complex, as neither Java SE nor OpenJDK supports Apple mobile devices. Till recently, the only sensible option was to use RoboVM ahead-of-time Java compiler for iOS. Unfortunately, on 15 April 2015, RoboVM project was shut down.

One possible alternative is Intel's Multi-OS Engine. Till recently, it was a proprietary technology, but on 11 August 2016 it was open-sourced. Although it can be possible to compile an iOS JavaFX app using JavaFXPorts' JavaFX implementation, there is no evidence for that so far. As you can see, the situation is dynamically changing, and this answer will be hopefully updated when new information is available.

Windows Phone: no support

With Windows Phone it's simple: there is no JavaFX support of any kind.

How to copy folders to docker image from Dockerfile?

FROM openjdk:8-jdk-alpine RUN apk update && apk add wget openssl lsof procps curl RUN apk update RUN mkdir -p /apps/agent RUN mkdir -p /apps/lib ADD ./app/agent /apps/agent ADD ./app/lib /apps/lib ADD ./app/* /apps/app/ RUN ls -lrt /apps/app/ CMD sh /apps/app/launch.sh

by using DockerFile, I'm copying agent and lib directories to /apps/agent,/apps/lib directories and bunch of files to target.

Maintaining the final state at end of a CSS3 animation

IF NOT USING THE SHORT HAND VERSION: Make sure the animation-fill-mode: forwards is AFTER the animation declaration or it will not work...

animation-fill-mode: forwards;
animation-name: appear;
animation-duration: 1s;
animation-delay: 1s;

vs

animation-name: appear;
animation-duration: 1s;
animation-fill-mode: forwards;
animation-delay: 1s;

How do I create a SQL table under a different schema?

  1. Right-click on the tables node and choose New Table...
  2. With the table designer open, open the properties window (view -> Properties Window).
  3. You can change the schema that the table will be made in by choosing a schema in the properties window.

Prevent form submission on Enter key press

Here is how you can do it using JavaScript:

_x000D_
_x000D_
//in your **popup.js** file just use this function 

    var input = document.getElementById("textSearch");
    input.addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            alert("yes it works,I'm happy ");
        }
    });
_x000D_
<!--Let's say this is your html file-->
 <!DOCTYPE html>
    <html>
      <body style="width: 500px">
        <input placeholder="Enter the text and press enter" type="text" id="textSearch"/> 
          <script type="text/javascript" src="public/js/popup.js"></script>
      </body>
    </html>
_x000D_
_x000D_
_x000D_

Can I use conditional statements with EJS templates (in JMVC)?

I know this is a little late answer,

you can use if and else statements in ejs as follows

<% if (something) { %>
   // Then do some operation
<% } else { %>
   // Then do some operation
<% } %>

But there is another thing I want to emphasize is that if you use the code this way,

<% if (something) { %>
   // Then do some operation
<% } %>
<% else { %>
   // Then do some operation
<% } %>

It will produce an error.

Hope this will help to someone

Fix height of a table row in HTML Table

This works, as long as you remove the height attribute from the table.

<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
  <tr><td height='9px' bgcolor="#990000">Upper</td></tr>
  <tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>

jquery $(this).id return Undefined

use this actiion

$(document).ready(function () {
var a = this.id;

alert (a);
});

JavaScript editor within Eclipse

Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS.

Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS.

ASP.NET 2.0 - How to use app_offline.htm

Make sure your app_offline.htm file is at least 512 bytes long. A zero-byte app_offline.htm will have no effect.

UPDATE: Newer versions of ASP.NET/IIS may behave better than when I first wrote this.

UPDATE 2: If you are using ASP.NET MVC, add the following to web.config:

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
</configuration>

jquery simple image slideshow tutorial

Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin.

_x000D_
_x000D_
$(function() {_x000D_
  var theImage = $('ul#ss li img');_x000D_
  var theWidth = theImage.width();_x000D_
  //wrap into mother div_x000D_
  $('ul#ss').wrap('<div id="mother" />');_x000D_
  //assign height width and overflow hidden to mother_x000D_
  $('#mother').css({_x000D_
    width: function() {_x000D_
      return theWidth;_x000D_
    },_x000D_
    height: function() {_x000D_
      return theImage.height();_x000D_
    },_x000D_
    position: 'relative',_x000D_
    overflow: 'hidden'_x000D_
  });_x000D_
  //get total of image sizes and set as width for ul _x000D_
  var totalWidth = theImage.length * theWidth;_x000D_
  $('ul').css({_x000D_
    width: function() {_x000D_
      return totalWidth;_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var ss_timer = setInterval(function() {_x000D_
    ss_next();_x000D_
  }, 3000);_x000D_
_x000D_
  function ss_next() {_x000D_
    var a = $(".active");_x000D_
    a.removeClass('active');_x000D_
_x000D_
    if (a.hasClass('last')) {_x000D_
      //last element -- loop_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (0)_x000D_
      }, 1000);_x000D_
      a.siblings(":first").addClass('active');_x000D_
    } else {_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (-(a.index() + 1) * theWidth)_x000D_
      }, 1000);_x000D_
      a.next().addClass('active');_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Cancel slideshow and move next manually on click_x000D_
  $('ul#ss li img').on('click', function() {_x000D_
    clearInterval(ss_timer);_x000D_
    ss_next();_x000D_
  });_x000D_
_x000D_
});
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
#ss {_x000D_
  list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
  float: left;_x000D_
}_x000D_
#ss img {_x000D_
  width: 200px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
  <li class="active">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado-colors.jpg">_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
  </li>_x000D_
  <li class="last">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado.jpg">_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

SQL Server : converting varchar to INT

You could try updating the table to get rid of these characters:

UPDATE dbo.[audit]
  SET UserID = REPLACE(UserID, CHAR(0), '')
  WHERE CHARINDEX(CHAR(0), UserID) > 0;

But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:

SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
  FROM dbo.[audit];

But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:

ALTER TABLE dbo.[audit]
  ADD CONSTRAINT do_not_allow_stupid_data
  CHECK (CHARINDEX(CHAR(0), UserID) = 0);

EDIT

Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:

DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;

-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;

-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;

Please confirm that this code on its own (well, the first SELECT, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:

SELECT UserID, CONVERT(VARBINARY(32), UserID)
  FROM dbo.[audit]
  WHERE UserID LIKE '%[^0-9]%';

So take a random row, and then paste the output into a query like this:

DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
  PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
  SET @i = @i + 1;
END

This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0) - since you can't really filter out the rows that contain CHAR(0) because they could contain CHAR(0) and CHAR(something else). For all we know you have values in the table like:

SELECT '15' + CHAR(9) + '23' + CHAR(0);

...which also can't be converted to an integer, whether you've replaced CHAR(0) or not.

I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.

Disable and enable buttons in C#

button2.Enabled == true ; must be button2.Enabled = true ;.

You have a compare == where you should have an assign =.

How to connect to a remote MySQL database with Java?

in my.cnf file , please change the following

## Instead of skip-networking the default is now to listen only on ## localhost which is more compatible and is not less secure. ## bind-address = 127.0.0.1

What is the difference between SQL and MySQL?

SQL is the actual language that as defined by the ISO and ANSI. Here is a link to the Wikipedia article. MySQL is a specific implementation of this standard. I believe Oracle bought the company that originally developed MySQL. Other companies also have their own implementations of the SQL standard.

Test if a string contains a word in PHP?

_x000D_
_x000D_
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
   // do your work_x000D_
}
_x000D_
_x000D_
_x000D_

JavaScript post request like a form submit

this is the answer of rakesh, but with support for arrays (which is quite common in forms):

plain javascript:

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    var addField = function( key, value ){
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", value );

        form.appendChild(hiddenField);
    }; 

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            if( params[key] instanceof Array ){
                for(var i = 0; i < params[key].length; i++){
                    addField( key, params[key][i] )
                }
            }
            else{
                addField( key, params[key] ); 
            }
        }
    }

    document.body.appendChild(form);
    form.submit();
}

oh, and here's the jquery version: (slightly different code, but boils down to the same thing)

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    var form = $(document.createElement( "form" ))
        .attr( {"method": method, "action": path} );

    $.each( params, function(key,value){
        $.each( value instanceof Array? value : [value], function(i,val){
            $(document.createElement("input"))
                .attr({ "type": "hidden", "name": key, "value": val })
                .appendTo( form );
        }); 
    } ); 

    form.appendTo( document.body ).submit(); 
}

Where is NuGet.Config file located in Visual Studio project?

If you use proxy, you will have to edit the Nuget.config file.

In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.

Include the setting:

<config>
  <add key = "http_proxy" value = "http://Youproxy:8080" />
  <add key = "http_proxy.user" value = "YouProxyUser" />
</config>

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

Since your server already includes the sites-enabled folder ( notice the include /etc/nginx/sites-enabled/* line ), then you better use that.

  1. Create a file inside /etc/nginx/sites-available and call it whatever you want, I'll call it django since it's a djanog server

    sudo touch /etc/nginx/sites-available/django
    
  2. Then create a symlink that points to it

    sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
    
  3. Then edit that file with whatever file editor you use, vim or nano or whatever and create the server inside it

    server {
        # hostname or ip or multiple separated by spaces
        server_name localhost example.com 192.168.1.1; #change to your setting
        location / {
            root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
        }
    }
    
  4. Restart or reload nginx settings

    sudo service nginx reload
    

Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server

Check if option is selected with jQuery, if not select a default

$("#select_box_id").children()[1].selected

This is another way of checking an option is selected or not in jquery. This will return Boolean (True or False).

[1] is index of select box option

Which @NotNull Java annotation should I use?

One of the nice things about IntelliJ is that you don't need to use their annotations. You can write your own, or you can use those of whatever other tool you like. You're not even limited to a single type. If you're using two libraries that use different @NotNull annotations, you can tell IntelliJ to use both of them. To do this, go to "Configure Inspections", click on the "Constant Conditions & Exceptions" inspection, and hit the "Configure inspections" button. I use the Nullness Checker wherever I can, so I set up IntelliJ to use those annotations, but you can make it work with whatever other tool you want. (I have no opinion on the other tools because I've been using IntelliJ's inspections for years, and I love them.)

How to connect to MySQL Database?

You must to download MySQLConnection NET from here.

Then you need add MySql.Data.DLL to MSVisualStudio like this:

  1. Open menu project
  2. Add
  3. Reference
  4. Browse to C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2
  5. Add MySql.Data.dll

If you want to know more visit: enter link description here

To use in the code you must import the library:

using MySql.Data.MySqlClient;

An example with connectio to Mysql database (NO SSL MODE) by means of Click event:

using System;
using System.Windows;
using MySql.Data.MySqlClient;


namespace Deportes_WPF
{

public partial class Login : Window
{
    private MySqlConnection connection;
    private string server;
    private string database;
    private string user;
    private string password;
    private string port;
    private string connectionString;
    private string sslM;

    public Login()
    {
        InitializeComponent();

        server = "server_name";
        database = "database_name";
        user = "user_id";
        password = "password";
        port = "3306";
        sslM = "none";

        connectionString = String.Format("server={0};port={1};user id={2}; password={3}; database={4}; SslMode={5}", server, port, user, password, database, sslM);

        connection = new MySqlConnection(connectionString);
    }

    private void conexion()
    {
        try
        {
            connection.Open();

            MessageBox.Show("successful connection");

            connection.Close();
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message + connectionString);
        }
    }

    private void btn1_Click(object sender, RoutedEventArgs e)
    {
        conexion();
    }
  }

}

How do you get the contextPath from JavaScript, the right way?

Reviewer the solution by this Checking the solution of this page, make the following solution I hope it works: Example:

Javascript:

var context = window.location.pathname.substring(0, window.location.pathname.indexOf("/",2)); 
var url =window.location.protocol+"//"+ window.location.host +context+"/bla/bla";

If statements for Checkboxes

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
    if (checkBoxImage.Checked)
    {
        groupBoxImage.Show();
    }
    else if (!checkBoxImage.Checked)
    {
        groupBoxImage.Hide(); 
    }
}

Private properties in JavaScript ES6 classes

Short answer, no, there is no native support for private properties with ES6 classes.

But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties. Note that the getters and setters gets redefine on each new instance of the class.

ES6

class Person {
    constructor(name) {
        var _name = name
        this.setName = function(name) { _name = name; }
        this.getName = function() { return _name; }
    }
}

ES5

function Person(name) {
    var _name = name
    this.setName = function(name) { _name = name; }
    this.getName = function() { return _name; }
}

How do I measure the execution time of JavaScript code with callbacks?

Old question but for a simple API and light-weight solution; you can use perfy which uses high-resolution real time (process.hrtime) internally.

var perfy = require('perfy');

function end(label) {
    return function (err, saved) {
        console.log(err ? 'Error' : 'Saved'); 
        console.log( perfy.end(label).time ); // <——— result: seconds.milliseconds
    };
}

for (var i = 1; i < LIMIT; i++) {
    var label = 'db-save-' + i;
    perfy.start(label); // <——— start and mark time
    db.users.save({ id: i, name: 'MongoUser [' + i + ']' }, end(label));
}

Note that each time perfy.end(label) is called, that instance is auto-destroyed.

Disclosure: Wrote this module, inspired by D.Deriso's answer. Docs here.

Python: How to get stdout after running os.system?

commands also works.

import commands
batcmd = "dir"
result = commands.getoutput(batcmd)
print result

It works on linux, python 2.7.

How to generate graphs and charts from mysql database in php

I use Google Chart Tools https://developers.google.com/chart/ It's well documented and the charts look great. Being javascript, you can feed it json data via ajax.

Get login username in java

in Unix:

new com.sun.security.auth.module.UnixSystem().getUsername()

in Windows:

new com.sun.security.auth.module.NTSystem().getName()

in Solaris:

new com.sun.security.auth.module.SolarisSystem().getUsername()

Why Git is not allowing me to commit even after configuration?

I had this problem even after setting the config properly. git config

My scenario was issuing git command through supervisor (in Linux). On further debugging, supervisor was not reading the git config from home folder. Hence, I had to set the environment HOME variable in the supervisor config so that it can locate the git config correctly. It's strange that supervisor was not able to locate the git config just from the username configured in supervisor's config (/etc/supervisor/conf.d).

How to Run the Procedure?

In SQL Plus:

VAR rc REFCURSOR
EXEC gokul_proc(1,'GOKUL', :rc);
print rc

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

Play infinitely looping video on-load in HTML5

As of April 2018, Chrome (along with several other major browsers) now require the muted attribute too.

Therefore, you should use

<video width="320" height="240" autoplay loop muted>
  <source src="movie.mp4" type="video/mp4" />
</video>

What is the difference between i++ and ++i?

Oddly it looks like the other two answers don't spell it out, and it's definitely worth saying:


i++ means 'tell me the value of i, then increment'

++i means 'increment i, then tell me the value'


They are Pre-increment, post-increment operators. In both cases the variable is incremented, but if you were to take the value of both expressions in exactly the same cases, the result will differ.

How to call a method function from another class?

You need to understand the difference between classes and objects. From the Java tutorial:

An object is a software bundle of related state and behavior

A class is a blueprint or prototype from which objects are created

You've defined the prototypes but done nothing with them. To use an object, you need to create it. In Java, we use the new keyword.

new Date();

You will need to assign the object to a variable of the same type as the class the object was created from.

Date d = new Date();

Once you have a reference to the object you can interact with it

d.date("01", "12", "14");

The exception to this is static methods that belong to the class and are referenced through it

public class MyDate{
  public static date(){ ... }
}

...
MyDate.date();

In case you aren't aware, Java already has a class for representing dates, you probably don't want to create your own.

In MySQL, can I copy one row to insert into the same table?

Here's an answer I found online at this site Describes how to do the above1 You can find the answer at the bottom of the page. Basically, what you do is copy the row to be copied to a temporary table held in memory. You then change the Primary Key number using update. You then re-insert it into the target table. You then drop the table.

This is the code for it:

CREATE TEMPORARY TABLE rescueteam ENGINE=MEMORY SELECT * FROMfitnessreport4 WHERE rID=1;# 1 row affected. UPDATE rescueteam SET rID=Null WHERE rID=1;# 1 row affected.INSERT INTO fitnessreport4 SELECT * FROM rescueteam;# 1 row affected. DROP TABLE rescueteam# MySQL returned an empty result set (i.e. zero
rows).

I created the temporary table rescueteam. I copied the row from my original table fitnessreport4. I then set the primary key for the row in the temporary table to null so that I can copy it back to the original table without getting a Duplicate Key error. I tried this code yesterday evening and it worked.

Adding header for HttpURLConnection

Just cause I don't see this bit of information in the answers above, the reason the code snippet originally posted doesn't work correctly is because the encodedBytes variable is a byte[] and not a String value. If you pass the byte[] to a new String() as below, the code snippet works perfectly.

encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

Unpacking a list / tuple of pairs into two lists / tuples

>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')

Edit: Note that zip(*iterable) is its own inverse:

>>> list(source_list) == zip(*zip(*source_list))
True

When unpacking into two lists, this becomes:

>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True

Addition suggested by rocksportrocker.

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I was facing the same error and struggled with it for hours. I had a web API project which is using Newtonsoft.json and another UnitTest project for the web API project. The unit test project also needed the Newtonsoft.json reference. But on adding the link I was getting the above exception.

I finally resolved it by adding the below code snippet in the app.config of the unit test project:

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>

How to fill the whole canvas with specific color?

_x000D_
_x000D_
let canvas = document.getElementById('canvas');_x000D_
canvas.setAttribute('width', window.innerWidth);_x000D_
canvas.setAttribute('height', window.innerHeight);_x000D_
let ctx = canvas.getContext('2d');_x000D_
_x000D_
//Draw Canvas Fill mode_x000D_
ctx.fillStyle = 'blue';_x000D_
ctx.fillRect(0,0,canvas.width, canvas.height);
_x000D_
* { margin: 0; padding: 0; box-sizing: border-box; }_x000D_
body { overflow: hidden; }
_x000D_
<canvas id='canvas'></canvas>
_x000D_
_x000D_
_x000D_

Download File to server from URL

set_time_limit(0); 
$file = file_get_contents('path of your file');
file_put_contents('file.ext', $file);

Is JavaScript's "new" keyword considered harmful?

I agree with pez and some here.

It seems obvious to me that "new" is self descriptive object creation, where the YUI pattern Greg Dean describes is completely obscured.

The possibility someone could write var bar = foo; or var bar = baz(); where baz isn't an object creating method seems far more dangerous.

Calling method using JavaScript prototype

In addition, if you want to override all instances and not just that one special instance, this one might help.

function MyClass() {}

MyClass.prototype.myMethod = function() {
  alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
  MyClass.prototype.myMethod_original.call( this );
  alert( "doing override");
};

myObj = new MyClass();
myObj.myMethod();

result:

doing original
doing override

How to reset Django admin password?

use

python manage.py dumpdata

then look at the end you will find the user name

How to compare only date components from DateTime in EF?

If you use the Date property for DB Entities you will get exception:

"The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

You can use something like this:

  DateTime date = DateTime.Now.Date;

  var result = from client in context.clients
               where client.BirthDate >= date
                     && client.BirthDate < date.AddDays(1)
               select client;

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

Another workaround is using shortpath in windows:

  1. open windows command console using cmd.exe
  2. goto c:\
  3. type command> dir program* /x
  4. it should display as short path like: PROGRA~2
  5. so C:\PROGRA~2 is same as C:\Program Files (x86)
  6. in your JAVA_HOME replace path to : C:\PROGRA~2\Java\jre7

This should work in windows 64 environment as it worked for me in win7 64bit version.

How to delete projects in Intellij IDEA 14?

You will have to manually delete from the project explorer (your local machine hard drive), then delete the project in IntelliJ when it asks to re-open recent projects.

Save child objects automatically using JPA Hibernate

Use org.hibernate.annotations for doing Cascade , if the hibernate and JPA are used together , its somehow complaining on saving the child objects.

How do I view an older version of an SVN file?

It is also interesting to compare the file of the current working revision with the same file of another revision.

You can do as follows:

$ svn diff -r34 file

Regular Expression to match only alphabetic characters

You may use any of these 2 variants:

/^[A-Z]+$/i
/^[A-Za-z]+$/

to match an input string of ASCII alphabets.

  • [A-Za-z] will match all the alphabets (both lowercase and uppercase).
  • ^ and $ will make sure that nothing but these alphabets will be matched.

Code:

preg_match('/^[A-Z]+$/i', "abcAbc^Xyz", $m);
var_dump($m);

Output:

array(0) {
}

Test case is for OP's comment that he wants to match only if there are 1 or more alphabets present in the input. As you can see in the test case that matches failed because there was ^ in the input string abcAbc^Xyz.

Note: Please note that the above answer only matches ASCII alphabets and doesn't match Unicode characters. If you want to match Unicode letters then use:

/^\p{L}+$/u

Here, \p{L} matches any kind of letter from any language

How to display a PDF via Android web browser without "downloading" first

You can open PDF in Google Docs Viewer by appending URL to:

http://docs.google.com/gview?embedded=true&url=<url of a supported doc>

This would open PDF in default browser or a WebView.

A list of supported formats is given here.

Allow access permission to write in Program Files of Windows 7

Another way round it would be to stop UAC then restart it. Create a CMD file with the following code;

Rem Stop UAC %windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f rem force reboot Start ShutDown /R /F /T 30

You'll need to right click on the CMD file and use run as admin. once you have finished what you are doing restart UAC with the following code (no need to use run as admin this time);

%windir%\System32\reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 1 /f

rem force reboot Start ShutDown /R /F /T 30

The down sides to using this method is have to right click and use run as admin to close UAC down and you have to reboot for it to take effect.

BTW there are several reasons why you would need to write to the forbidden areas...the first two that springs to mind would be to run a batch file to append host to prevent your browser going to dodgy sites or to copy license keys in a silent install.

JavaScript query string

Building on the answer by @CMS I have the following (in CoffeeScript which can easily be converted to JavaScript):

String::to_query = ->
  [result, re, d] = [{}, /([^&=]+)=([^&]*)/g, decodeURIComponent]
  while match = re.exec(if @.match /^\?/ then @.substring(1) else @)
    result[d(match[1])] = d match[2] 
  result

You can easily grab what you need with:

location.search.to_query()['my_param']

The win here is an object-oriented interface (instead of functional) and it can be done on any string (not just location.search).

If you are already using a JavaScript library this function make already exist. For example here is Prototype's version

Spring @ContextConfiguration how to put the right location for the xml

We Use:

@ContextConfiguration(locations="file:WebContent/WEB-INF/spitterMVC-servlet.xml")

the project is a eclipse dynamic web project, then the path is:

{project name}/WebContent/WEB-INF/spitterMVC-servlet.xml

creating charts with angularjs

The ZingChart library has an AngularJS directive that was built in-house. Features include:

  • Full access to the entire ZingChart library (all charts, maps, and features)
  • Takes advantage of Angular's 2-way data binding, making data and chart elements easy to update
  • Support from the development team

    ...
    $scope.myJson = {
    type : 'line',
       series : [
          { values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
       ]
    };
    ...
    
    <zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
    

There is a full demo with code examples available.

Single Form Hide on Startup

I use this:

private void MainForm_Load(object sender, EventArgs e)
{
    if (Settings.Instance.HideAtStartup)
    {
        BeginInvoke(new MethodInvoker(delegate
        {
            Hide();
        }));
    }
}

Obviously you have to change the if condition with yours.

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

While variable is not defined - wait

You could have Flash call the function when it's done. I'm not sure what you mean by web services. I assume you have JavaScript code calling web services via Ajax, in which case you would know when they terminate. In the worst case, you could do a looping setTimeout that would check every 100 ms or so.

And the check for whether or not a variable is defined can be just if (myVariable) or safer: if(typeof myVariable == "undefined")

Convert a Python list with strings all to lowercase or uppercase

If your purpose is to matching with another string by converting in one pass, you can use str.casefold() as well.

This is useful when you have non-ascii characters and matching with ascii versions(eg: maße vs masse).Though str.lower or str.upper fails in such cases, str.casefold() will pass. This is available in Python 3 and the idea is discussed in detail with the answer https://stackoverflow.com/a/31599276/4848659.

>>>str="Hello World";
>>>print(str.lower());
hello world
>>>print(str.upper());
HELLO WOLRD
>>>print(str.casefold());
hello world

Mercurial — revert back to old version and continue from there

hg update [-r REV]

If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.

Homebrew refusing to link OpenSSL

for me this is what worked...

I edited the ./bash_profile and added below command

export PATH="/usr/local/opt/openssl/bin:$PATH"

What does "yield break;" do in C#?

yield basically makes an IEnumerable<T> method behave similarly to a cooperatively (as opposed to preemptively) scheduled thread.

yield return is like a thread calling a "schedule" or "sleep" function to give up control of the CPU. Just like a thread, the IEnumerable<T> method regains controls at the point immediately afterward, with all local variables having the same values as they had before control was given up.

yield break is like a thread reaching the end of its function and terminating.

People talk about a "state machine", but a state machine is all a "thread" really is. A thread has some state (I.e. values of local variables), and each time it is scheduled it takes some action(s) in order to reach a new state. The key point about yield is that, unlike the operating system threads we're used to, the code that uses it is frozen in time until the iteration is manually advanced or terminated.

How to convert all tables from MyISAM into InnoDB?

for mysqli connect;

<?php

$host       = "host";
$user       = "user";
$pass       = "pss";
$database   = "db_name";


$connect = new mysqli($host, $user, $pass, $database);  

// Actual code starts here Dont forget to change db_name !!
$sql = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'db_name' 
    AND ENGINE = 'MyISAM'";

$rs = $connect->query($sql);

while($row = $rs->fetch_array())
{
    $tbl = $row[0];
    $sql = "ALTER TABLE `$tbl` ENGINE=INNODB";
    $connect->query($sql);
} ?>

Disable vertical sync for glxgears

For intel drivers, there is also this method

Disable Vertical Synchronization (VSYNC)

The intel-driver uses Triple Buffering for vertical synchronization, this allows for full performance and avoids tearing. To turn vertical synchronization off (e.g. for benchmarking) use this .drirc in your home directory:

<device screen="0" driver="dri2">
    <application name="Default">
        <option name="vblank_mode" value="0"/>
    </application>
</device>

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

i solved this problem by removing space between quotes and command value inside of array ,this is happened because container exited after started and no executable command present which to be run inside of container.

['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']

JQuery get data from JSON array

I think you need something like:

var text= data.response.venue.tips.groups[0].items[1].text;

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

I was experiencing this error on Android 5.1.1 devices sending network requests using okhttp/4.0.0-RC1. Setting header Content-Length: <sizeof response> on the server side resolved the issue.

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

Remove a prefix from a string

I think you can use methods of the str type to do this. There's no need for regular expressions:

def remove_prefix(text, prefix):
    if text.startswith(prefix): # only modify the text if it starts with the prefix
         text = text.replace(prefix, "", 1) # remove one instance of prefix
    return text

case statement in SQL, how to return multiple variables?

In your case you would use two case staements, one for each value you want returned.

Granting Rights on Stored Procedure to another user of Oracle

Packages and stored procedures in Oracle execute by default using the rights of the package/procedure OWNER, not the currently logged on user.

So if you call a package that creates a user for example, its the package owner, not the calling user that needs create user privilege. The caller just needs to have execute permission on the package.

If you would prefer that the package should be run using the calling user's permissions, then when creating the package you need to specify AUTHID CURRENT_USER

Oracle documentation "Invoker Rights vs Definer Rights" has more information http://docs.oracle.com/cd/A97630_01/appdev.920/a96624/08_subs.htm#18575

Hope this helps.

How to use onResume()?

After an activity started, restarted (onRestart() happens before onStart()), or paused (onPause()), onResume() called. When the activity is in the state of onResume(), the activity is ready to be used by the app user.

I have studied the activity lifecycle a little bit, and here's my understanding of this topic: If you want to restart the activity (A) at the end of the execution of another, there could be a few different cases.

  1. The other activity (B) has been paused and/or stopped or destroyed, and the activity A possibly had been paused (onPause()), in this case, activity A will call onResume()

  2. The activity B has been paused and/or stopped or destroyed, the activity A possibly had been stopped (onStop()) due to memory thing, in this case, activity A will call onRestart() first, onStart() second, then onResume()

  3. The activity B has been paused and/or stopped or destroyed, the activity A has been destroyed, the programmer can call onStart() manually to start the activity first, then onResume() because when an activity is in the destroyed status the activity has not started, and this happens before the activity being completely removed. If the activity is removed, the activity needs to be created again. Manually calling onStart() I think it's because if the activity not started and it is created, onStart() will be called after onCreate().

If you want to update data, make a data update function and put the function inside the onResume(). Or put a loadData function inside onResume()

It's better to understand the lifecycle with the help of the Activity lifecycle diagram.

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

How to enter in a Docker container already running with a new TTY

First step get container id:

docker ps

This will show you something like

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

1170fe9e9460 localhost:5000/python:env-7e847468c4d73a0f35e9c5164046ad88 "./run_notebook.sh" 26 seconds ago Up 25 seconds 0.0.0.0:8989->9999/tcp SLURM_TASK-303337_0

1170fe9e9460 is the container id in this case.

Second, enter the docker :

docker exec -it [container_id] bash

so in the above case: docker exec -it 1170fe9e9460 bash

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

Return string without trailing slash

Based on @vdegenne 's answer... how to strip:

Single trailing slash:

theString.replace(/\/$/, '');

Single or consecutive trailing slashes:

theString.replace(/\/+$/g, '');

Single leading slash:

theString.replace(/^\//, '');

Single or consecutive leading slashes:

theString.replace(/^\/+/g, '');

Single leading and trailing slashes:

theString.replace(/^\/|\/$/g, '')

Single or consecutive leading and trailing slashes:

theString.replace(/^\/+|\/+$/g, '')

To handle both slashes and backslashes, replace instances of \/ with [\\/]

Commands out of sync; you can't run this command now

I ran into this error using Doctrine DBAL QueryBuilder.

I created a query with QueryBuilder that uses column subselects, also created with QueryBuilder. The subselects were only created via $queryBuilder->getSQL() and not executed. The error happened on creating the second subselect. By provisionally executing each subselect with $queryBuilder->execute() before using $queryBuilder->getSQL(), everything worked. It is as if the connection $queryBuilder->connection remains in an invalid state for creating a new SQL before executing the currently prepared SQL, despite the new QueryBuilder instance on each subselect.

My solution was to write the subselects without QueryBuilder.

Python convert csv to xlsx

Simple 1-to-1 CSV to XLSX file conversion without enumerating/looping through the rows:

import pyexcel

sheet = pyexcel.get_sheet(file_name="myFile.csv", delimiter=",")
sheet.save_as("myFile.xlsx")

Notes:

  1. I have found that if the file_name is really long (>30 characters excluding path) then the resultant XLSX file will throw an error when Excel tries to load it. Excel will offer to fix the error which it does, but it is frustrating.
  2. There is a great answer previously provided that combines all of the CSV files in a directory into one XLSX workbook, which fits a different use case than just trying to do a 1-to-1 CSV file to XLSX file conversion.

IPython Notebook save location

I tried the other solutions, but I didn't find that c.NotebookApp.notebook_dir setting in the config...

#jupyter_notebook_config.json

{
  "NotebookApp": {
    "nbserver_extensions": {
      "jupyter_nbextensions_configurator": true
    }
  }
}

So, what I do is:

  • cd into the directory where I want the notebooks and checkpoints saved
  • start the notebook server jupyter-lab
  • then, in an active notebook cell, I change my working directory so that the code in my python cells can access my other modules =)
# ipython cell
import os

# change where notebooks are stored
os.chdir('/Users/me/Project')
os.getcwd()

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Open soft keyboard programmatically

Kotlin

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}

Subtract days, months, years from a date in JavaScript

I implemented a function similar to the momentjs method subtract.

- If you use Javascript

function addDate(dt, amount, dateType) {
  switch (dateType) {
    case 'days':
      return dt.setDate(dt.getDate() + amount) && dt;
    case 'weeks':
      return dt.setDate(dt.getDate() + (7 * amount)) && dt;
    case 'months':
      return dt.setMonth(dt.getMonth() + amount) && dt;
    case 'years':
      return dt.setFullYear( dt.getFullYear() + amount) && dt;
  }
}

example:

let dt = new Date();
dt = addDate(dt, -1, 'months');// use -1 to subtract 

- If you use Typescript:

export enum dateAmountType {
  DAYS,
  WEEKS,
  MONTHS,
  YEARS,
}

export function addDate(dt: Date, amount: number, dateType: dateAmountType): Date {
  switch (dateType) {
    case dateAmountType.DAYS:
      return dt.setDate(dt.getDate() + amount) && dt;
    case dateAmountType.WEEKS:
      return dt.setDate(dt.getDate() + (7 * amount)) && dt;
    case dateAmountType.MONTHS:
      return dt.setMonth(dt.getMonth() + amount) && dt;
    case dateAmountType.YEARS:
      return dt.setFullYear( dt.getFullYear() + amount) && dt;
  }
}

example:

let dt = new Date();
dt = addDate(dt, -1, 'months'); // use -1 to subtract

Optional (unit-tests)

I also made some unit-tests for this function using Jasmine:

  it('addDate() should works properly', () => {
    for (const test of [
      { amount: 1,  dateType: dateAmountType.DAYS,   expect: '2020-04-13'},
      { amount: -1, dateType: dateAmountType.DAYS,   expect: '2020-04-11'},
      { amount: 1,  dateType: dateAmountType.WEEKS,  expect: '2020-04-19'},
      { amount: -1, dateType: dateAmountType.WEEKS,  expect: '2020-04-05'},
      { amount: 1,  dateType: dateAmountType.MONTHS, expect: '2020-05-12'},
      { amount: -1, dateType: dateAmountType.MONTHS, expect: '2020-03-12'},
      { amount: 1,  dateType: dateAmountType.YEARS,  expect: '2021-04-12'},
      { amount: -1, dateType: dateAmountType.YEARS,  expect: '2019-04-12'},
    ]) {
      expect(formatDate(addDate(new Date('2020-04-12'), test.amount, test.dateType))).toBe(test.expect);
    }

  });

To use this test you need this function:

// get format date as 'YYYY-MM-DD'
export function formatDate(date: Date): string {
  const d     = new Date(date);
  let month   = '' + (d.getMonth() + 1);
  let day     = '' + d.getDate();
  const year  = d.getFullYear();

  if (month.length < 2)  {
    month = '0' + month;
  }
  if (day.length < 2) {
    day = '0' + day;
  }

  return [year, month, day].join('-');
}

When to use @QueryParam vs @PathParam

Before talking about QueryParam & PathParam. Let's first understand the URL & its components. URL consists of endpoint + resource + queryParam/ PathParam.

For Example,

URL: https://app.orderservice.com/order?order=12345678

or

URL: https://app.orderservice.com/orders/12345678

where

endpoint: https://app.orderservice.com

resource: orders

queryParam: order=12345678

PathParam: 12345678

@QueryParam:

QueryParam is used when the requirement is to filter the request based on certain criteria/criterias. The criteria is specified with ? after the resource in URL. Multiple filter criterias can be specified in the queryParam by using & symbol.

For Example:

https://app.orderservice.com/orders?order=12345678 & customername=X

@PathParam:

PathParam is used when the requirement is to select the particular order based on guid/id. PathParam is the part of the resource in URL.

For Example:

https://app.orderservice.com/orders/12345678

Fail during installation of Pillow (Python module) in Linux

brew install zlib

on OS X doesn't work anymore and instead prompts to install lzlib. Installing that doesn't help.

Instead you install XCode Command line tools and that should install zlib

xcode-select --install