Programs & Examples On #Fetchmail

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Remote JMX connection

http://blogs.oracle.com/jmxetc/entry/troubleshooting_connection_problems_in_jconsole

If you are trying to access a server which is behind a NAT - you will most probably have to start your server with the option

-Djava.rmi.server.hostname=<public/NAT address>

so that the RMI stubs sent to the client contain the server's public address allowing it to be reached by the clients from the outside.

How might I find the largest number contained in a JavaScript array?

I'm not a JavaScript expert, but I wanted to see how these methods stack up, so this was good practice for me. I don't know if this is technically the right way to performance test these, but I just ran them one right after another, as you can see in my code.

Sorting and getting the 0th value is by far the worst method (and it modifies the order of your array, which may not be desirable). For the others, the difference is negligible unless you're talking millions of indices.

Average results of five runs with a 100,000-index array of random numbers:

  • reduce took 4.0392 ms to run
  • Math.max.apply took 3.3742 ms to run
  • sorting and getting the 0th value took 67.4724 ms to run
  • Math.max within reduce() took 6.5804 ms to run
  • custom findmax function took 1.6102 ms to run

var performance = window.performance

function findmax(array)
{
    var max = 0,
        a = array.length,
        counter

    for (counter=0; counter<a; counter++)
    {
        if (array[counter] > max)
        {
            max = array[counter]
        }
    }
    return max
}

function findBiggestNumber(num) {
  var counts = []
  var i
  for (i = 0; i < num; i++) {
      counts.push(Math.random())
  }

  var a, b

  a = performance.now()
  var biggest = counts.reduce(function(highest, count) {
        return highest > count ? highest : count
      }, 0)
  b = performance.now()
  console.log('reduce took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest2 = Math.max.apply(Math, counts)
  b = performance.now()
  console.log('Math.max.apply took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest3 = counts.sort(function(a,b) {return b-a;})[0]
  b = performance.now()
  console.log('sorting and getting the 0th value took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest4 = counts.reduce(function(highest, count) {
        return Math.max(highest, count)
      }, 0)
  b = performance.now()
  console.log('Math.max within reduce() took ' + (b - a) + ' ms to run')

  a = performance.now()
  var biggest5 = findmax(counts)
  b = performance.now()
  console.log('custom findmax function took ' + (b - a) + ' ms to run')
  console.log(biggest + '-' + biggest2 + '-' + biggest3 + '-' + biggest4 + '-' + biggest5)

}

findBiggestNumber(1E5)

Laravel 5 Carbon format datetime

First parse the created_at field as Carbon object.

$createdAt = Carbon::parse($item['created_at']);

Then you can use

$suborder['payment_date'] = $createdAt->format('M d Y');

What does "use strict" do in JavaScript, and what is the reasoning behind it?

Strict mode can prevent memory leaks.

Please check the function below written in non-strict mode:

function getname(){
    name = "Stack Overflow"; // Not using var keyword
    return name;
}
getname();
console.log(name); // Stack Overflow

In this function, we are using a variable called name inside the function. Internally, the compiler will first check if there is any variable declared with that particular name in that particular function scope. Since the compiler understood that there is no such variable, it will check in the outer scope. In our case, it is the global scope. Again, the compiler understood that there is also no variable declared in the global space with that name, so it creates such a variable for us in the global space. Conceptually, this variable will be created in the global scope and will be available in the entire application.

Another scenario is that, say, the variable is declared in a child function. In that case, the compiler checks the validity of that variable in the outer scope, i.e., the parent function. Only then it will check in the global space and create a variable for us there. That means additional checks need to be done. This will affect the performance of the application.


Now let's write the same function in strict mode.

"use strict"
function getname(){
    name = "Stack Overflow"; // Not using var keyword
    return name;
}
getname();
console.log(name); 

We will get the following error.

Uncaught ReferenceError: name is not defined
at getname (<anonymous>:3:15)
at <anonymous>:6:5

Here, the compiler throws the reference error. In strict mode, the compiler does not allow us to use the variable without declaring it. So memory leaks can be prevented. In addition, we can write more optimized code.

HTML anchor tag with Javascript onclick event

Use following code to show menu instead go to href addres

_x000D_
_x000D_
function show_more_menu(e) {_x000D_
  if( !confirm(`Go to ${e.target.href} ?`) ) e.preventDefault();_x000D_
}
_x000D_
<a href='more.php' onclick="show_more_menu(event)"> More >>> </a>
_x000D_
_x000D_
_x000D_

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

Write HTML string in JSON

Just encode html using Base64 algorithm before adding html to the JSON and decode html using Base64 when you read.

byte[] utf8 = htmlMessage.getBytes("UTF8");
htmlMessage= new String(new Base64().encode(utf8));


byte[] dec = new Base64().decode(htmlMessage.getBytes());
htmlMessage = new String(dec , "UTF8");

Replace \n with <br />

The Problem is When you denote '\n' in the replace() call , '\n' is treated as a String length=4 made out of ' \ n '
To get rid of this, use ascii notation. http://www.asciitable.com/

example:

newLine = chr(10)
thatLine=thatLine.replace(newLine , '<br />')

print(thatLine) #python3

print thatLine #python2 .

Open Source Alternatives to Reflector?

ILSpy works great!

As far as I can tell it does everything that Reflector did and looks the same too.

While loop to test if a file exists in bash

Like @zane-hooper, I've had a similar problem on NFS. On parallel / distributed filesystems the lag between you creating a file on one machine and the other machine "seeing" it can be very large, so I could wait up to a full minute after the creation of the file before the while loop exits (and there also is an aftereffect of it "seeing" an already deleted file).

This creates the illusion that the script "doesn't work", while in fact it is the filesystem that is dropping the ball.

This took me a while to figure out, hope it saves somebody some time.

PS This also causes an annoying number of "Stale file handler" errors.

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

How to change the hosts file on android

You have root, but you still need to remount /system to be read/write

$ adb shell
$ su
$ mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

Go here for more information: Mount a filesystem read-write.

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

How do you fix the "element not interactable" exception?

For the html code:

test.html

<button class="dismiss"  onclick="alert('hello')">
    <string for="exit">Dismiss</string>
</button>

the below python code worked for me. You can just try it.

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("http://localhost/gp/test.html")
button = driver.find_element_by_class_name("dismiss")
button.click()
time.sleep(5)
driver.quit()

How to show progress dialog in Android?

ProgressDialog dialog = 
   ProgressDialog.show(yourActivity.this, "", "Please Wait...");

Check if a property exists in a class

There are 2 possibilities.

You really don't have Label property.

You need to call appropriate GetProperty overload and pass the correct binding flags, e.g. BindingFlags.Public | BindingFlags.Instance

If your property is not public, you will need to use BindingFlags.NonPublic or some other combination of flags which fits your use case. Read the referenced API docs to find the details.

EDIT:

ooops, just noticed you call GetProperty on typeof(MyClass). typeof(MyClass) is Type which for sure has no Label property.

How to set encoding in .getJSON jQuery

f you want to use $.getJSON() you can add the following before the call :

$.ajaxSetup({
    scriptCharset: "utf-8",
    contentType: "application/json; charset=utf-8"
});

Multi-line strings in PHP

Not sure how it stacks up performance-wise, but for places where it doesn't really matter, I like this format because I can be sure it is using \r\n (CRLF) and not whatever format my PHP file happens to be saved in.

$text="line1\r\n" .
      "line2\r\n" .
      "line3\r\n";

It also lets me indent however I want.

Securely storing passwords for use in python script

the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8)    # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16)     # 128-bit IV
cipher = AES.new(key, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files

What's the use of ob_start() in php?

You have it backwards. ob_start does not buffer the headers, it buffers the content. Using ob_start allows you to keep the content in a server-side buffer until you are ready to display it.

This is commonly used to so that pages can send headers 'after' they've 'sent' some content already (ie, deciding to redirect half way through rendering a page).

How to read a PEM RSA private key from .NET

Check http://msdn.microsoft.com/en-us/library/dd203099.aspx

under Cryptography Application Block.

Don't know if you will get your answer, but it's worth a try.

Edit after Comment.

Ok then check this code.

using System.Security.Cryptography;


public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { 
    X509Certificate2 myCertificate; 
    try{ 
        myCertificate = new X509Certificate2(PathToPrivateKeyFile); 
    } catch{ 
        throw new CryptographicException("Unable to open key file."); 
    } 

    RSACryptoServiceProvider rsaObj; 
    if(myCertificate.HasPrivateKey) { 
         rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; 
    } else 
        throw new CryptographicException("Private key not contained within certificate."); 

    if(rsaObj == null) 
        return String.Empty; 

    byte[] decryptedBytes; 
    try{ 
        decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); 
    } catch { 
        throw new CryptographicException("Unable to decrypt data."); 
    } 

    //    Check to make sure we decrpyted the string 
   if(decryptedBytes.Length == 0) 
        return String.Empty; 
    else 
        return System.Text.Encoding.UTF8.GetString(decryptedBytes); 
} 

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; }

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You code should be:

   <section id="right">
      <label for="form_msg">Message</label>
      <textarea name="form_msg" id="#msg_text"></textarea>
      <input id="submit" class="button" name="submit" type="submit" value="Send">
   </section>

Js

var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
};
$.ajax({
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){
        $('.success').fadeIn(1000);
    }
});

The PHP:

<?php
if($_POST){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("[email protected]","My Subject:",$email,$message);
}
?>

How to use onClick with divs in React.js

Whilst this can be done with react, be aware that using onClicks with divs (instead of Buttons or Anchors, and others which already have behaviours for click events) is bad practice and should be avoided whenever it can be.

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

This can happens when one library is loaded into gradle several times. Most often through other connected libraries.

Remove a implementation this library in build.gradle

Then Build -> Clear project

and you can run the assembly)

Can "git pull --all" update all my local branches?

This issue is not solved (yet), at least not easily / without scripting: see this post on git mailing list by Junio C Hamano explaining situation and providing call for a simple solution.

The major reasoning is that you shouldn't need this:

With git that is not ancient (i.e. v1.5.0 or newer), there is no reason to have local "dev" that purely track the remote anymore. If you only want to go-look-and-see, you can check out the remote tracking branch directly on a detached HEAD with "git checkout origin/dev".

Which means that the only cases we need to make it convenient for users are to handle these local branches that "track" remote ones when you do have local changes, or when you plan to have some.

If you do have local changes on "dev" that is marked to track the remove "dev", and if you are on a branch different from "dev", then we should not do anything after "git fetch" updates the remote tracking "dev". It won't fast forward anyway

The call for a solution was for an option or external script to prune local branches that follow now remote-tracking branches, rather than to keep them up-to-date by fast-forwarding, like original poster requested.

So how about "git branch --prune --remote=<upstream>" that iterates over local branches, and if

(1) it is not the current branch; and
(2) it is marked to track some branch taken from the <upstream>; and
(3) it does not have any commits on its own;

then remove that branch? "git remote --prune-local-forks <upstream>" is also fine; I do not care about which command implements the feature that much.

Note: as of git 2.10 no such solution exists. Note that the git remote prune subcommand, and git fetch --prune are about removing remote-tracking branch for branch that no longer exists on remote, not about removing local branch that tracks remote-tracking branch (for which remote-tracking branch is upstream branch).

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

If you are getting that error from Event Viewer, you should see another error event (at least one) from the Source ".NET Runtime". Look at that error message as it will contain the Exception info.

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

How to append output to the end of a text file

To append a file use >>

echo "hello world"  >> read.txt   
cat read.txt     
echo "hello siva" >> read.txt   
cat read.txt

then the output should be

hello world   # from 1st echo command
hello world   # from 2nd echo command
hello siva

To overwrite a file use >

echo "hello tom" > read.txt
cat read.txt  

then the out put is

hello tom

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.

SQL keys, MUL vs PRI vs UNI

UNI: For UNIQUE:

  • It is a set of one or more columns of a table to uniquely identify the record.
  • A table can have multiple UNIQUE key.
  • It is quite like primary key to allow unique values but can accept one null value which primary key does not.

PRI: For PRIMARY:

  • It is also a set of one or more columns of a table to uniquely identify the record.
  • A table can have only one PRIMARY key.
  • It is quite like UNIQUE key to allow unique values but does not allow any null value.

MUL: For MULTIPLE:

  • It is also a set of one or more columns of a table which does not identify the record uniquely.
  • A table can have more than one MULTIPLE key.
  • It can be created in table on index or foreign key adding, it does not allow null value.
  • It allows duplicate entries in column.
  • If we do not specify MUL column type then it is quite like a normal column but can allow null entries too hence; to restrict such entries we need to specify it.
  • If we add indexes on column or add foreign key then automatically MUL key type added.

NullPointerException in Java with no StackTrace

Here is an explanation : Hotspot caused exceptions to lose their stack traces in production – and the fix

I've tested it on Mac OS X

  • java version "1.6.0_26"
  • Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511)
  • Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)

    Object string = "abcd";
    int i = 0;
    while (i < 12289) {
        i++;
        try {
            Integer a = (Integer) string;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

For this specific fragment of code, 12288 iterations (+frequency?) seems to be the limit where JVM has decided to use preallocated exception...

How to solve ADB device unauthorized in Android ADB host device?

Have you tried

adb kill-server
adb shell

Sometimes adb gets stuck and first killing adb server and then starting some command forces authorization window to pop-up.

Also please check adb client version on your phone. THis feature is supported from adb 1.0.31 as far as I remember.

Build error: "The process cannot access the file because it is being used by another process"

I had the same issue and could not rectify by using any of the methods mentioned in previous answers. I resolved the issue by killing all instances of "SSIS Debug Hist (32 bit)" in task manager and now working as normal.

Set line spacing

I am not sure if this is what you meant:

line-height: size;

Android: Unable to add window. Permission denied for this window type

if you use apiLevel >= 19, don't use

WindowManager.LayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT 

which gets the following error:

android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@40ec8528 -- permission denied for this window type

Use this instead:

LayoutParams.TYPE_TOAST or TYPE_APPLICATION_PANEL

Converting Swagger specification JSON to HTML documentation

Check out pretty-swag

It has

  1. Similar looking as Swagger-Editor's right panel
  2. Search / Filter
  3. Schema Folding
  4. Live Feedback
  5. Output as a single html file

I was looking at Swagger Editor and thought it could export the preview pane but turned out it cannot. So I wrote my own version of it.

Full Disclosure: I am the author of the tool.

Java switch statement: Constant expression required, but it IS constant

Below code is self-explanatory, We can use an enum with a switch case:

/**
 *
 */
enum ClassNames {
    STRING(String.class, String.class.getSimpleName()),
    BOOLEAN(Boolean.class, Boolean.class.getSimpleName()),
    INTEGER(Integer.class, Integer.class.getSimpleName()),
    LONG(Long.class, Long.class.getSimpleName());
    private Class typeName;
    private String simpleName;
    ClassNames(Class typeName, String simpleName){
        this.typeName = typeName;
        this.simpleName = simpleName;
    }
}

Based on the class values from the enum can be mapped:

 switch (ClassNames.valueOf(clazz.getSimpleName())) {
        case STRING:
            String castValue = (String) keyValue;
            break;
        case BOOLEAN:
            break;
        case Integer:
            break;
        case LONG:
            break;
        default:
            isValid = false;

    }

Hope it helps :)

Running a single test from unittest.TestCase via the command line

In case you want to run only tests from a specific class:

if __name__ == "__main__":
    unittest.main(MyCase())

It works for me in Python 3.6.

Save PHP array to MySQL?

Uhh, I don't know why everyone suggests serializing the array.

I say, the best way is to actually fit it into your database schema. I have no idea (and you gave no clues) about the actual semantic meaning of the data in your array, but there are generally two ways of storing sequences like that

create table mydata (
  id int not null auto_increment primary key,
  field1 int not null,
  field2 int not null,
  ...
  fieldN int not null
)

This way you are storing your array in a single row.

create table mydata (
    id int not null auto_increment primary key,
    ...
)

create table myotherdata (
    id int not null auto_increment primary key,
    mydata_id int not null,
    sequence int not null,
    data int not null
)

The disadvantage of the first method is, obviously, that if you have many items in your array, working with that table will not be the most elegant thing. It is also impractical (possible, but quite inelegant as well - just make the columns nullable) to work with sequences of variable length.

For the second method, you can have sequences of any length, but of only one type. You can, of course, make that one type varchar or something and serialize the items of your array. Not the best thing to do, but certainly better, than serializing the whole array, right?

Either way, any of this methods gets a clear advantage of being able to access an arbitrary element of the sequence and you don't have to worry about serializing arrays and ugly things like that.

As for getting it back. Well, get the appropriate row/sequence of rows with a query and, well, use a loop.. right?

PHP Fatal error: Call to undefined function json_decode()

you might also consider avoiding the core PHP module altogether.

It is quite common to use the guzzle json tools as a library in PHP apps these days. If your app is a composer app, it is trivial to include them as a part of a composer build. The guzzle tool, as a library, would be a turnkey replacement for the json tool, if you tell PHP to autoinclude the tool.

http://docs.guzzlephp.org/en/stable/search.html?q=json_encode#

http://apigen.juzna.cz/doc/guzzle/guzzle/function-GuzzleHttp.json_decode.html

How do I return multiple values from a function in C?

Option 1: Declare a struct with an int and string and return a struct variable.

struct foo {    
 int bar1;
 char bar2[MAX];
};

struct foo fun() {
 struct foo fooObj;
 ...
 return fooObj;
}

Option 2: You can pass one of the two via pointer and make changes to the actual parameter through the pointer and return the other as usual:

int fun(char **param) {
 int bar;
 ...
 strcpy(*param,"....");
 return bar;
}

or

 char* fun(int *param) {
 char *str = /* malloc suitably.*/
 ...
 strcpy(str,"....");
 *param = /* some value */
 return str;
}

Option 3: Similar to the option 2. You can pass both via pointer and return nothing from the function:

void fun(char **param1,int *param2) {
 strcpy(*param1,"....");
 *param2 = /* some calculated value */
}

Is it really impossible to make a div fit its size to its content?

you can also use

word-break: break-all;

when nothing seems working this works always ;)

Change the maximum upload file size

As changing globally is somewhat risky, I was trying to increase max upload value for a single script big_file_upload.php. For some reason ini_set didn't help. After some reasearch I've come up with this. Put it in .htaccess (unless name changed via AccessFileName)

<If "%{REQUEST_URI} == '/subfolder/big_file_upload.php'" >
php_value upload_max_filesize 200M
php_value post_max_size 200M
</If>
<Else>
php_value upload_max_filesize 1M
php_value post_max_size 1M
</Else>

Worked for me.

C# Iterate through Class properties

Yes, you could make an indexer on your Record class that maps from the property name to the correct property. This would keep all the binding from property name to property in one place eg:

public class Record
{
    public string ItemType { get; set; }

    public string this[string propertyName]
    {
        set
        {
            switch (propertyName)
            {
                case "itemType":
                    ItemType = value;
                    break;
                    // etc
            }   
        }
    }
}

Alternatively, as others have mentioned, use reflection.

How to determine the content size of a UIWebView?

This's weird!

I tested the solutions both sizeThatFits: and [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] are NOT working for me.

However, I found an interesting easy way to get the right height of webpage content. Currently, I used it in my delegate method scrollViewDidScroll:.

CGFloat contentHeight = scrollView.contentSize.height - CGRectGetHeight(scrollView.frame);

Verified in iOS 9.3 Simulator/Device, good luck!

EDIT:

Background: The html content is calculated by my string variable and HTTP content template, loaded by method loadHTMLString:baseURL:, no registered JS scripts there.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

I used to have the same problem.

Your config use security="none" so cannot generate _csrf:

<http pattern="/login.jsp" security="none"/>

you can set access="IS_AUTHENTICATED_ANONYMOUSLY" for page /login.jsp replace above config:

<http>
    <intercept-url pattern="/login.jsp*" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
    <intercept-url pattern="/**" access="ROLE_USER"/>
    <form-login login-page="/login.jsp"
            authentication-failure-url="/login.jsp?error=1"
            default-target-url="/index.jsp"/>
    <logout/>
    <csrf />
</http>

Correct format specifier to print pointer or address?

Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

*) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from <inttypes.h>, added in C99.

All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

printf("x lives at %p.\n", (void*)&x);

HttpClient - A task was cancelled?

in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception

My solution is

catch (Exception ex)
            {
                if (ex.InnerException is TimeoutException)
                {
                    ex = ex.InnerException;
                }
                else if (ex is TaskCanceledException)
                {
                    if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                    {
                        ex = new TimeoutException("Timeout occurred");
                    }
                }                
                Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);
            }

keyCode values for numeric keypad?

Docs says the order of events related to the onkeyxxx event:

  1. onkeydown
  2. onkeypress
  3. onkeyup

If you use like below code, it fits with also backspace and enter user interactions. After you can do what you want in onKeyPress or onKeyUp events. Code block trigger event.preventDefault function if the value is not number,backspace or enter.

onInputKeyDown = event => {
    const { keyCode } = event;
    if (
      (keyCode >= 48 && keyCode <= 57) ||
      (keyCode >= 96 && keyCode <= 105) ||
      keyCode === 8 || //Backspace key
      keyCode === 13   //Enter key
    ) {
    } else {
      event.preventDefault();
    }
  };

Remove last character from C++ string

buf.erase(buf.size() - 1);

This assumes you know that the string is not empty. If so, you'll get an out_of_range exception.

How can I calculate the number of years between two dates?

Maybe my function can explain better how to do this in a simple way without loop, calculations and/or libs

_x000D_
_x000D_
function checkYearsDifference(birthDayDate){_x000D_
    var todayDate = new Date();_x000D_
    var thisMonth = todayDate.getMonth();_x000D_
    var thisYear = todayDate.getFullYear();_x000D_
    var thisDay = todayDate.getDate();_x000D_
    var monthBirthday = birthDayDate.getMonth(); _x000D_
    var yearBirthday = birthDayDate.getFullYear();_x000D_
    var dayBirthday = birthDayDate.getDate();_x000D_
    //first just make the difference between years_x000D_
    var yearDifference = thisYear - yearBirthday;_x000D_
    //then check months_x000D_
    if (thisMonth == monthBirthday){_x000D_
      //if months are the same then check days_x000D_
      if (thisDay<dayBirthday){_x000D_
        //if today day is before birthday day_x000D_
        //then I have to remove 1 year_x000D_
        //(no birthday yet)_x000D_
        yearDifference = yearDifference -1;_x000D_
      }_x000D_
      //if not no action because year difference is ok_x000D_
    }_x000D_
    else {_x000D_
      if (thisMonth < monthBirthday) {_x000D_
        //if actual month is before birthday one_x000D_
        //then I have to remove 1 year_x000D_
        yearDifference = yearDifference -1;_x000D_
      }_x000D_
      //if not no action because year difference is ok_x000D_
    }_x000D_
    return yearDifference;_x000D_
  }
_x000D_
_x000D_
_x000D_

How does lock work exactly?

Its simpler than you think.

According to Microsoft: The lock keyword ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

The lock keyword calls Enter at the start of the block and Exit at the end of the block. lock keyword actually handles Monitor class at back end.

For example:

private static readonly Object obj = new Object();

lock (obj)
{
    // critical section
}

In the above code, first the thread enters a critical section, and then it will lock obj. When another thread tries to enter, it will also try to lock obj, which is already locked by the first thread. Second thread will have to wait for the first thread to release obj. When the first thread leaves, then another thread will lock obj and will enter the critical section.

Search all the occurrences of a string in the entire project in Android Studio

Android Studio 3.3 seems to have changed the shortcut to search for all references (find in path) on macOS.

In order to do that you should use Ctrl + Shift + F now (instead of Command + Shift + F as wrote on the previous answers):

UPDATE

To replace in path just use Ctrl + Shift + R.

enter image description here

On design patterns: When should I use the singleton?

It can be very pragmatic to configure specific infrastructure concerns as singletons or global variables. My favourite example of this is Dependency Injection frameworks that make use of singletons to act as a connection point to the framework.

In this case you are taking a dependency on the infrastructure to simplify using the library and avoid unneeded complexity.

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Dumb question/answer perhaps, but have you tried dd/MM/yyyy? Note the capitalization.

mm is for minutes with a leading zero. So I doubt that's what you want.

This may be helpful: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

Remove all non-"word characters" from a String in Java, leaving accented characters?

Well, here is one solution I ended up with, but I hope there's a more elegant one...

StringBuilder result = new StringBuilder();
for(int i=0; i<name.length(); i++) {
    char tmpChar = name.charAt( i );
    if (Character.isLetterOrDigit( tmpChar) || tmpChar == '_' ) {
        result.append( tmpChar );
    }
}

result ends up with the desired result...

Text file in VBA: Open/Find Replace/SaveAs/Close File

Guess I'm too late...

Came across the same problem today; here is my solution using FileSystemObject:

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close

Directory.GetFiles: how to get only filename, not full path?

Use this to obtain only the filename.

Path.GetFileName(files[0]);

DataSet panel (Report Data) in SSRS designer is gone

View -> Datasets (bottom of menu, above Refresh)

PHP Constants Containing Arrays?

Yes, You can define an array as constant. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

<?php
    // Works as of PHP 5.3.0
    const CONSTANT = 'Hello World';
    echo CONSTANT;

    // Works as of PHP 5.6.0
    const ANOTHER_CONST = CONSTANT.'; Goodbye World';
    echo ANOTHER_CONST;

    const ANIMALS = array('dog', 'cat', 'bird');
    echo ANIMALS[1]; // outputs "cat"

    // Works as of PHP 7
    define('ANIMALS', array(
        'dog',
        'cat',
        'bird'
    ));
    echo ANIMALS[1]; // outputs "cat"
?>

With the reference of this link

Have a happy coding.

getting the X/Y coordinates of a mouse click on an image with jQuery

note! there is a difference between e.clientX & e.clientY and e.pageX and e.pageY

try them both out and make sure you are using the proper one. clientX and clientY change based on scrolling position

How to get script of SQL Server data?

Check out SSMS Tool Pack. It works in Management Studio 2005 and 2008. There is an option to generate insert statements which I've found helpful moving small amounts of data from one system to another.

With this option you will have to script out the DDL separately.

EXCEL Multiple Ranges - need different answers for each range

Nested if's in Excel Are ugly:

=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))

That should cover it.

How to convert password into md5 in jquery?

You need additional plugin for this.

take a look at this plugin

Difference between a Seq and a List in Scala

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList.

A List is a Seq that is implemented as an immutable linked list. It's best used in cases with last-in first-out (LIFO) access patterns.

Here is the complete collection class hierarchy from the Scala FAQ:

enter image description here

Import Excel spreadsheet columns into SQL Server database

This may sound like the long way around, but you may want to look at using Excel to generate INSERT SQL code that you can past into Query Analyzer to create your table.

Works well if you cant use the wizards because the excel file isn't on the server

How to detect scroll direction

var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$(document).bind(mousewheelevt, 
function(e)
    {
        var evt = window.event || e //equalize event object     
        evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible               
        var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
        if(delta > 0) 
            {
            scrollup();
            }
        else
            {
            scrolldown();
            }   
    }
);

Determining complexity for recursive functions (Big O notation)

The key here is to visualise the call tree. Once done that, the complexity is:

nodes of the call tree * complexity of other code in the function

the latter term can be computed the same way we do for a normal iterative function.

Instead, the total nodes of a complete tree are computed as

                  C^L - 1
                  -------  , when C>1
               /   C - 1
              /
 # of nodes =
              \    
               \ 
                  L        , when C=1

Where C is number of children of each node and L is the number of levels of the tree (root included).

It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".

So, in the examples above:

  1. the call tree here is C = 1, L = n+1. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n+1) * O(1) = O(n)
n     level 1
n-1   level 2
n-2   level 3
n-3   level 4
... ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n/5) * O(1) = O(n)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5
  1. call tree here is C = 1, L = log(n). Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = log5(n) * O(1) = O(log(n))
n
n/5
n/5^2
n/5^3
... ~ log5(n) levels -> L = log5(n)
  1. call tree here is C = 2, L = n. Complexity of the rest of function is O(1). This time we use the full formula for the number of nodes in the call tree because C > 1. Therefore total complexity is (C^L-1)/(C-1) * O(1) = (2^n - 1) * O(1) = O(2^n).
               n                   level 1
      n-1             n-1          level 2
  n-2     n-2     n-2     n-2      ...
n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3    ...     
              ...                ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(n). Therefore total complexity is L * O(1) = (n/5) * O(n) = O(n^2)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5

numpy get index where value is true

To get the row numbers where at least one item is larger than 15:

>>> np.where(np.any(e>15, axis=1))
(array([1, 2], dtype=int64),)

PHP Convert String into Float/Double

If the function floatval does not work you can try to make this :

    $string = "2968789218";
    $float = $string * 1.0;
    echo $float;

But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

You can do it using the "collapse" directive: http://jsfiddle.net/iscrow/Es4L3/ (check the two "Note" in the HTML).

        <!-- Note: set the initial collapsed state and change it when clicking -->
        <a ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed" class="btn btn-navbar">
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
           <span class="icon-bar"></span>
        </a>
        <a class="brand" href="#">Title</a>
           <!-- Note: use "collapse" here. The original "data-" settings are not needed anymore. -->
           <div collapse="navCollapsed" class="nav-collapse collapse navbar-responsive-collapse">
              <ul class="nav">

That is, you need to store the collapsed state in a variable, and changing the collapsed also by (simply) changing the value of that variable.


Release 0.14 added a uib- prefix to components:

https://github.com/angular-ui/bootstrap/wiki/Migration-guide-for-prefixes

Change: collapse to uib-collapse.

git replace local version with remote version

I understand the question as this: you want to completely replace the contents of one file (or a selection) from upstream. You don't want to affect the index directly (so you would go through add + commit as usual).

Simply do

git checkout remote/branch -- a/file b/another/file

If you want to do this for extensive subtrees and instead wish to affect the index directly use

git read-tree remote/branch:subdir/

You can then (optionally) update your working copy by doing

git checkout-index -u --force

Django - Did you forget to register or load this tag?

{% load static %}

Please add this template tag on top of the HTML or base HTML file

Generating random number between 1 and 10 in Bash Shell Script

Here is example of pseudo-random generator when neither $RANDOM nor /dev/urandom is available

echo $(date +%S) | grep -o .$ | sed s/0/10/

How to fix: Error device not found with ADB.exe

Try any of the following solutions. I get errors with adb every now and then. And one of the following always works.

Solution 1
Open command prompt as administrator and enter

  1. adb kill-server
  2. adb start-server

Solution 2
Install drivers for your phone if you're not testing on emulator.

Solution 3
Open android sdk manager and install "Google USB Driver" from extras folder. (attached screenshot)

Android SDK Google USB Driver missing

Solution 4
Go to settings > Developer Options > Enable USB Debugging.
(If you don't see Developer Options, Go to Settings > About Phone > Keep tapping "Build number" until it says "You're a developer!"

Enable USB Debugging

Python Library Path

You can also make additions to this path with the PYTHONPATH environment variable at runtime, in addition to:

import sys
sys.path.append('/home/user/python-libs')

git checkout tag, git pull fails in branch

In order to just download updates:

git fetch origin master

However, this just updates a reference called origin/master. The best way to update your local master would be the checkout/merge mentioned in another comment. If you can guarantee that your local master has not diverged from the main trunk that origin/master is on, you could use git update-ref to map your current master to the new point, but that's probably not the best solution to be using on a regular basis...

What do these three dots in React do?

These three dots are called spread operator. Spread operator helps us to create a copy state or props in react.

Using spread operator in react state

const [myState, setMyState] = useState({
    variable1: 'test',
    variable2: '',
    variable3: ''
});

setMyState({...myState, variable2: 'new value here'});

in the above code spread operator will maintain a copy of current state and we will also add new value at same time, if we don't do this then state will have only value of variable2 spread operator helps us to write optimize code

How to change the DataTable Column Name?

after generating XML you can just Replace your XML <Marks>... content here </Marks> tags with <SubjectMarks>... content here </SubjectMarks>tag. and pass updated XML to your DB.

Edit: I here explain complete process here.

Your XML Generate Like as below.

<NewDataSet>
      <StudentMarks> 
          <StudentID>1</StudentID>
          <CourseID>100</CourseID>
          <SubjectCode>MT400</SubjectCode>
          <Marks>80</Marks>
      </StudentMarks>
      <StudentMarks> 
          <StudentID>1</StudentID>
          <CourseID>100</CourseID>
          <SubjectCode>MT400</SubjectCode>
          <Marks>79</Marks>
      </StudentMarks>
      <StudentMarks> 
          <StudentID>1</StudentID>
          <CourseID>100</CourseID>
          <SubjectCode>MT400</SubjectCode>
          <Marks>88</Marks>
      </StudentMarks>
  </NewDataSet>

Here you can assign XML to string variable like as

string strXML = DataSet.GetXML();

strXML = strXML.Replace ("<Marks>","<SubjectMarks>");
strXML = strXML.Replace ("<Marks/>","<SubjectMarks/>");

and now pass strXML To your DB. Hope it will help for you.

Scanner vs. BufferedReader

In currently latest JDK6 release/build (b27), the Scanner has a smaller buffer (1024 chars) as opposed to the BufferedReader (8192 chars), but it's more than sufficient.

As to the choice, use the Scanner if you want to parse the file, use the BufferedReader if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.

  • Parsing = interpreting the given input as tokens (parts). It's able to give back you specific parts directly as int, string, decimal, etc. See also all those nextXxx() methods in Scanner class.
  • Reading = dumb streaming. It keeps giving back you all characters, which you in turn have to manually inspect if you'd like to match or compose something useful. But if you don't need to do that anyway, then reading is sufficient.

How to write a simple Java program that finds the greatest common divisor between two numbers?

public static int GCD(int x, int y) {   
    int r;
    while (y!=0) {
        r = x%y;
        x = y;
        y = r;
    }
    return x;
}

What is secret key for JWT based authentication and how to generate it?

A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90

now install JWT using command

npm i jsonwebtoken

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});

output: enter image description here

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.

jQuery on window resize

function myResizeFunction() {
  ...
}

$(function() {
  $(window).resize(myResizeFunction).trigger('resize');
});

This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize') to run on page load instead.

UPDATE: Here's another option if you don't want to make use of any other third-party libraries.

This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).

It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.

function myResizeFunction() {
  var $window = $(this),
      height = Math.ceil($window.height()),
      previousHeight = $window.data('previousHeight');

  if (height !== previousHeight) {
    if (height < 819)
      previousHeight >= 819 && $('.footer').removeClass('hgte819');
    else if (!previousHeight || previousHeight < 819)
      $('.footer').addClass('hgte819');

    $window.data('previousHeight', height);
  }
}

$(function() {
  $(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});

As an example, you might have the following as some of your CSS rules:

.footer {
  bottom: auto;
  left: auto;
  position: static;
}

.footer.hgte819 {
  bottom: 3px;
  left: 0;
  position: absolute;
}

How to find the last day of the month from date?

If you use the Carbon API extension for PHP DateTime, you can get the last day of the month with:

$date = Carbon::now();
$date->addMonth();
$date->day = 0;
echo $date->toDateString(); // use toDateTimeString() to get date and time 

Microsoft Excel mangles Diacritics in .csv files?

As Fregal said \uFEFF is the way to go.

<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%>
<%
Response.Clear();
Response.ContentType = "text/csv";
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition", "attachment; filename=excelTest.csv");
Response.Write("\uFEFF");
// csv text here
%>

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

AngularJS : Why ng-bind is better than {{}} in angular?

ng-bind is better than {{...}}

For example, you could do:

<div>
  Hello, {{variable}}
</div>

This means that the whole text Hello, {{variable}} enclosed by <div> will be copied and stored in memory.

If instead you do something like this:

<div>
  Hello, <span ng-bind="variable"></span>
</div>

Only the value of the value will be stored in memory, and angular will register a watcher (watch expression) which consists of the variable only.

Interface or an Abstract Class: which one to use?

Just wanted to add an example of when you may need to use both. I am currently writing a file handler bound to a database model in a general purpose ERP solution.

  • I have multiple abstract classes which handle the standard crud and also some specialty functionality like conversion and streaming for different categories of files.
  • The file access interface defines a common set of methods which are needed to get, store and delete a file.

This way, I get to have multiple templates for different files and a common set of interface methods with clear distinction. The interface gives the correct analogy to the access methods rather than what would have been with a base abstract class.

Further down the line when I will make adapters for different file storage services, this implementation will allow the interface to be used elsewhere in totally different contexts.

How to manage local vs production settings in Django?

I use a slightly modified version of the "if DEBUG" style of settings that Harper Shelby posted. Obviously depending on the environment (win/linux/etc.) the code might need to be tweaked a bit.

I was in the past using the "if DEBUG" but I found that occasionally I needed to do testing with DEUBG set to False. What I really wanted to distinguish if the environment was production or development, which gave me the freedom to choose the DEBUG level.

PRODUCTION_SERVERS = ['WEBSERVER1','WEBSERVER2',]
if os.environ['COMPUTERNAME'] in PRODUCTION_SERVERS:
    PRODUCTION = True
else:
    PRODUCTION = False

DEBUG = not PRODUCTION
TEMPLATE_DEBUG = DEBUG

# ...

if PRODUCTION:
    DATABASE_HOST = '192.168.1.1'
else:
    DATABASE_HOST = 'localhost'

I'd still consider this way of settings a work in progress. I haven't seen any one way to handling Django settings that covered all the bases and at the same time wasn't a total hassle to setup (I'm not down with the 5x settings files methods).

Pass array to mvc Action via AJAX

If you're using ASP.NET Core MVC and need to handle the square brackets (rather than use the jQuery "traditional" option), the only option I've found is to manually build the IEnumerable in the contoller method.

string arrayKey = "p[]=";
var pArray = HttpContext.Request.QueryString.Value
    .Split('&')
    .Where(s => s.Contains(arrayKey))
    .Select(s => s.Substring(arrayKey.Length));

"Missing return statement" within if / for / while

That is illegal syntax. It is not an optional thing for you to return a variable. You MUST return a variable of the type you specify in your method.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
}

You are effectively saying, I promise any class can use this method(public) and I promise it will always return a String(String).

Then you are saying IF my condition is true I will return x. Well that is too bad, there is no IF in your promise. You promised that myMethod will ALWAYS return a String. Even if your condition is ALWAYS true the compiler has to assume that there is a possibility of it being false. Therefore you always need to put a return at the end of your non-void method outside of any conditions JUST IN CASE all of your conditions fail.

public String myMethod()
{
    if(condition)
    {
       return x;
    }
  return ""; //or whatever the default behavior will be if all of your conditions fail to return.
}

How do I limit the number of decimals printed for a double?

Use the DecimalFormat class to format the double

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Skip to next iteration in loop vba

I use Goto

  For x= 1 to 20

       If something then goto continue

       skip this code

  Continue:

  Next x

Convert JavaScript string in dot notation into an object reference

I have extended the elegant answer by ninjagecko so that the function handles both dotted and/or array style references, and so that an empty string causes the parent object to be returned.

Here you go:

string_to_ref = function (object, reference) {
    function arr_deref(o, ref, i) { return !ref ? o : (o[ref.slice(0, i ? -1 : ref.length)]) }
    function dot_deref(o, ref) { return ref.split('[').reduce(arr_deref, o); }
    return !reference ? object : reference.split('.').reduce(dot_deref, object);
};

See my working jsFiddle example here: http://jsfiddle.net/sc0ttyd/q7zyd/

How can I export a GridView.DataSource to a datatable or dataset?

You should convert first DataSource in BindingSource, look example

BindingSource bs = (BindingSource)dgrid.DataSource; // Se convierte el DataSource 
DataTable tCxC = (DataTable) bs.DataSource;

With the data of tCxC you can do anything.

How to overwrite styling in Twitter Bootstrap

If you want to overwrite any css in bootstrap use !important

Let's say here is the page header class in bootstrap which have 40px margin on top, my client don't like it and he want it to be 15 on top and 10 on bottom only

.page-header {
    border-bottom: 1px solid #EEEEEE;
    margin: 40px 0 20px;
    padding-bottom: 9px;
}

So I added on class in my site.css file with the same name like this

.page-header
{
    padding-bottom: 9px;
    margin: 15px 0 10px 0px !important;
}

Note the !important with my margin, which will overwrite the margin of bootstarp page-header class margin.

Item frequency count in Python

freqs = {}
for word in words:
    freqs[word] = freqs.get(word, 0) + 1 # fetch and increment OR initialize

I think this results to the same as Triptych's solution, but without importing collections. Also a bit like Selinap's solution, but more readable imho. Almost identical to Thomas Weigel's solution, but without using Exceptions.

This could be slower than using defaultdict() from the collections library however. Since the value is fetched, incremented and then assigned again. Instead of just incremented. However using += might do just the same internally.

Android - implementing startForeground for a service?

I'd start by completely filling in the Notification. Here is a sample project demonstrating the use of startForeground().

500 internal server error, how to debug

You can turn on your PHP errors with error_reporting:

error_reporting(E_ALL);
ini_set('display_errors', 'on');

Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:

Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.

You should set display_errors = 1 in your php.ini file and restart the server.

How to expire a cookie in 30 minutes using jQuery?

30 minutes is 30 * 60 * 1000 miliseconds. Add that to the current date to specify an expiration date 30 minutes in the future.

 var date = new Date();
 var minutes = 30;
 date.setTime(date.getTime() + (minutes * 60 * 1000));
 $.cookie("example", "foo", { expires: date });

align textbox and text/labels in html?

I like to set the 'line-height' in the css for the divs to get them to line up properly. Here is an example of how I do it using asp and css:

ASP:

<div id="profileRow1">
    <div id="profileRow1Col1" class="righty">
        <asp:Label ID="lblCreatedDateLabel" runat="server" Text="Date Created:"></asp:Label><br />
        <asp:Label ID="lblLastLoginDateLabel" runat="server" Text="Last Login Date:"></asp:Label><br />
        <asp:Label ID="lblUserIdLabel" runat="server" Text="User ID:"></asp:Label><br />
        <asp:Label ID="lblUserNameLabel" runat="server" Text="Username:"></asp:Label><br />
        <asp:Label ID="lblFirstNameLabel" runat="server" Text="First Name:"></asp:Label><br />
        <asp:Label ID="lblLastNameLabel" runat="server" Text="Last Name:"></asp:Label><br />
    </div>
    <div id="profileRow1Col2">
        <asp:Label ID="lblCreatedDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
        <asp:Label ID="lblLastLoginDate" runat="server" Text="00/00/00 00:00:00"></asp:Label><br />
        <asp:Label ID="lblUserId" runat="server" Text="UserId"></asp:Label><br />
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br />
    </div>
</div>

And here is the code in the CSS file to make all of the above fields look nice and neat:

#profileRow1{width:100%;line-height:40px;}
#profileRow1Col1{float:left; width:25%; margin-right:20px;}
#profileRow1Col2{float:left; width:25%;}
.righty{text-align:right;}

you can basically pull everything but the DIV tags and replace with your own content.

Trust me when I say it looks aligned the way the image in the original post does!

I would post a screenshot but Stack wont let me: Oops! Your edit couldn't be submitted because: We're sorry, but as a spam prevention mechanism, new users aren't allowed to post images. Earn more than 10 reputation to post images.

:)

Add / Change parameter of URL and redirect to the new URL

To do it in PHP: You have a couple of parameters to view your page, lets say action and view-all. You will (probably) access these already with $action = $_GET['action'] or whatever, maybe setting a default value.

Then you decide depending on that if you want to swich a variable like $viewAll = $viewAll == 'Yes' ? 'No' : 'Yes'.

And in the end you just build the url with these values again like

$clickUrl = $_SERVER['PHP_SELF'] . '?action=' . $action . '&view-all=' . $viewAll;

And thats it.

So you depend on the page status and not the users url (because maybe you decide later that $viewAll is Yes as default or whatever).

Plot multiple lines in one graph

You should bring your data into long (i.e. molten) format to use it with ggplot2:

library("reshape2")
mdf <- melt(mdf, id.vars="Company", value.name="value", variable.name="Year")

And then you have to use aes( ... , group = Company ) to group them:

ggplot(data=mdf, aes(x=Year, y=value, group = Company, colour = Company)) +
    geom_line() +
    geom_point( size=4, shape=21, fill="white")

enter image description here

javac : command not found

I don't know exactly what yum install java will actually install. But to check for javac existence do:

> updatedb
> locate javac

preferably as root. If it's not there you've probably only installed the Java runtime (JRE) and not the Java Development Kit (JDK). You're best off getting this from the Oracle site: as the Linux repos may be slightly behind with latest versions and also they seem to only supply the open-jdk as opposed to the Oracle/Sun one, which I would prefer given the choice.

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

Go to Your Build.gradle and add below dependencies for both Java 9 or Java 10.

sourceCompatibility = 10 // You can also decrease your souce compatibility to 1.8 

//java 9+ does not have Jax B Dependents

    compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
    compile group: 'com.sun.xml.bind', name: 'jaxb-core', version: '2.3.0'
    compile group: 'com.sun.xml.bind', name: 'jaxb-impl', version: '2.3.0'
    compile group: 'javax.activation', name: 'activation', version: '1.1.1'

Find a file in python

If you are using Python on Ubuntu and you only want it to work on Ubuntu a substantially faster way is the use the terminal's locate program like this.

import subprocess

def find_files(file_name):
    command = ['locate', file_name]

    output = subprocess.Popen(command, stdout=subprocess.PIPE).communicate()[0]
    output = output.decode()

    search_results = output.split('\n')

    return search_results

search_results is a list of the absolute file paths. This is 10,000's of times faster than the methods above and for one search I've done it was ~72,000 times faster.

How does cellForRowAtIndexPath work?

Basically it's designing your cell, The cellforrowatindexpath is called for each cell and the cell number is found by indexpath.row and section number by indexpath.section . Here you can use a label, button or textfied image anything that you want which are updated for all rows in the table. Answer for second question In cell for row at index path use an if statement

In Objective C

-(UITableViewCell *)tableView:(UITableView *)tableView  cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

 NSString *CellIdentifier = @"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if(tableView == firstTableView)
  {
      //code for first table view 
      [cell.contentView addSubview: someView];
  }

  if(tableview == secondTableView)
  {
      //code for secondTableView 
      [cell.contentView addSubview: someView];
  }
  return cell;
}

In Swift 3.0

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!

  if(tableView == firstTableView)   {
     //code for first table view 
  }

  if(tableview == secondTableView)      {
     //code for secondTableView 
  }

  return cell
}

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

Detect browser or tab closing

window.onbeforeunload = function ()
{       

    if (isProcess > 0) 
    {
        return true;       
    }   

    else
    { 
        //do something      
    }
}; 

This function show a confirmation dialog box if you close window or refresh page during any process in browser.This function work in all browsers.You have to set isProcess var in your ajax process.

Sorting a tab delimited file

If you want to make it easier for yourself by only having tabs, replace the spaces with tabs:

tr " " "\t" < <file> | sort <options>

int array to string

You can simply use String.Join function, and as separator use string.Empty because it uses StringBuilder internally.

string result = string.Join(string.Empty, new []{0,1,2,3,0,1});

E.g.: If you use semicolon as separator, the result would be 0;1;2;3;0;1.

It actually works with null separator, and second parameter can be enumerable of any objects, like:

string result = string.Join(null, new object[]{0,1,2,3,0,"A",DateTime.Now});

SQL Server: Difference between PARTITION BY and GROUP BY

It has really different usage scenarios. When you use GROUP BY you merge some of the records for the columns that are same and you have an aggregation of the result set.

However when you use PARTITION BY your result set is same but you just have an aggregation over the window functions and you don't merge the records, you will still have the same count of records.

Here is a rally helpful article explaining the difference: http://alevryustemov.com/sql/sql-partition-by/

Double.TryParse or Convert.ToDouble - which is faster and safer?

I generally try to avoid the Convert class (meaning: I don't use it) because I find it very confusing: the code gives too few hints on what exactly happens here since Convert allows a lot of semantically very different conversions to occur with the same code. This makes it hard to control for the programmer what exactly is happening.

My advice, therefore, is never to use this class. It's not really necessary either (except for binary formatting of a number, because the normal ToString method of number classes doesn't offer an appropriate method to do this).

Find text in string with C#

  string WordInBetween(string sentence, string wordOne, string wordTwo)
        {

            int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;

            int end = sentence.IndexOf(wordTwo) - start - 1;

            return sentence.Substring(start, end);


        }

How to fix request failed on channel 0

As you already found the -T flag that create a PTY, I will just respond to the second part:

shell request failed on channel 0

You should pass a command:

ssh [email protected] -p 22 help

After reading back the manual here: https://www.jenkins.io/doc/book/managing/cli/, I find it not really clear that it would not work without a command. But as stated by @U.V., the ssh interface is not a console interface, rather a connection utility. So you need to pass a command...

If someone from the "jenkins" team pass accross this post, it would be great that if we pass no command, the help would show up :-)

How to remove outliers from a dataset

Wouldn't:

z <- df[df$x > quantile(df$x, .25) - 1.5*IQR(df$x) & 
        df$x < quantile(df$x, .75) + 1.5*IQR(df$x), ] #rows

accomplish this task quite easily?

How to unzip files programmatically in Android?

Minimal example I used to unzip a specific file from my zipfile into my applications cache folder. I then read the manifest file using a different method.

private void unzipUpdateToCache() {
    ZipInputStream zipIs = new ZipInputStream(context.getResources().openRawResource(R.raw.update));
    ZipEntry ze = null;

    try {

        while ((ze = zipIs.getNextEntry()) != null) {
            if (ze.getName().equals("update/manifest.json")) {
                FileOutputStream fout = new FileOutputStream(context.getCacheDir().getAbsolutePath() + "/manifest.json");

                byte[] buffer = new byte[1024];
                int length = 0;

                while ((length = zipIs.read(buffer))>0) {
                    fout.write(buffer, 0, length);
                }
                zipIs .closeEntry();
                fout.close();
            }
        }
        zipIs .close();

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

}

Getting unix timestamp from Date()

Use SimpleDateFormat class. Take a look on its javadoc: it explains how to use format switches.

Error occurred during initialization of boot layer FindException: Module not found

I solved this issue by going into Properties -> Java Build Path and reordering my source folder so it was above the JRE System Library.

What is the easiest way to clear a database from the CLI with manage.py in Django?

I think Django docs explicitly mention that if the intent is to start from an empty DB again (which seems to be OP's intent), then just drop and re-create the database and re-run migrate (instead of using flush):

If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.

So for OP's case, we just need to:

  1. Drop the database from MySQL
  2. Recreate the database
  3. Run python manage.py migrate

Android Studio Run/Debug configuration error: Module not specified

I realized following line was missing in settings.gradle file

include ':app'

make sure you include ":app" module

Unique constraint on multiple columns

If the table is already created in the database, then you can add a unique constraint later on by using this SQL query:

ALTER TABLE dbo.User
  ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)

JavaScript/jQuery - "$ is not defined- $function()" error

I have solved it as follow.

import $ from 'jquery';

(function () {
    // ... code let script = $(..)
})();

How to change scroll bar position with CSS?

Here is another way, by rotating element with the scrollbar for 180deg, wrapping it's content into another element, and rotating that wrapper for -180deg. Check the snippet below

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 2px solid black;_x000D_
  margin: 15px;_x000D_
}_x000D_
#vertical {_x000D_
  direction: rtl;_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  background: gold;_x000D_
}_x000D_
#vertical p {_x000D_
  direction: ltr;_x000D_
  margin-bottom: 0;_x000D_
}_x000D_
#horizontal {_x000D_
  direction: rtl;_x000D_
  transform: rotate(180deg);_x000D_
  overflow-y: hidden;_x000D_
  overflow-x: scroll;_x000D_
  background: tomato;_x000D_
  padding-top: 30px;_x000D_
}_x000D_
#horizontal span {_x000D_
  direction: ltr;_x000D_
  display: inline-block;_x000D_
  transform: rotate(-180deg);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id=vertical>_x000D_
  <p>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content_x000D_
    <br>content</p>_x000D_
</div>_x000D_
<div id=horizontal><span> content_content_content_content_content_content_content_content_content_content_content_content_content_content</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In JavaScript can I make a "click" event fire programmatically for a file input element?

I have been searching for solution to this whole day. And these are the conclusions that I have made:

  1. For the security reasons Opera and Firefox don't allow to trigger file input.
  2. The only convenient alternative is to create a "hidden" file input (using opacity, not "hidden" or "display: none"!) and afterwards create the button "below" it. In this way the button is seen but on user click it actually activates the file input.

Hope this helps! :)

<div style="display: block; width: 100px; height: 20px; overflow: hidden;">
<button style="width: 110px; height: 30px; position: relative; top: -5px; left: -5px;"><a href="javascript: void(0)">Upload File</a></button>
<input type="file" id="upload_input" name="upload" style="font-size: 50px; width: 120px; opacity: 0; filter:alpha(opacity=0);  position: relative; top: -40px;; left: -20px" />
</div>

How to close current tab in a browser window?

a bit late but this is what i found out...

window.close() will only work (IE is an exception) if the window that you are trying to close() was opened by a script using window.open() method.

!(please see the comment of @killstreet below about anchor tag with target _blank)

TLDR: chrome & firefox allow to close them.

you will get console error: Scripts may not close windows that were not opened by script. as an error and nothing else.

you could add a unique parameter in the URL to know if the page was opened from a script (like time) - but its just a hack and not a native functionality and will fail in some cases.

i couldn't find any way to know if the page was opened from a open() or not, and close will not throw and errors. this will NOT print "test":

try{
  window.close();
}
catch (e){
  console.log("text");
}

you can read in MDN more about the close() function

How do I run two commands in one line in Windows CMD?

It's simple: just differentiate them with && signs. Example:

echo "Hello World" && echo "GoodBye World".

"Goodbye World" will be printed after "Hello World".

How to create an object property from a variable value in JavaScript?

You cannot use a variable to access a property via dot notation, instead use the array notation.

var obj= {
     'name' : 'jroi'
};
var a = 'name';
alert(obj.a); //will not work
alert(obj[a]); //should work and alert jroi'

How do I set path while saving a cookie value in JavaScript?

document.cookie = "cookiename=Some Name; path=/";

This will do

Prevent linebreak after </div>

display:inline;

OR

float:left;

OR

display:inline-block; -- Might not work on all browsers.

What is the purpose of using a div here? I'd suggest a span, as it is an inline-level element, whereas a div is a block-level element.


Do note that each option above will work differently.

display:inline; will turn the div into the equivalent of a span. It will be unaffected by margin-top, margin-bottom, padding-top, padding-bottom, height, etc.

float:left; keeps the div as a block-level element. It will still take up space as if it were a block, however the width will be fitted to the content (assuming width:auto;). It can require a clear:left; for certain effects.

display:inline-block; is the "best of both worlds" option. The div is treated as a block element. It responds to all of the margin, padding, and height rules as expected for a block element. However, it is treated as an inline element for the purpose of placement within other elements.

Read this for more information.

C++, copy set to vector

Just use the constructor for the vector that takes iterators:

std::set<T> s;

//...

std::vector v( s.begin(), s.end() );

Assumes you just want the content of s in v, and there's nothing in v prior to copying the data to it.

How can I get onclick event on webview in android?

I think you can also use MotionEvent.ACTION_UP state, example:

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (v.getId()) {
    case R.id.iv:
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (isheadAndFootShow == false) {
                headLayout.setVisibility(View.VISIBLE);
                footLayout.setVisibility(View.VISIBLE);
                isheadAndFootShow = true;
            } else {
                headLayout.setVisibility(View.INVISIBLE);
                footLayout.setVisibility(View.INVISIBLE);
                isheadAndFootShow = false;
            }
            return true;
        }
        break;
    }

    return false;
}

Stopping an Android app from console

adb shell killall -9 com.your.package.name

according to MAC "mandatory access control" you probably have the permission to kill process which is not started by root

have fun!

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

contenteditable change events

_x000D_
_x000D_
const p = document.querySelector('p')_x000D_
const result = document.querySelector('div')_x000D_
const observer = new MutationObserver((mutationRecords) => {_x000D_
  result.textContent = mutationRecords[0].target.data_x000D_
  // result.textContent = p.textContent_x000D_
})_x000D_
observer.observe(p, {_x000D_
  characterData: true,_x000D_
  subtree: true,_x000D_
})
_x000D_
<p contenteditable>abc</p>_x000D_
<div />
_x000D_
_x000D_
_x000D_

Changing navigation bar color in Swift

Make sure to set the Button State for .normal

extension UINavigationBar {

    func makeContent(color: UIColor) {
        let attributes: [NSAttributedString.Key: Any]? = [.foregroundColor: color]

        self.titleTextAttributes = attributes
        self.topItem?.leftBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
        self.topItem?.rightBarButtonItem?.setTitleTextAttributes(attributes, for: .normal)
    }
}

P.S iOS 12, Xcode 10.1

How to remove part of a string?

Dynamically, if you want to remove (a) part(s) from (a) fixed index(es) of a string, use this function:

/**
 * Removes index/indexes from a string, using a delimiter.
 * 
 * @param string $string
 * @param int|int[] $index An index, or a list of indexes to be removed from string.
 * @param string $delimiter 
 * @return string
 * @todo Note: For PHP versions lower than 7.0, remove scalar type hints (i.e. the
 * types before each argument) and the return type.
 */
function removeFromString(string $string, $index, string $delimiter = " "): string
{
    $stringParts = explode($delimiter, $string);

    // Remove indexes from string parts
    if (is_array($index)) {
        foreach ($index as $i) {
            unset($stringParts[(int)($i)]);
        }
    } else {
        unset($stringParts[(int)($index)]);
    }

    // Join all parts together and return it
    return implode($delimiter, $stringParts);
}

For your purpose:

remove_from_str("REGISTER 11223344 here", 1); // Output: REGISTER here

One of its usages is to execute command-like strings, which you know their structures.

How to set value in @Html.TextBoxFor in Razor syntax?

I tried replacing value with Value and it worked out. It has set the value in input tag now.

How to cast an Object to an int

For Example Object variable; hastaId

Object hastaId = session.getAttribute("hastaID");

For Example Cast an Object to an int,hastaID

int hastaID=Integer.parseInt(String.valueOf(hastaId));

Search of table names

I know this is an old thread, but if you prefer case-insensitive searching:

SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE Lower(TABLE_NAME) LIKE Lower('%%')

How do I set the eclipse.ini -vm option?

My solution for Ubuntu Linux:

-vm
/home/daniel/Downloads/jdk1.6.0_17/bin
-startup
plugins/org.eclipse.equinox.launcher_1.1.1.R36x_v20101122_1400.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.2.R36x_v20101019_1345
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=256m
-Xms40m
-Xmx512m

How do you install Boost on MacOS?

Unless your compiler is different than the one supplied with the Mac XCode Dev tools, just follow the instructions in section 5.1 of Getting Started Guide for Unix Variants. The configuration and building of the latest source couldn't be easier, and it took all about about 1 minute to configure and 10 minutes to compile.

Could not load type from assembly error

Yet another solution: Old DLLs pointing to each other and cached by Visual Studio in

C:\Users\[yourname]\AppData\Local\Microsoft\VisualStudio\10.0\ProjectAssemblies

Exit VS, delete everything in this folder and Bob's your uncle.

How to convert an int to a hex string?

Note that for large values, hex() still works (some other answers don't):

x = hex(349593196107334030177678842158399357)
print(x)

Python 2: 0x4354467b746f6f5f736d616c6c3f7dL
Python 3: 0x4354467b746f6f5f736d616c6c3f7d

For a decrypted RSA message, one could do the following:

import binascii

hexadecimals = hex(349593196107334030177678842158399357)

print(binascii.unhexlify(hexadecimals[2:-1])) # python 2
print(binascii.unhexlify(hexadecimals[2:])) # python 3

Redirecting from cshtml page

Would be safer to do this.

@{ Response.Redirect("~/Account/LogIn?returnUrl=Products");}

So the controller for that action runs as well, to populate any model the view needs.

Source
Redirect from a view to another view

Although as @Satpal mentioned, I do recommend you do the redirecting on your controller.

add column to mysql table if it does not exist

Check if Column Exist or not in PDO (100%)

{
    if(isset($_POST['Add']))
    {
        $ColumnExist = $dbh->prepare("SELECT * FROM ColumnChecker where column_name='$insert_column_name' LIMIT 1");
        $ColumnExist ->execute();
        $ColumnName = $ColumnExist->fetch(2);
        $Display_Column_Name = $ColumnName['column_name'];

        if($Display_Column_Name == $insert_column_name)
        {
            echo "$Display_Column_Name already exist";
        } //*****************************
        else 
        {
            $InsertColumn = $dbh->prepare("insert into ColumnChecker ( column_name ) values ('$insert_column_name')");
            $InsertColumn->execute();

            if($InsertColumn)
            {
                $Add = $dbh->prepare("ALTER TABLE `$Table` ADD `$insert_column_name` $insert_column_type($insert_column_Length) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ");
                $Add->execute();

                if($Add)
                {
                    echo 'Table has been updated';  
                }
                else 
                {
                    echo 'Sorry! Try again...'; 
                }
            }   
        }
    }
}#Add Column into Table :)

How to refer to Excel objects in Access VBA?

I dissent from both the answers. Don't create a reference at all, but use late binding:

  Dim objExcelApp As Object
  Dim wb As Object

  Sub Initialize()
    Set objExcelApp = CreateObject("Excel.Application")
  End Sub

  Sub ProcessDataWorkbook()
     Set wb = objExcelApp.Workbooks.Open("path to my workbook")
     Dim ws As Object
     Set ws = wb.Sheets(1)

     ws.Cells(1, 1).Value = "Hello"
     ws.Cells(1, 2).Value = "World"

     'Close the workbook
     wb.Close
     Set wb = Nothing
  End Sub

You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().

This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.

Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

Stop fixed position at footer

$(window).scroll(() => {
    const footerToTop = $('.your-footer').position().top;
    const scrollTop = $(document).scrollTop() + $(window).height();
    const difference = scrollTop - footerToTop;
    const bottomValue = scrollTop > footerToTop ? difference : 0;
    $('.your-fixed-element').css('bottom', bottomValue);
});

Laravel 5.1 API Enable Cors

I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT and DELETE) which will be preceded by an OPTIONS request, specifying the middleware in the $routeMiddleware array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS as well. This is because without an OPTIONS route Laravel will internally respond to that method without the CORS headers.

So in short either define the middleware in the $middleware array which runs globally for all requests or if you're doing it in $middlewareGroups or $routeMiddleware then also define a route handler for OPTIONS. This can be done like this:

Route::match(['options', 'put'], '/route', function () {
    // This will work with the middleware shown in the accepted answer
})->middleware('cors');

I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    private static $allowedOriginsWhitelist = [
      'http://localhost:8000'
    ];

    // All the headers must be a string

    private static $allowedOrigin = '*';

    private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';

    private static $allowCredentials = 'true';

    private static $allowedHeaders = '';

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      if (! $this->isCorsRequest($request))
      {
        return $next($request);
      }

      static::$allowedOrigin = $this->resolveAllowedOrigin($request);

      static::$allowedHeaders = $this->resolveAllowedHeaders($request);

      $headers = [
        'Access-Control-Allow-Origin'       => static::$allowedOrigin,
        'Access-Control-Allow-Methods'      => static::$allowedMethods,
        'Access-Control-Allow-Headers'      => static::$allowedHeaders,
        'Access-Control-Allow-Credentials'  => static::$allowCredentials,
      ];

      // For preflighted requests
      if ($request->getMethod() === 'OPTIONS')
      {
        return response('', 200)->withHeaders($headers);
      }

      $response = $next($request)->withHeaders($headers);

      return $response;
    }

    /**
     * Incoming request is a CORS request if the Origin
     * header is set and Origin !== Host
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function isCorsRequest($request)
    {
      $requestHasOrigin = $request->headers->has('Origin');

      if ($requestHasOrigin)
      {
        $origin = $request->headers->get('Origin');

        $host = $request->getSchemeAndHttpHost();

        if ($origin !== $host)
        {
          return true;
        }
      }

      return false;
    }

    /**
     * Dynamic resolution of allowed origin since we can't
     * pass multiple domains to the header. The appropriate
     * domain is set in the Access-Control-Allow-Origin header
     * only if it is present in the whitelist.
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function resolveAllowedOrigin($request)
    {
      $allowedOrigin = static::$allowedOrigin;

      // If origin is in our $allowedOriginsWhitelist
      // then we send that in Access-Control-Allow-Origin

      $origin = $request->headers->get('Origin');

      if (in_array($origin, static::$allowedOriginsWhitelist))
      {
        $allowedOrigin = $origin;
      }

      return $allowedOrigin;
    }

    /**
     * Take the incoming client request headers
     * and return. Will be used to pass in Access-Control-Allow-Headers
     *
     * @param  \Illuminate\Http\Request  $request
     */
    private function resolveAllowedHeaders($request)
    {
      $allowedHeaders = $request->headers->get('Access-Control-Request-Headers');

      return $allowedHeaders;
    }
}

Also written a blog post on this.

Node.js setting up environment specific configs to be used with everyauth

My solution,

load the app using

NODE_ENV=production node app.js

Then setup config.js as a function rather than an object

module.exports = function(){
    switch(process.env.NODE_ENV){
        case 'development':
            return {dev setting};

        case 'production':
            return {prod settings};

        default:
            return {error or other settings};
    }
};

Then as per Jans solution load the file and create a new instance which we could pass in a value if needed, in this case process.env.NODE_ENV is global so not needed.

var Config = require('./conf'),
    conf = new Config();

Then we can access the config object properties exactly as before

conf.twitter.consumerKey

Fatal error: Class 'Illuminate\Foundation\Application' not found

In my case composer was not installed in that directory. So I run

composer install

then error resolved.

or you can try

composer update --no-scripts
cd bootstrap/cache/->rm -rf *.php
composer dump-autoload

bash script use cut command at variable and store result at another variable

You can avoid the loop and cut etc by using:

awk -F ':' '{system("ping " $1);}' config.txt

However it would be better if you post a snippet of your config.txt

How to sort an array of associative arrays by value of a given key in PHP?

You are right, the function you're looking for is array_multisort().

Here's an example taken straight from the manual and adapted to your case:

$price = array();
foreach ($inventory as $key => $row)
{
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

As of PHP 5.5.0 you can use array_column() instead of that foreach:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

For me the solution was to download the Android SDK and launch adb devices which started the adb daemon.

Can you use if/else conditions in CSS?

Yet another option (based on whether you want that if statement to be dynamically evaluated or not) is to use the C preprocessor, as described here.

How to format numbers?

This is an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):

function addSeperator(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

What's the best way to parse command line arguments?

Use optparse which comes with the standard library. For example:

#!/usr/bin/env python
import optparse

def main():
  p = optparse.OptionParser()
  p.add_option('--person', '-p', default="world")
  options, arguments = p.parse_args()
  print 'Hello %s' % options.person

if __name__ == '__main__':
  main()

Source: Using Python to create UNIX command line tools

However as of Python 2.7 optparse is deprecated, see: Why use argparse rather than optparse?

Specifying colClasses in the read.csv

Assuming your 'time' column has at least one observation with a non-numeric character and all your other columns only have numbers, then 'read.csv's default will be to read in 'time' as a 'factor' and all the rest of the columns as 'numeric'. Therefore setting 'stringsAsFactors=F' will have the same result as setting the 'colClasses' manually i.e.,

data <- read.csv('test.csv', stringsAsFactors=F)

CSS filter: make color image with transparency white

To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.

With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.

However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.

Here's a JSFiddle changing the colour of the JSFiddle logo.

_x000D_
_x000D_
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
    //Draw the original image so that you can fetch the colour data_x000D_
    ctx.drawImage(img,0,0);_x000D_
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
    _x000D_
    /*_x000D_
    imgData.data is a one-dimensional array which contains _x000D_
    the respective RGBA values for every pixel _x000D_
    in the selected region of the context _x000D_
    (note i+=4 in the loop)_x000D_
    */_x000D_
    _x000D_
    for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
   imgData.data[i] = 255; //Red, 0-255_x000D_
   imgData.data[i+1] = 255; //Green, 0-255_x000D_
   imgData.data[i+2] = 255; //Blue, 0-255_x000D_
   /* _x000D_
   imgData.data[i+3] contains the alpha value_x000D_
   which we are going to ignore and leave_x000D_
   alone with its original value_x000D_
   */_x000D_
    }_x000D_
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
    background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
_x000D_
_x000D_

jQuery.ajax returns 400 Bad Request

I think you just need to add 2 more options (contentType and dataType):

$('#my_get_related_keywords').click(function() {

    $.ajax({
            type: "POST",
            url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
            data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
            contentType: "application/json; charset=utf-8", // this
            dataType: "json", // and this
            success: function (msg) {
               //do something
            },
            error: function (errormessage) {
                //do something else
            }
        });
}

Where is git.exe located?

Just to add to a couple of answers already here:

On Windows, you can use the built in "where" instead of "which" (which is for Linux). So, where git will tell you the location of git assuming that it is in the system path.

If it is not in the system path, and you want a native (no downloads or installations), reasonable time command to find it, use dir /s git.exe

Set icon for Android application

Goto File->new->ImageAsset.

From their you can create Image Assets for your icon.

After that we will get icon image in mipmap different formats like hdpi,mdpi,xhdpi,xxhdpi,xxxhdpi.

Now goto AndroidManifest.xml

<application android:icon="@mipmap/your_Icon"> ....</application>

How to find the location of the Scheduled Tasks folder

On newer versions of Windows (Windows 10 and Windows Server 2016) the tasks you create are located in C:\Windows\Tasks. They will have the extension .job

For example if you create the task "DoWork" it will create the task in

C:\Windows\Tasks\DoWork.job

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

I like to make use of the css :before and a data-* attribute for the list

HTML:

<ul data-header="heading"> 
<li>list item </li>
<li>list item </li>
<li>list item </li>
</ul>

CSS:

ul:before{
    content:attr(data-header);
    font-size:120%;
    font-weight:bold;
    margin-left:-15px;
}

This will make a list with the header on it that is whatever text is specified as the list's data-header attribute. You can then easily style it to your needs.

Cannot connect to the Docker daemon on macOS

I had docker up to date, docker said it was running, and the diagnosis was good. I needed to unset some legacy environment variable (thanks https://docs.docker.com/docker-for-mac/troubleshoot/#workarounds-for-common-problems )

unset DOCKER_HOST
unset DOCKER_CERT_PATH
unset DOCKER_TLS_VERIFY

Python 101: Can't open file: No such file or directory

I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder

How to create an 2D ArrayList in java?

The best way is to use a List within a List:

List<List<String>> listOfLists = new ArrayList<List<String>>();  

What is time_t ultimately a typedef to?

The time_t Wikipedia article article sheds some light on this. The bottom line is that the type of time_t is not guaranteed in the C specification.

The time_t datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard time() library function. This type is a typedef defined in the standard header. ISO C defines time_t as an arithmetic type, but does not specify any particular type, range, resolution, or encoding for it. Also unspecified are the meanings of arithmetic operations applied to time values.

Unix and POSIX-compliant systems implement the time_t type as a signed integer (typically 32 or 64 bits wide) which represents the number of seconds since the start of the Unix epoch: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not. Systems using a 32-bit time_t type are susceptible to the Year 2038 problem.

selenium - chromedriver executable needs to be in PATH

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

How to make a machine trust a self-signed Java application

I was having the same issue. So I went to the Java options through Control Panel. Copied the web address that I was having an issue with to the exceptions and it was fixed.

Open Redis port for remote connections

Bind & protected-mode both are the essential steps. But if ufw is enabled then you will have to make redis port allow in ufw.

  1. Check ufw status ufw status if Status: active then allow redis-port ufw allow 6379
  2. vi /etc/redis/redis.conf
  3. Change the bind 127.0.0.1 to bind 0.0.0.0
  4. change the protected-mode yes to protected-mode no

How do I enable TODO/FIXME/XXX task tags in Eclipse?

For me, such tags are enabled by default. You can configure which task tags should be used in the workspace options: Java > Compiler > Task tags

alt text

Check if they are enabled in this location, and that should be enough to have them appear in the Task list (or the Markers view).

Extra note: reinstalling Eclipse won't change anything most of the time if you work on the same workspace. Most settings used by Eclipse are stored in the .metadata folder, in your workspace folder.

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

The Image pull policy will always actually help to pull the image every single time a new pod is created (this can be in any case like scaling the replicas, or pod dies and new pod is created)

But if you want to update the image of the current running pod, deployment is the best way. It leaves you flawless update without any problem (mainly when you have a persistent volume attached to the pod) :)

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

I had this, but, it was because I had added a NuGet package that had updated the binding redirects. Once I removed the package, the redirects were still there. I removed all of them, and then ran update-package -reinstall. This added the correct redirects.

Get img src with PHP

Use a HTML parser like DOMDocument and then evaluate the value you're looking for with DOMXpath:

$html = '<img id="12" border="0" src="/images/image.jpg"
         alt="Image" width="100" height="100" />';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"

Or for those who really need to save space:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

And for the one-liners out there:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

Could not load file or assembly 'System.Web.Mvc'

I added "Microsoft ASP.NET Razor" using Manage NuGet Packages.

With Add References, for some reason, I only had System.Web.Helpers 1.0.0 and 2.0.0... but not 3.0.0.

Another option, that worked form me was to delete the references to System.Web.Mvc and System.Web.Http... then re-add them browing to the package locations in the csproj file (you can most easily edit the project with a text editor):

<Reference Include="System.Web.Http">
  <HintPath>..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>

<Reference Include="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <HintPath>..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>

How to schedule a periodic task in Java?

These two classes can work together to schedule a periodic task:

Scheduled Task

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

Run Scheduled Task

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

Reference https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

How to add text at the end of each line in Vim?

If you want to add ',' at end of the lines starting with 'key', use:

:%s/key.*$/&,

Can you split/explode a field in a MySQL query?

It is possible to explode a string in a MySQL SELECT statement.

Firstly generate a series of numbers up to the largest number of delimited values you wish to explode. Either from a table of integers, or by unioning numbers together. The following generates 100 rows giving the values 1 to 100. It can easily be expanded to give larger ranges (add another sub query giving the values 0 to 9 for hundreds - hence giving 0 to 999, etc).

SELECT 1 + units.i + tens.i * 10 AS aNum
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens

This can be cross joined against your table to give you the values. Note that you use SUBSTRING_INDEX to get the delimited value up to a certain value, and then use SUBSTRING_INDEX to get that value, excluding previous ones.

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(clients.courseNames, ',', sub0.aNum), ',', -1) AS a_course_name
FROM clients
CROSS JOIN
(
    SELECT 1 + units.i + tens.i * 10 AS aNum, units.i + tens.i * 10 AS aSubscript
    FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
    CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0

As you can see there is a slight issue here that the last delimited value is repeated many times. To get rid of this you need to limit the range of numbers based on how many delimiters there are. This can be done by taking the length of the delimited field and comparing it to the length of the delimited field with the delimiters changed to '' (to remove them). From this you can get the number of delimiters:-

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(clients.courseNames, ',', sub0.aNum), ',', -1) AS a_course_name
FROM clients
INNER JOIN
(
    SELECT 1 + units.i + tens.i * 10 AS aNum
    FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
    CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
ON (1 + LENGTH(clients.courseNames) - LENGTH(REPLACE(clients.courseNames, ',', ''))) >= sub0.aNum

In the original example field you could (for example) count the number of students on each course based on this. Note that I have changed the sub query that gets the range of numbers to bring back 2 numbers, 1 is used to determine the course name (as these are based on starting at 1) and the other gets the subscript (as they are based starting at 0).

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(clients.courseNames, ',', sub0.aNum), ',', -1) AS a_course_name, COUNT(clientenrols.studentId)
FROM clients
INNER JOIN
(
    SELECT 1 + units.i + tens.i * 10 AS aNum, units.i + tens.i * 10 AS aSubscript
    FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units
    CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
) sub0
ON (1 + LENGTH(clients.courseNames) - LENGTH(REPLACE(clients.courseNames, ',', ''))) >= sub0.aNum
LEFT OUTER JOIN clientenrols
ON clientenrols.courseId = sub0.aSubscript
GROUP BY a_course_name

As you can see, it is possible but quite messy. And with little opportunity to use indexes it is not going to be efficient. Further the range must cope with the greatest number of delimited values, and works by excluding lots of duplicates; if the max number of delimited values is very large then this will slow things down dramatically. Overall it is generally far better to just properly normalise the database.

Getting output of system() calls in Ruby

I'd like to expand & clarify chaos's answer a bit.

If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:

output = `ls`
p output

or

printf output # escapes newline chars

Set value for particular cell in pandas DataFrame with iloc

another way is, you assign a column value for a given row based on the index position of a row, the index position always starts with zero, and the last index position is the length of the dataframe:

df["COL_NAME"].iloc[0]=x

How to update a menu item shown in the ActionBar?

In Kotlin 1.2 simply call:

invalidateOptionsMenu()

and the onCreateOptionsMenu function will be called again.

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

How to reference a method in javadoc?

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

{@link package.class#member label}

Examples

Method in the same class:

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

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

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

Method in a different package and not imported:

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

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

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

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

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

Labels

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

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

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

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

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

Type erasure and #member

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

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

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

Excel VBA date formats

Use value(cellref) on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173).

How to send an email using PHP?

The core way to send emails from PHP is to use its built in mail() function, but there are a couple of ready-to-use SDKs which can ease the integration:

  1. Swiftmailer
  2. PHPMailer
  3. Pepipost (works over HTTP hence SMTP port block issue can be avoided)
  4. Sendmail

P.S. I am employed with Pepipost.

How can one use multi threading in PHP applications

pcntl_fork won't work in a web server environment if it has safe mode turned on. In this case, it will only work in the CLI version of PHP.

How can I open multiple files using "with open" in Python?

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

How to count items in JSON object using command line?

The shortest expression is

curl 'http://…' | jq length

Can Python test the membership of multiple values in a list?

I'm pretty sure in is having higher precedence than , so your statement is being interpreted as 'a', ('b' in ['b' ...]), which then evaluates to 'a', True since 'b' is in the array.

See previous answer for how to do what you want.

Openssl : error "self signed certificate in certificate chain"

The solution for the error is to add this line at the top of the code:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

Two versions of python on linux. how to make 2.7 the default

All OS comes with a default version of python and it resides in /usr/bin. All scripts that come with the OS (e.g. yum) point this version of python residing in /usr/bin. When you want to install a new version of python you do not want to break the existing scripts which may not work with new version of python.

The right way of doing this is to install the python as an alternate version.

e.g.
wget http://www.python.org/ftp/python/2.7.3/Python-2.7.3.tar.bz2 
tar xf Python-2.7.3.tar.bz2
cd Python-2.7.3
./configure --prefix=/usr/local/
make && make altinstall

Now by doing this the existing scripts like yum still work with /usr/bin/python. and your default python version would be the one installed in /usr/local/bin. i.e. when you type python you would get 2.7.3

This happens because. $PATH variable has /usr/local/bin before usr/bin.

/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin

If python2.7 still does not take effect as the default python version you would need to do

export PATH="/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}