Programs & Examples On #Oscache

How would you implement an LRU cache in Java?

There are two open source implementations.

Apache Solr has ConcurrentLRUCache: https://lucene.apache.org/solr/3_6_1/org/apache/solr/util/ConcurrentLRUCache.html

There's an open source project for a ConcurrentLinkedHashMap: http://code.google.com/p/concurrentlinkedhashmap/

Undoing a git rebase

For multiple commits, remember that any commit references all the history leading up to that commit. So in Charles' answer, read "the old commit" as "the newest of the old commits". If you reset to that commit, then all the history leading up to that commit will reappear. This should do what you want.

Checking if element exists with Python Selenium

you could use is_displayed() like below

res = driver.find_element_by_id("some_id").is_displayed()
assert res, 'element not displayed!'

How can I create a border around an Android LinearLayout?

This solution will only add the border, the body of the LinearLayout will be transparent.

First, Create this border drawable in the drawable folder, border.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android= "http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke android:width="2dp" android:color="#ec0606"/>
    <corners android:radius="10dp"/>
</shape>

Then, in your LinearLayout View, add the border.xml as the background like this

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@drawable/border">

Return sql rows where field contains ONLY non-alphanumeric characters

SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.

As it happens, you are close. Just need leading+trailing wildcards and move the NOT

 WHERE whatever NOT LIKE '%[a-z0-9]%'

Valid characters in a Java class name

What other rules govern Java class names (for instance, Java class names cannot begin with a number)?

  • Java class names usually begin with a capital letter.
  • Java class names cannot begin with a number.
  • if there are multiple words in the class name like "MyClassName" each word should begin with a capital letter. eg- "MyClassName".This naming convention is based on CamelCase Type.

Deserialize JSON with C#

Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer, DataContractJsonSerializer.

In this sample, you can the following:

var jsonData = JObject.Parse("your JSON data here");

Then you can cast jsonData to JArray, and you can use a for loop to get data at each iteration.

Also, I want to add something:

for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
    var data = jsonData[i - 1];
}

Working with dynamic object and using Newtonsoft serialize is a good choice.

bootstrap multiselect get selected values

$('#multiselect1').on('change', function(){
    var selected = $(this).find("option:selected");    
    var arrSelected = [];

    // selected.each(function(){
    //   arrSelected.push($(this).val());
    // });

    // The problem with the above selected.each statement is that  
    // there is no iteration value.
    // $(this).val() is all selected items, not an iterative item value.
    // With each iteration the selected items will be appended to 
    // arrSelected like so    
    //
    // arrSelected [0]['item0','item1','item2']
    // arrSelected [1]['item0','item1','item2'] 

    // You need to get the iteration value. 
    //
    selected.each((idx, val) => {
        arrSelected.push(val.value);
    });
    // arrSelected [0]['item0'] 
    // arrSelected [1]['item1']
    // arrSelected [2]['item2']
});

jQuery adding 2 numbers from input fields

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnadd').on('click', function () {
            var n1 = parseInt($('#txtn1').val());
            var n2 = parseInt($('#txtn2').val());
            var r = n1 + n2;
            alert("sum of 2 No= " + r);
            return false;
        });
        $('#btnclear').on('click', function () {
            $('#txtn1').val('');
            $('#txtn2').val('');
            $('#txtn1').focus();
            return false;
        });
    });
</script>

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

MySQL Job failed to start

I had the same problem. But i discover that my hd is full.

$ sudo cat /var/log/upstart/mysql.log
/proc/self/fd/9: ERROR: The partition with /var/lib/mysql is too full!

So, I run

$ df -h

And I got the message

/dev/xvda1      7.8G  7.4G     0 100% /

Then I found out which folder was full by running the following command on the terminal

$ cd /var/www
$ for i in *; do echo $i; find $i |wc -l; done

This give me the number of files on each folder on /var/www. I logged into the folder with most files, and deleted some backup files, and i continued deleting useless files and cache files.

then I run $ sudo /etc/init.d/mysql start and it work again

How can I plot data with confidence intervals?

Here is part of my program related to plotting confidence interval.

1. Generate the test data

ads = 1
require(stats); require(graphics)
library(splines)
x_raw <- seq(1,10,0.1)
y <- cos(x_raw)+rnorm(len_data,0,0.1)
y[30] <- 1.4 # outlier point
len_data = length(x_raw)
N <- len_data
summary(fm1 <- lm(y~bs(x_raw, df=5), model = TRUE, x =T, y = T))
ht <-seq(1,10,length.out = len_data)
plot(x = x_raw, y = y,type = 'p')
y_e <- predict(fm1, data.frame(height = ht))
lines(x= ht, y = y_e)

Result

enter image description here

2. Fitting the raw data using B-spline smoother method

sigma_e <- sqrt(sum((y-y_e)^2)/N)
print(sigma_e)
H<-fm1$x
A <-solve(t(H) %*% H)
y_e_minus <- rep(0,N)
y_e_plus <- rep(0,N)
y_e_minus[N]
for (i in 1:N)
{
    tmp <-t(matrix(H[i,])) %*% A %*% matrix(H[i,])
    tmp <- 1.96*sqrt(tmp)
    y_e_minus[i] <- y_e[i] - tmp
    y_e_plus[i] <- y_e[i] + tmp
}
plot(x = x_raw, y = y,type = 'p')
polygon(c(ht,rev(ht)),c(y_e_minus,rev(y_e_plus)),col = rgb(1, 0, 0,0.5), border = NA)
#plot(x = x_raw, y = y,type = 'p')
lines(x= ht, y = y_e_plus, lty = 'dashed', col = 'red')
lines(x= ht, y = y_e)
lines(x= ht, y = y_e_minus, lty = 'dashed', col = 'red')

Result

enter image description here

In Python, how do you convert a `datetime` object to seconds?

To convert a datetime object that represents time in UTC to POSIX timestamp:

from datetime import timezone

seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()

To convert a datetime object that represents time in the local timezone to POSIX timestamp:

import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()

See How do I convert local time to UTC in Python? If the tz database is available on a given platform; a stdlib-only solution may work.

Follow the links if you need solutions for <3.3 Python versions.

php - push array into array - key issue

first convert your array too JSON

while($query->fetch()){
   $col[] = json_encode($row,JSON_UNESCAPED_UNICODE);
}

then vonvert back it to array

foreach($col as &$array){
   $array = json_decode($array,true);
}

good luck

Can I update a component's props in React.js?

A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.

For instance, a Dashboard has a speed field in its state, and passes it to a Gauge child thats displays this speed. Its render method is just return <Gauge speed={this.state.speed} />. When the Dashboard calls this.setState({speed: this.state.speed + 1}), the Gauge is re-rendered with the new value for speed.

Just before this happens, Gauge's componentWillReceiveProps is called, so that the Gauge has a chance to compare the new value to the old one.

cannot resolve symbol javafx.application in IntelliJ Idea IDE

You can use the one that comes with IntelliJ: <intellij>/jre64/lib/ext/jfxrt.jar.

What EXACTLY is meant by "de-referencing a NULL pointer"?

Quoting from wikipedia:

A pointer references a location in memory, and obtaining the value at the location a pointer refers to is known as dereferencing the pointer.

Dereferencing is done by applying the unary * operator on the pointer.

int x = 5;
int * p;      // pointer declaration
p = &x;       // pointer assignment
*p = 7;       // pointer dereferencing, example 1
int y = *p;   // pointer dereferencing, example 2

"Dereferencing a NULL pointer" means performing *p when the p is NULL

How to delete all data from solr and hbase

The curl examples above all failed for me when I ran them from a cygwin terminal. There were errors like this when i ran the script example.

curl http://192.168.2.20:7773/solr/CORE1/update --data '<delete><query>*:*</query></delete>' -H 'Content-type:text/xml; charset=utf-8'
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">0</int><int name="QTime">1</int></lst>
</response>
<!-- 
     It looks like it deleted stuff, but it did not go away
     maybe because the committing call failed like so 
-->
curl http://192.168.1.2:7773/solr/CORE1/update --data-binary '' -H 'Content-type:text/xml; charset=utf-8'
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">400</int><int name="QTime">2</int></lst><lst name="error"><str name="msg">Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]</str><int name="code">400</int></lst>
</response>

I needed to use the delete in a loop on core names to wipe them all out in a project.

This query below worked for me in the Cygwin terminal script.

curl http://192.168.1.2:7773/hpi/CORE1/update?stream.body=<delete><query>*:*</query></delete>&commit=true
<?xml version="1.0" encoding="UTF-8"?>
<response>
<lst name="responseHeader"><int name="status">0</int><int name="QTime">1</int></lst>
</response>

This one line made the data go away and the change persisted.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Based on BaileyP's answer. The main difference is that these methods return -1 if the pattern can't be matched.

Edit: Thanks to Jason Bunting's answer I got an idea. Why not modify the .lastIndex property of the regex? Though this will only work for patterns with the global flag (/g).

Edit: Updated to pass the test-cases.

String.prototype.regexIndexOf = function(re, startPos) {
    startPos = startPos || 0;

    if (!re.global) {
        var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
        re = new RegExp(re.source, flags);
    }

    re.lastIndex = startPos;
    var match = re.exec(this);

    if (match) return match.index;
    else return -1;
}

String.prototype.regexLastIndexOf = function(re, startPos) {
    startPos = startPos === undefined ? this.length : startPos;

    if (!re.global) {
        var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
        re = new RegExp(re.source, flags);
    }

    var lastSuccess = -1;
    for (var pos = 0; pos <= startPos; pos++) {
        re.lastIndex = pos;

        var match = re.exec(this);
        if (!match) break;

        pos = match.index;
        if (pos <= startPos) lastSuccess = pos;
    }

    return lastSuccess;
}

How to build and fill pandas dataframe from for loop?

Make a list of tuples with your data and then create a DataFrame with it:

d = []
for p in game.players.passing():
    d.append((p, p.team, p.passer_rating()))

pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))

A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.

Testing functions:

def with_tuples(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append((x-1, x, x+1))

    return pd.DataFrame(res, columns=("a", "b", "c"))

def with_dict(loop_size=1e5):
    res = []

    for x in range(int(loop_size)):
        res.append({"a":x-1, "b":x, "c":x+1})

    return pd.DataFrame(res)

Results:

%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop

%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.

You can scale the pixmap by keeping its aspect ratio every time it changes:

QPixmap p; // load pixmap
// get label dimensions
int w = label->width();
int h = label->height();

// set a scaled pixmap to a w x h window keeping its aspect ratio 
label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));

There are two places where you should add this code:

  • When the pixmap is updated
  • In the resizeEvent of the widget that contains the label

Simple regular expression for a decimal with a precision of 2

Valid regex tokens vary by implementation. A generic form is:

[0-9]+(\.[0-9][0-9]?)?

More compact:

\d+(\.\d{1,2})?

Both assume that both have at least one digit before and one after the decimal place.

To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):

^\d+(\.\d{1,2})?$

To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:

^(\d+(\.\d{0,2})?|\.?\d{1,2})$

Added

Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.

Added

Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.

Get push notification while App in foreground iOS

You can create your own notification that mimics the banner alert.

One way is to create a custom uiview that looks like the banner and can animate and respond to touches. With this in mind you can create even better banners with even more functionality.

Or you can look for an api that does it for you and add them as podfiles to your project.

Here are a couple that I have used:

https://github.com/terryworona/TWMessageBarManager

https://github.com/toursprung/TSMessages

What does @media screen and (max-width: 1024px) mean in CSS?

If your media query condition is true then your CSS with that condition will work. That means CSS within your media query's condition pixel size will effect, or else if the condition will fail that mean if the device's width is greater than 1024px than your CSS will not work.Because your media query condition false.

max-width is your max CSS limit till that width.

Local package.json exists, but node_modules missing

Just had the same error message, but when I was running a package.json with:

"scripts": {
    "build": "tsc -p ./src",
}

tsc is the command to run the TypeScript compiler.

I never had any issues with this project because I had TypeScript installed as a global module. As this project didn't include TypeScript as a dev dependency (and expected it to be installed as global), I had the error when testing in another machine (without TypeScript) and running npm install didn't fix the problem. So I had to include TypeScript as a dev dependency (npm install typescript --save-dev) to solve the problem.

'str' object has no attribute 'decode'. Python 3 error?

Use codecs module's open() to read file:

import codecs
with codecs.open(file_name, 'r', encoding='utf-8', errors='ignore') as fdata:

counting number of directories in a specific directory

Some useful examples:

count files in current dir

/bin/ls -lA  | egrep -c '^-'

count dirs in current dir

/bin/ls -lA  | egrep -c '^d'

count files and dirs in current dir

/bin/ls -lA  | egrep -c '^-|^d'

count files and dirs in in one subdirectory

/bin/ls -lA  subdir_name/ | egrep -c '^-|^d'

I have noticed a strange thing (at least in my case) :

When I have tried with ls instead /bin/ls the -A parameter do not list implied . and .. NOT WORK as espected. When I use ls that show ./ and ../ So that result wrong count. SOLUTION : /bin/ls instead ls

How to get year and month from a date - PHP

$dateValue = '2012-01-05';
$yeararray = explode("-", $dateValue);

echo "Year : ". $yeararray[0];
echo "Month : ". date( 'F', mktime(0, 0, 0, $yeararray[1]));

Usiong explode() this can be done.

All com.android.support libraries must use the exact same version specification

My solution i just add

//noinspection GradleCompatible

and I build to test my app, everything is ok.

pop/remove items out of a python tuple

There is a simple but practical solution.

As DSM said, tuples are immutable, but we know Lists are mutable. So if you change a tuple to a list, it will be mutable. Then you can delete the items by the condition, then after changing the type to a tuple again. That’s it.

Please look at the codes below:

tuplex = list(tuplex)
for x in tuplex:
  if (condition):
     tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)

For example, the following procedure will delete all even numbers from a given tuple.

tuplex = (1, 2, 3, 4, 5, 6, 7, 8, 9)
tuplex = list(tuplex)
for x in tuplex:
  if (x % 2 == 0):
     tuplex.pop(tuplex.index(x))
tuplex = tuple(tuplex)
print(tuplex)

if you test the type of the last tuplex, you will find it is a tuple.

Finally, if you want to define an index counter as you did (i.e., n), you should initialize it before the loop, not in the loop.

Uploading images using Node.js, Express, and Mongoose

It will become easy to store files after converting in string you just have to convert string in image in your frontend

convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder

"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")

to delete the file

       let resultHandler = function (err) {
            if (err) {
                console.log("unlink failed", err);
            } else {
                console.log("file deleted");
            }
        }

        fs.unlink(req.file.path, resultHandler);

at your routes import multer

 `multer const multer = require('multer');
  const upload = multer({ dest: __dirname + '/uploads/images' });`
  Add upload.single('img') in your request

  router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]), 
        upload.single('img'), usersController.fellowsdetails);

OR

If you want save images in localstorage and want save path in database you can try following approach

you have to install first the fs-extra which will create folder. I am creating separate folders by id's if you want to remove it you can remove it. and to save path of image where it is uploaded add this code in your api or controller you are using to save image and and add it in database with other data

    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;

create separate folder for multer like multerHelper.js

 const multer = require('multer');
 let fs = require('fs-extra');

 let storage = multer.diskStorage({
 destination: function (req, file, cb) {
    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;
    fs.mkdirsSync(path);
    cb(null, path);
 },
 filename: function (req, file, cb) {
    // console.log(file);

  let extArray = file.mimetype.split("/");
  let extension = extArray[extArray.length - 1];
  cb(null, file.fieldname + '-' + Date.now() + "." + extension);
 }
})

let upload = multer({ storage: storage });

let createUserImage = upload.array('images', 100);

let multerHelper = {
     createUserImage,
}

   module.exports = multerHelper;

In your routes import multerhelper file

   const multerHelper = require("../helpers/multer_helper");

   router.post(multerHelper. createUserImage , function(req, res, next) {
      //Here accessing the body datas.
    })

Conda command is not recognized on Windows 10

When you install anaconda on windows now, it doesn't automatically add Python or Conda.

If you don’t know where your conda and/or python is, you type the following commands into your anaconda prompt

enter image description here

Next, you can add Python and Conda to your path by using the setx command in your command prompt. enter image description here

Next close that command prompt and open a new one. Congrats you can now use conda and python

Source: https://medium.com/@GalarnykMichael/install-python-on-windows-anaconda-c63c7c3d1444

How to run a PowerShell script

If you are on PowerShell 2.0, use PowerShell.exe's -File parameter to invoke a script from another environment, like cmd.exe. For example:

Powershell.exe -File C:\my_path\yada_yada\run_import_script.ps1

How to get Maven project version to the bash command line

There is also one option without need Maven:

grep -oPm1 "(?<=<version>)[^<]+" "pom.xml"

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric

geom_segment(data=tmpp, 
   aes(x=start_pos, 
   y=lib.complexity, 
   xend=end_pos, 
   yend=lib.complexity)
)
# to 
geom_segment(data=tmpp, 
   aes(x=as.numeric(start_pos), 
   y=as.numeric(lib.complexity), 
   xend=as.numeric(end_pos), 
   yend=as.numeric(lib.complexity))
)

get the titles of all open windows

Hera's the function UpdateWindowsList_WindowMenu() that you must call after any operations are performed on Tabs.Here windowToolStripMenuItem is the menu item added to Window Menu to menu strip.

public void UpdateWindowsList_WindowMenu()  
{  
    //get all tab pages from tabControl1  
    TabControl.TabPageCollection tabcoll = tabControl1.TabPages;  

    //get  windowToolStripMenuItem drop down menu items count  
    int n = windowToolStripMenuItem.DropDownItems.Count;  

    //remove all menu items from of windowToolStripMenuItem  
    for (int i = n - 1; i >=2; i--)  
    {  
        windowToolStripMenuItem.DropDownItems.RemoveAt(i);  
    }  

    //read each tabpage from tabcoll and add each tabpage text to windowToolStripMenuItem  
    foreach (TabPage tabpage in tabcoll)  
    {  
        //create Toolstripmenuitem  
        ToolStripMenuItem menuitem = new ToolStripMenuItem();  
        String s = tabpage.Text;  
        menuitem.Text = s;  

        if (tabControl1.SelectedTab == tabpage)  
        {  
            menuitem.Checked = true;  
        }  
        else  
        {  
            menuitem.Checked = false;  
        }  

        //add menuitem to windowToolStripMenuItem  
        windowToolStripMenuItem.DropDownItems.Add(menuitem);  

        //add click events to each added menuitem  
        menuitem.Click += new System.EventHandler(WindowListEvent_Click);  
    }  
}  

private void WindowListEvent_Click(object sender, EventArgs e)  
{  
    //casting ToolStripMenuItem to ToolStripItem  
    ToolStripItem toolstripitem = (ToolStripItem)sender;  

    //create collection of tabs of tabContro1  
    //check every tab text is equal to clicked menuitem then select the tab  
    TabControl.TabPageCollection tabcoll = tabControl1.TabPages;  
    foreach (TabPage tb in tabcoll)  
    {  
        if (toolstripitem.Text == tb.Text)  
        {  
            tabControl1.SelectedTab = tb;  
            //call UpdateWindowsList_WindowMenu() to perform changes on menuitems  
            UpdateWindowsList_WindowMenu();  
        }  
    }  
}  

How to pass variable number of arguments to a PHP function

This is now possible with PHP 5.6.x, using the ... operator (also known as splat operator in some languages):

Example:

function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
    foreach ( $intervals as $interval ) {
        $dt->add( $interval );
    }
    return $dt;
}

addDateIntervaslToDateTime( new DateTime, new DateInterval( 'P1D' ), 
        new DateInterval( 'P4D' ), new DateInterval( 'P10D' ) );

Rounded table corners CSS only

The best solution I've found for rounded corners and other CSS3 behavior for IE<9 can be found here: http://css3pie.com/

Download the plug-in, copy to a directory in your solution structure. Then in your stylesheet make sure to have the behavior tag so that it pulls in the plug-in.

Simple example from my project which gives me rounded corners, color gradient, and box shadow for my table:

.table-canvas 
{
    -webkit-border-radius: 8px;
    -moz-border-radius: 8px;
    overflow:hidden;
    border-radius: 10px;
    -pie-background: linear-gradient(#ece9d8, #E5ECD8);   
    box-shadow: #666 0px 2px 3px;
    behavior: url(Include/PIE.htc);
    overflow: hidden;
}

Don't worry if your Visual Studio CSS intellisense gives you the green underline for unknown properites, it still works when you run it. Some of the elements are not very clearly documented, but the examples are pretty good, especially on the front page.

C# List of objects, how do I get the sum of a property

Here is example code you could run to make such test:

var f = 10000000;
var p = new int[f];

for(int i = 0; i < f; ++i)
{
    p[i] = i % 2;
}

var time = DateTime.Now;
p.Sum();
Console.WriteLine(DateTime.Now - time);

int x = 0;
time = DateTime.Now;
foreach(var item in p){
   x += item;
}
Console.WriteLine(DateTime.Now - time);

x = 0;
time = DateTime.Now;
for(int i = 0, j = f; i < j; ++i){
   x += p[i];
}
Console.WriteLine(DateTime.Now - time);

The same example for complex object is:

void Main()
{
    var f = 10000000;
    var p = new Test[f];

    for(int i = 0; i < f; ++i)
    {
        p[i] = new Test();
        p[i].Property = i % 2;
    }

    var time = DateTime.Now;
    p.Sum(k => k.Property);
    Console.WriteLine(DateTime.Now - time);

    int x = 0;
    time = DateTime.Now;
    foreach(var item in p){
        x += item.Property;
    }
    Console.WriteLine(DateTime.Now - time);

    x = 0;
    time = DateTime.Now;
    for(int i = 0, j = f; i < j; ++i){
        x += p[i].Property;
    }
    Console.WriteLine(DateTime.Now - time);
}

class Test
{
    public int Property { get; set; }
}

My results with compiler optimizations off are:

00:00:00.0570370 : Sum()
00:00:00.0250180 : Foreach()
00:00:00.0430272 : For(...)

and for second test are:

00:00:00.1450955 : Sum()
00:00:00.0650430 : Foreach()
00:00:00.0690510 : For()

it looks like LINQ is generally slower than foreach(...) but what is weird for me is that foreach(...) appears to be faster than for loop.

How can I open an Excel file in Python?

This may help:

This creates a node that takes a 2D List (list of list items) and pushes them into the excel spreadsheet. make sure the IN[]s are present or will throw and exception.

this is a re-write of the Revit excel dynamo node for excel 2013 as the default prepackaged node kept breaking. I also have a similar read node. The excel syntax in Python is touchy.

thnx @CodingNinja - updated : )

###Export Excel - intended to replace malfunctioning excel node

import clr

clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
##AddReferenceGUID("{00020813-0000-0000-C000-000000000046}") ''Excel                            C:\Program Files\Microsoft Office\Office15\EXCEL.EXE 
##Need to Verify interop for version 2015 is 15 and node attachemnt for it.
from Microsoft.Office.Interop import  * ##Excel
################################Initialize FP and Sheet ID
##Same functionality as the excel node
strFileName = IN[0]             ##Filename
sheetName = IN[1]               ##Sheet
RowOffset= IN[2]                ##RowOffset
ColOffset= IN[3]                ##COL OFfset
Data=IN[4]                      ##Data
Overwrite=IN[5]                 ##Check for auto-overwtite
XLVisible = False   #IN[6]      ##XL Visible for operation or not?

RowOffset=0
if IN[2]>0:
    RowOffset=IN[2]             ##RowOffset

ColOffset=0
if IN[3]>0:
    ColOffset=IN[3]             ##COL OFfset

if IN[6]<>False:
    XLVisible = True #IN[6]     ##XL Visible for operation or not?

################################Initialize FP and Sheet ID
xlCellTypeLastCell = 11                 #####define special sells value constant
################################
xls = Excel.ApplicationClass()          ####Connect with application
xls.Visible = XLVisible                 ##VISIBLE YES/NO
xls.DisplayAlerts = False               ### ALerts

import os.path

if os.path.isfile(strFileName):
    wb = xls.Workbooks.Open(strFileName, False)     ####Open the file 
else:
    wb = xls.Workbooks.add#         ####Open the file 
    wb.SaveAs(strFileName)
wb.application.visible = XLVisible      ####Show Excel
try:
    ws = wb.Worksheets(sheetName)       ####Get the sheet in the WB base

except:
    ws = wb.sheets.add()                ####If it doesn't exist- add it. use () for object method
    ws.Name = sheetName



#################################
#lastRow for iterating rows
lastRow=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Row
#lastCol for iterating columns
lastCol=ws.UsedRange.SpecialCells(xlCellTypeLastCell).Column
#######################################################################
out=[]                                  ###MESSAGE GATHERING

c=0
r=0
val=""
if Overwrite == False :                 ####Look ahead for non-empty cells to throw error
    for r, row in enumerate(Data):   ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
        for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
            if col.Value2 >"" :
                OUT= "ERROR- Cannot overwrite"
                raise ValueError("ERROR- Cannot overwrite")
##out.append(Data[0]) ##append mesage for error
############################################################################

for r, row in enumerate(Data):   ####BASE 0## EACH ROW OF DATA ENUMERATED in the 2D array #range( RowOffset, lastRow + RowOffset):
    for c, col in enumerate (row): ####BASE 0## Each colmn in each row is a cell with data ### in range(ColOffset, lastCol + ColOffset):
        ws.Cells[r+1+RowOffset,c+1+ColOffset].Value2 = col.__str__()

##run macro disbled for debugging excel macro
##xls.Application.Run("Align_data_and_Highlight_Issues")

How I can check whether a page is loaded completely or not in web driver?

Below is some code from my BasePageObject class for waits:

public void waitForPageLoadAndTitleContains(int timeout, String pageTitle) {
    WebDriverWait wait = new WebDriverWait(driver, timeout, 1000);
    wait.until(ExpectedConditions.titleContains(pageTitle));
}

public void waitForElementPresence(By locator, int seconds) {
    WebDriverWait wait = new WebDriverWait(driver, seconds);
    wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}

public void jsWaitForPageToLoad(int timeOutInSeconds) {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String jsCommand = "return document.readyState";

    // Validate readyState before doing any waits
    if (js.executeScript(jsCommand).toString().equals("complete")) {
        return;
    }

    for (int i = 0; i < timeOutInSeconds; i++) {
        TimeManager.waitInSeconds(3);
        if (js.executeScript(jsCommand).toString().equals("complete")) {
            break;
        }
    }
}

   /**
     * Looks for a visible OR invisible element via the provided locator for up
     * to maxWaitTime. Returns as soon as the element is found.
     *
     * @param byLocator
     * @param maxWaitTime - In seconds
     * @return
     *
     */
    public WebElement findElementThatIsPresent(final By byLocator, int maxWaitTime) {
        if (driver == null) {
            nullDriverNullPointerExeption();
        }
        FluentWait<WebDriver> wait = new FluentWait<>(driver).withTimeout(maxWaitTime, java.util.concurrent.TimeUnit.SECONDS)
                .pollingEvery(200, java.util.concurrent.TimeUnit.MILLISECONDS);

        try {
            return wait.until((WebDriver webDriver) -> {
                List<WebElement> elems = driver.findElements(byLocator);
                if (elems.size() > 0) {
                    return elems.get(0);
                } else {
                    return null;
                }
            });
        } catch (Exception e) {
            return null;
        }
    }

Supporting methods:

     /**
     * Gets locator.
     *
     * @param fieldName
     * @return
     */
    public By getBy(String fieldName) {
        try {
            return new Annotations(this.getClass().getDeclaredField(fieldName)).buildBy();
        } catch (NoSuchFieldException e) {
            return null;
        }
    }

Loop X number of times

Use:

1..10 | % { write "loop $_" }

Output:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

Error: JAVA_HOME is not defined correctly executing maven

JAVA_HOME should be /usr/lib/jvm/java-7-oracle/jre/.

Chrome extension id - how to find it

You get an extension ID when you upload your extension to Google Web Store. Ie. Adblock has URL https://chrome.google.com/webstore/detail/cfhdojbkjhnklbpkdaibdccddilifddb and the last part of this URL is its extension ID cfhdojbkjhnklbpkdaibdccddilifddb.


If you wish to read installed extension IDs from your extension, check out the managment module. chrome.management.getAll allows to fetch information about all installed extensions.

Modifying location.hash without page scrolling

This solution creates a div at the actual scrollTop and removes it after changing hash:

$('#menu a').on('click',function(){
    //your anchor event here
    var href = $(this).attr('href');
    window.location.hash = href;
    if(window.location.hash == href)return false;           
    var $jumpTo = $('body').find(href);
    $('body').append(
        $('<div>')
            .attr('id',$jumpTo.attr('id'))
            .addClass('fakeDivForHash')
            .data('realElementForHash',$jumpTo.removeAttr('id'))
            .css({'position':'absolute','top':$(window).scrollTop()})
    );
    window.location.hash = href;    
});
$(window).on('hashchange', function(){
    var $fakeDiv = $('.fakeDivForHash');
    if(!$fakeDiv.length)return true;
    $fakeDiv.data('realElementForHash').attr('id',$fakeDiv.attr('id'));
    $fakeDiv.remove();
});

optional, triggering anchor event at page load:

$('#menu a[href='+window.location.hash+']').click();

How can I change the current URL?

Simple assigning to window.location or window.location.href should be fine:

window.location = newUrl;

However, your new URL will cause the browser to load the new page, but it sounds like you'd like to modify the URL without leaving the current page. You have two options for this:

  1. Use the URL hash. For example, you can go from example.com to example.com#foo without loading a new page. You can simply set window.location.hash to make this easy. Then, you should listen to the HTML5 hashchange event, which will be fired when the user presses the back button. This is not supported in older versions of IE, but check out jQuery BBQ, which makes this work in all browsers.

  2. You could use HTML5 History to modify the path without reloading the page. This will allow you to change from example.com/foo to example.com/bar. Using this is easy:

    window.history.pushState("example.com/foo");

    When the user presses "back", you'll receive the window's popstate event, which you can easily listen to (jQuery):

    $(window).bind("popstate", function(e) { alert("location changed"); });

    Unfortunately, this is only supported in very modern browsers, like Chrome, Safari, and the Firefox 4 beta.

How to delete a specific line in a file?

The best and fastest option, rather than storing everything in a list and re-opening the file to write it, is in my opinion to re-write the file elsewhere.

with open("yourfile.txt", "r") as file_input:
    with open("newfile.txt", "w") as output: 
        for line in file_input:
            if line.strip("\n") != "nickname_to_delete":
                output.write(line)

That's it! In one loop and one only you can do the same thing. It will be much faster.

Mysql command not found in OS X 10.7

in terminal do:

vi ~/.bash_profile 

And add this line:

export PATH=${PATH}:/usr/local/mysql/bin

and the type this in terminal:

mysql -u [username] -p [password]

Better way to remove specific characters from a Perl string

Well if you're using the randomly-generated string so that it has a low probability of being matched by some intentional string that you might normally find in the data, then you probably want one string per file.

You take that string, call it $place_older say. And then when you want to eliminate the text, you call quotemeta, and you use that value to substitute:

my $subs = quotemeta $place_holder;
s/$subs//g;

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How does OAuth 2 protect against things like replay attacks using the Security Token?

Figure 1, lifted from RFC6750:

     +--------+                               +---------------+
     |        |--(A)- Authorization Request ->|   Resource    |
     |        |                               |     Owner     |
     |        |<-(B)-- Authorization Grant ---|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(C)-- Authorization Grant -->| Authorization |
     | Client |                               |     Server    |
     |        |<-(D)----- Access Token -------|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(E)----- Access Token ------>|    Resource   |
     |        |                               |     Server    |
     |        |<-(F)--- Protected Resource ---|               |
     +--------+                               +---------------+

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

What is "Linting"?

Interpreted languages like Python and JavaScript benefit greatly from linting, as these languages don’t have a compiling phase to display errors before execution.

Linters are also useful for code formatting and/or adhering to language specific best practices.

Lately I have been using ESLint for JS/React and will occasionally use it with an airbnb-config file.

number of values in a list greater than a certain number

You could do something like this:

>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3

It might initially seem strange to add True to True this way, but I don't think it's unpythonic; after all, bool is a subclass of int in all versions since 2.3:

>>> issubclass(bool, int)
True

Java - Writing strings to a CSV file

I think this is a simple code in java which will show the string value in CSV after compile this code.

public class CsvWriter {

    public static void main(String args[]) {
        // File input path
        System.out.println("Starting....");
        File file = new File("/home/Desktop/test/output.csv");
        try {
            FileWriter output = new FileWriter(file);
            CSVWriter write = new CSVWriter(output);

            // Header column value
            String[] header = { "ID", "Name", "Address", "Phone Number" };
            write.writeNext(header);
            // Value
            String[] data1 = { "1", "First Name", "Address1", "12345" };
            write.writeNext(data1);
            String[] data2 = { "2", "Second Name", "Address2", "123456" };
            write.writeNext(data2);
            String[] data3 = { "3", "Third Name", "Address3", "1234567" };
            write.writeNext(data3);
            write.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }

        System.out.println("End.");

    }
}

inline conditionals in angular.js

EDIT: 2Toad's answer below is what you're looking for! Upvote that thing

If you're using Angular <= 1.1.4 then this answer will do:

One more answer for this. I'm posting a separate answer, because it's more of an "exact" attempt at a solution than a list of possible solutions:

Here's a filter that will do an "immediate if" (aka iif):

app.filter('iif', function () {
   return function(input, trueValue, falseValue) {
        return input ? trueValue : falseValue;
   };
});

and can be used like this:

{{foo == "bar" | iif : "it's true" : "no, it's not"}}

Why has it failed to load main-class manifest attribute from a JAR file?

If you using eclipse, try below: 1. Right click on the project -> select Export 2. Select Runnable Jar file in the select an export destination 3. Enter jar's name and Select "Package required ... " (second radio button) -> Finish

Hope this helps...!

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

View and check the reference paths in your csproj.

I had removed references to System.Web.Mvc (and others) and readded them to a custom path. C:\Project\OurWebReferences

However, after doing this, the reference path in the still csproj did not change. WAS

<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\..\OurWebProject\bin\Debug\System.Web.Mvc.dll</HintPath>
</Reference>

Changed to manually

<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
        <HintPath>..\..\..\..\OurWebReferences\System.Web.Mvc.dll</HintPath>
</Reference>

Paths are an example only.

HTML: How to create a DIV with only vertical scroll-bars for long paragraphs?

This is my mix:

overflow-y: scroll;
height: 13em; // Initial height.
resize: vertical; // Allow user to change the vertical size.
max-height: 31em; // If you want to constrain the max size.

How can I check if a directory exists in a Bash shell script?

You can use test -d (see man test).

-d file True if file exists and is a directory.

For example:

test -d "/etc" && echo Exists || echo Does not exist

Note: The test command is same as conditional expression [ (see: man [), so it's portable across shell scripts.

[ - This is a synonym for the test builtin, but the last argument must, be a literal ], to match the opening [.

For possible options or further help, check:

  • help [
  • help test
  • man test or man [

How to use SVG markers in Google Maps API v3

I know this post is a bit old, but I have seen so much bad information on this at SO that I could scream. So I just gotta throw my two cents in with a whole different approach that I know works, as I use it reliably on many maps. Besides that, I believe the OP wanted the ability to rotate the arrow marker around the map point as well, which is different than rotating the icon around it's own x,y axis which will change where the arrow marker points to on the map.

First, remember we are playing with Google maps and SVG, so we must accomodate the way in which Google deploys it's implementation of SVG for markers (or actually symbols). Google sets its anchor for the SVG marker image at 0,0 which IS NOT the upper left corner of the SVG viewBox. In order to get around this, you must draw your SVG image a bit differently to give Google what it wants... yes the answer is in the way you actually create the SVG path in your SVG editor (Illustrator, Inkscape, etc...).

The first step, is to get rid of the viewBox. This can be done by setting the viewBox in your XML to 0... that's right, just one zero instead of the usual four arguments for the viewBox. This turns the view box off (and yes, this is semantically correct). You will probably notice the size of your image jump immeadiately when you do this, and that is because the svg no longer has a base (the viewBox) to scale the image. So we create that reference directly, by setting the width and height to the actual number of pixels you wish your image to be in the XML editor of your SVG editor.

By setting the width and height of the svg image in the XML editor you create a baseline for scaling of the image, and this size becomes a value of 1 for the marker scale properties by default. You can see the advantage this has for dynamic scaling of the marker.

Now that you have your image sized, move the image until the part of the image you wish to have as the anchor is over the 0,0 coordinates of the svg editor. Once you have done this copy the value of the d attribute of the svg path. You will notice about half of the numbers are negative, which is the result of aligning your anchor point for the 0,0 of the image instead of the viewBox.

Using this technique will then let you rotate the marker correctly, around the lat and lng point on the map. This is the only reliable way to bind the point on the svg marker you want to the lat and long of the marker location.

I tried to make a JSFiddle for this, but there is some bug in there implementation, one of the reasons I am not so fond of reinterpreted code. So instead, I have included a fully self-contained example below that you can try out, adapt, and use as a reference. This is the same code I tried at JSFiddle that failed, yet it sails through Firebug without a whimper.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <meta name="viewport"  content="width=device-width, initial-scale=1" />
    <meta name="author"    content="Drew G. Stimson, Sr. ( Epiphany )" />
    <title>Create Draggable and Rotatable SVG Marker</title>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script>
    <style type="text/css">
      #document_body {
        margin:0;
        border: 0;
        padding: 10px;
        font-family: Arial,sans-serif;
        font-size: 14px;
        font-weight: bold;
        color: #f0f9f9;
        text-align: center;
        text-shadow: 1px 1px 1px #000;
        background:#1f1f1f;
      }
      #map_canvas, #rotation_control {
        margin: 1px;
        border:1px solid #000;
        background:#444;
        -webkit-border-radius: 4px;
           -moz-border-radius: 4px;
                border-radius: 4px;
      }
      #map_canvas { 
        width: 100%;
        height: 360px;
      }
      #rotation_control { 
        width: auto;
        padding:5px;
      }
      #rotation_value { 
        margin: 1px;
        border:1px solid #999;
        width: 60px;
        padding:2px;
        font-weight: bold;
        color: #00cc00;
        text-align: center;
        background:#111;
        border-radius: 4px;
      }
</style>

<script type="text/javascript">
  var map, arrow_marker, arrow_options;
  var map_center = {lat:41.0, lng:-103.0};
  var arrow_icon = {
    path: 'M -1.1500216e-4,0 C 0.281648,0 0.547084,-0.13447 0.718801,-0.36481 l 17.093151,-22.89064 c 0.125766,-0.16746 0.188044,-0.36854 0.188044,-0.56899 0,-0.19797 -0.06107,-0.39532 -0.182601,-0.56215 -0.245484,-0.33555 -0.678404,-0.46068 -1.057513,-0.30629 l -11.318243,4.60303 0,-26.97635 C 5.441639,-47.58228 5.035926,-48 4.534681,-48 l -9.06959,0 c -0.501246,0 -0.906959,0.41772 -0.906959,0.9338 l 0,26.97635 -11.317637,-4.60303 c -0.379109,-0.15439 -0.812031,-0.0286 -1.057515,0.30629 -0.245483,0.33492 -0.244275,0.79809 0.0055,1.13114 L -0.718973,-0.36481 C -0.547255,-0.13509 -0.281818,0 -5.7002158e-5,0 Z',
    strokeColor: 'black',
    strokeOpacity: 1,
    strokeWeight: 1,
    fillColor: '#fefe99',
    fillOpacity: 1,
    rotation: 0,
    scale: 1.0
  };

function init(){
  map = new google.maps.Map(document.getElementById('map_canvas'), {
    center: map_center,
    zoom: 4,
    mapTypeId: google.maps.MapTypeId.HYBRID
  });
  arrow_options = {
    position: map_center,
    icon: arrow_icon,
    clickable: false,
    draggable: true,
    crossOnDrag: true,
    visible: true,
    animation: 0,
    title: 'I am a Draggable-Rotatable Marker!' 
  };
  arrow_marker = new google.maps.Marker(arrow_options);
  arrow_marker.setMap(map);
}
function setRotation(){
  var heading = parseInt(document.getElementById('rotation_value').value);
  if (isNaN(heading)) heading = 0;
  if (heading < 0) heading = 359;
  if (heading > 359) heading = 0;
  arrow_icon.rotation = heading;
  arrow_marker.setOptions({icon:arrow_icon});
  document.getElementById('rotation_value').value = heading;
}
</script>
</head>
<body id="document_body" onload="init();">
  <div id="rotation_control">
    <small>Enter heading to rotate marker&nbsp;&nbsp;&nbsp;&nbsp;</small>
    Heading&deg;<input id="rotation_value" type="number" size="3" value="0" onchange="setRotation();" />
    <small>&nbsp;&nbsp;&nbsp;&nbsp;Drag marker to place marker</small>
    </div>
    <div id="map_canvas"></div>
</body>
</html>

This is exactly what Google does for it's own few symbols available in the SYMBOL class of the Maps API, so if that doesn't convince you... Anyway, I hope this will help you to correctly make and set up a SVG marker for your Google maps endevours.

Print DIV content by JQuery

There is a way to use this with a hidden div but you have to work abit more with the printElement() function and css.

Css:

#SelectorToPrint{
     display: none;
}

Script:

  $("#SelectorToPrint").printElement({ printBodyOptions:{styleToAdd:'padding:10px;margin:10px;display:block', classNameToAdd:'WhatYouWant'}})

This will override the display: none in the new window you open and the content will be displayed on the print-preview page and the div on you site remains hidden.

Rotation of 3D vector?

A one-liner, with numpy/scipy functions.

We use the following:

let a be the unit vector along axis, i.e. a = axis/norm(axis)
and A = I × a be the skew-symmetric matrix associated to a, i.e. the cross product of the identity matrix with a

then M = exp(? A) is the rotation matrix.

from numpy import cross, eye, dot
from scipy.linalg import expm, norm

def M(axis, theta):
    return expm(cross(eye(3), axis/norm(axis)*theta))

v, axis, theta = [3,5,0], [4,4,1], 1.2
M0 = M(axis, theta)

print(dot(M0,v))
# [ 2.74911638  4.77180932  1.91629719]

expm (code here) computes the taylor series of the exponential:
\sum_{k=0}^{20} \frac{1}{k!} (? A)^k , so it's time expensive, but readable and secure. It can be a good way if you have few rotations to do but a lot of vectors.

java.lang.NoClassDefFoundError: org/json/JSONObject

No.. It is not proper way. Refer the steps,

For Classpath reference: Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.

For Deployment Assembly: Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.

This is the proper way! Don't forget to remove environment variable. It is not required now.

Try this. Surely it will work. Try to use Maven, it will simplify you task.

Simple PowerShell LastWriteTime compare

Use

ls | % {(get-date) - $_.LastWriteTime }

It can work to retrieve the diff. You can replace ls with a single file.

What is sharding and why is it important?

Is sharding mostly important in very large scale applications or does it apply to smaller scale ones?

Sharding is a concern if and only if your needs scale past what can be served by a single database server. It's a swell tool if you have shardable data and you have incredibly high scalability and performance requirements. I would guess that in my entire 12 years I've been a software professional, I've encountered one situation that could have benefited from sharding. It's an advanced technique with very limited applicability.

Besides, the future is probably going to be something fun and exciting like a massive object "cloud" that erases all potential performance limitations, right? :)

How do I measure request and response times at once using cURL?

If you want to analyze or summarize the latency you can try apache bench:

ab -n [number of samples] [url]

For example:

ab -n 100 http://www.google.com/

It will show:

This is ApacheBench, Version 2.3 <$Revision: 1757674 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking www.google.com (be patient).....done


Server Software:        gws
Server Hostname:        www.google.com
Server Port:            80

Document Path:          /
Document Length:        12419 bytes

Concurrency Level:      1
Time taken for tests:   10.700 seconds
Complete requests:      100
Failed requests:        97
   (Connect: 0, Receive: 0, Length: 97, Exceptions: 0)
Total transferred:      1331107 bytes
HTML transferred:       1268293 bytes
Requests per second:    9.35 [#/sec] (mean)
Time per request:       107.004 [ms] (mean)
Time per request:       107.004 [ms] (mean, across all concurrent requests)
Transfer rate:          121.48 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:       20   22   0.8     22      26
Processing:    59   85 108.7     68     911
Waiting:       59   85 108.7     67     910
Total:         80  107 108.8     90     932

Percentage of the requests served within a certain time (ms)
  50%     90
  66%     91
  75%     93
  80%     95
  90%    105
  95%    111
  98%    773
  99%    932
 100%    932 (longest request)

How can I start PostgreSQL server on Mac OS X?

There is some edge case that maybe will be helpful for someone:

There is an option that you will have postgres.pid filled with some PID. If you restart your machine, and before PostgreSQL will be back again, some other process will take that PID.

If that will happen, both the pg_ctl status and brew service are asked about the PostgreSQL status, will tell you that it is up.

Just do ps aux | grep <yourPID> and check if it is really PostgreSQL.

Excluding Maven dependencies

You can utilize the dependency management mechanism.

If you create entries in the <dependencyManagement> section of your pom for spring-security-web and spring-web with the desired 3.1.0 version set the managed version of the artifact will override those specified in the transitive dependency tree.

I'm not sure if that really saves you any code, but it is a cleaner solution IMO.

How to make the overflow CSS property work with hidden as value

Ok if anyone else is having this problem this may be your answer:

If you are trying to hide absolute positioned elements make sure the container of those absolute positioned elements is relatively positioned.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

If you are looking for Simple/quicker way, you can follow this solution.

  1. Right click on your project.
  2. Goto > Build Path > Configure Build Path > Java Build Path
  3. Goto 'Source' tab, there, you can see like <<your_project_name>>/src/main/java(missing).
  4. Click on it and remove.
  5. Click on Apply and Close.
  6. Now, right click on project and >New > Source folder > add source folder "src/main/java".

happy learning and do not forget to upvote :)

jQuery send string as POST parameters

I see that they did not understand your question.

Answer is: add "traditional" parameter to your ajax call like this:

$.ajax({
  traditional: true,
  type: "POST",
  url: url,
  data: custom,
  success: ok,
  dataType: "json"
});

And it will work with parameters PASSED AS A STRING.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I just replaced version 11.2.0 with 11.0.0 and then it seemed to work fine, so that had to mean that 11.2.0 wasn't included with the latest Android SDK.

So, after struggling with all the available scattered documentation, I reached this document by pure chance (I guess it is not indexed high enough by Google): https://developers.google.com/android/guides/releases

I quote from there:

Highlights from the Google Play services 11.2 release. Google Play services dependencies are now available via maven.google.com

Now, even when that shouldn't necessarily mean that they are not available with the downloaded SDK anymore, it seems that this is actually the case.

Anyway, adding google() to my build.gradle didn't work (not found, undefined, or whatever...), so I used a different approach that I found in this document referenced from the previous one:

https://developer.android.com/studio/build/dependencies.html#google-maven

I modified my build.gradle file adding that line to allprojects/repositories, as in:

allprojects {
...
    repositories {
...
        maven { url "https://maven.google.com/"}
    }
}

And then also in the android section in the same build.gradle file:

project(":android") {
...
    dependencies {
...
        compile 'com.google.android.gms:play-services-ads:11.2.0'
    }
}

Those two lines were enough to make Gradle sync without problems. I didn't need to add any plugins apart from the ones that are already added in my libGDX project by default.

After that, I got a few different errors, but none about Gradle or dependencies. In a brief, JFTR:

First, I had a minSdkVersion of 8. Solved by raising it to 14. I think I could live without supporting all those devices below 14.

Second, I had problems with the dex upper limit of references. I've never faced this problem before, but maybe you've already noticed the solution I used: instead of compiling the whole 'com.google.android.gms:play-services' I used only 'com.google.android.gms:play-services-ads' that's the API I'm actually interested right now. For those other particular cases where a solution like this may not be useful, this document could provide some better insight: https://developer.android.com/studio/build/multidex.html

Third, even after that I got this "jumbo" thing problem described and answered here: https://stackoverflow.com/a/26248495/1160360

And that's it. As of now, everything builds and my game does finally shows those Admob banners.

I've spent hours with this, thought, which makes me wonder if all these building automation systems we are using lately are worth the extra load they add.

I mean, the first time I had to add Admob to an app five years ago or so, I just had to download a .jar file and put it on a directory on my project. It was pretty obvious and the whole process, from googling "how to setup Admob in my android project" to have my app showing an Admob banner took me just a few minutes. I'm gonna leave it here, since this is not the place for such kind of debate.

Nonetheless, I hope my own experience is useful for someone else further.

How to empty the content of a div

If your div looks like this:

<div id="MyDiv">content in here</div>

Then this Javascript:

document.getElementById("MyDiv").innerHTML = "";

will make it look like this:

<div id="MyDiv"></div>

jQuery issue in Internet Explorer 8

I think that you have same problem as I do:

Message: Permission denied
Line: 13
Char: 27021
Code: 0
URI: http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.3.2.min.js

Because of cross domain reference. Try to host jquery.js on same domain.

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Android Studio - How to Change Android SDK Path

You can also create the environment variable (in Windows) ANDROID_HOME to the location of the Android SDK and Android Studio will use that.

Convert the first element of an array to a string in PHP

Since the issue of whitespace only comes up when exporting arrays, you can use the original var_export() for all other variable types. This function does the job, and, from the outside, works the same as var_export().

<?php

function var_export_min($var, $return = false) {
    if (is_array($var)) {
        $toImplode = array();
        foreach ($var as $key => $value) {
            $toImplode[] = var_export($key, true).'=>'.var_export_min($value, true);
        }
        $code = 'array('.implode(',', $toImplode).')';
        if ($return) return $code;
        else echo $code;
    } else {
        return var_export($var, $return);
    }
}

?>

http://www.php.net/manual/en/function.var-export.php#54440

Spring Boot: Cannot access REST Controller on localhost (404)

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

System.Net.WebException HTTP status code

By using the null-conditional operator (?.) you can get the HTTP status code with a single line of code:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

The variable status will contain the HttpStatusCode. When the there is a more general failure like a network error where no HTTP status code is ever sent then status will be null. In that case you can inspect ex.Status to get the WebExceptionStatus.

If you just want a descriptive string to log in case of a failure you can use the null-coalescing operator (??) to get the relevant error:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

If the exception is thrown as a result of a 404 HTTP status code the string will contain "NotFound". On the other hand, if the server is offline the string will contain "ConnectFailure" and so on.

(And for anybody that wants to know how to get the HTTP substatus code. That is not possible. It is a Microsoft IIS concept that is only logged on the server and never sent to the client.)

The simplest way to resize an UIImage?

Yet another way of resizing an UIImage:

// Resize to height = 100 points.
let originalImage = UIImage(named: "MyOriginalImage")!
let resizingFactor = 100 / originalImage.size.height
let newImage = UIImage(cgImage: originalImage.cgImage!, scale: originalImage.scale / resizingFactor, orientation: .up)

How to delete an element from a Slice in Golang

Remove one element from the Slice (this is called 're-slicing'):

package main

import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println(all) //[0 1 2 3 4 5 6 7 8 9]
    all = RemoveIndex(all, 5)
    fmt.Println(all) //[0 1 2 3 4 6 7 8 9]
}

Is the sizeof(some pointer) always equal to four?

In addition to what people have said about 64-bit (or whatever) systems, there are other kinds of pointer than pointer-to-object.

A pointer-to-member might be almost any size, depending how they're implemented by your compiler: they aren't necessarily even all the same size. Try a pointer-to-member of a POD class, and then a pointer-to-member inherited from one of the base classes of a class with multiple bases. What fun.

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

There are two main differences.

Accessing the association sides

The first one is related to how you will access the relationship. For a unidirectional association, you can navigate the association from one end only.

So, for a unidirectional @ManyToOne association, it means you can only access the relationship from the child side where the foreign key resides.

If you have a unidirectional @OneToMany association, it means you can only access the relationship from the parent side which manages the foreign key.

For the bidirectional @OneToMany association, you can navigate the association in both ways, either from the parent or from the child side.

You also need to use add/remove utility methods for bidirectional associations to make sure that both sides are properly synchronized.

Performance

The second aspect is related to performance.

  1. For @OneToMany, unidirectional associations don't perform as well as bidirectional ones.
  2. For @OneToOne, a bidirectional association will cause the parent to be fetched eagerly if Hibernate cannot tell whether the Proxy should be assigned or a null value.
  3. For @ManyToMany, the collection type makes quite a difference as Sets perform better than Lists.

Set max-height on inner div so scroll bars appear, but not on parent div

If you make

overflow: hidden in the outer div and overflow-y: scroll in the inner div it will work.

http://jsfiddle.net/C8MuZ/11/

Visual Studio keyboard shortcut to display IntelliSense

In Visual Studio 2015 this shortcut opens a preview of the definition which even works through typedefs and #defines.

Ctrl + , (comma)

Enter image description here

What is the difference between functional and non-functional requirements?

FUNCTIONAL REQUIREMENTS the activities the system must perform

  • business uses functions the users carry out
  • use cases example if you are developing a payroll system required functions
  • generate electronic fund transfers
  • calculation commission amounts
  • calculate payroll taxes
  • report tax deduction to the IRS

PL/SQL, how to escape single quote in a string?

You can use literal quoting:

stmt := q'[insert into MY_TBL (Col) values('ER0002')]';

Documentation for literals can be found here.

Alternatively, you can use two quotes to denote a single quote:

stmt := 'insert into MY_TBL (Col) values(''ER0002'')';

The literal quoting mechanism with the Q syntax is more flexible and readable, IMO.

What is causing the error `string.split is not a function`?

run this

// you'll see that it prints Object
console.log(typeof document.location);

you want document.location.toString() or document.location.href

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

For a true comparison, you can use:

dateTime1.Date.CompareTo(dateTime2.Date);

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

You can also likely get around this issue by requiring 'thread' in your application as such:

require 'thread'

As per the RubyGems 1.6.0 release notes.

Insert data using Entity Framework model

[HttpPost] // it use when you write logic on button click event

public ActionResult DemoInsert(EmployeeModel emp)
{
    Employee emptbl = new Employee();    // make object of table
    emptbl.EmpName = emp.EmpName;
    emptbl.EmpAddress = emp.EmpAddress;  // add if any field you want insert
    dbc.Employees.Add(emptbl);           // pass the table object 
    dbc.SaveChanges();

    return View();
}

How to read input from console in a batch file?

In addition to the existing answer it is possible to set a default option as follows:

echo off
ECHO A current build of Test Harness exists.
set delBuild=n
set /p delBuild=Delete preexisting build [y/n] (default - %delBuild%)?:

This allows users to simply hit "Enter" if they want to enter the default.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

I've tried everything suggested here but didn't work for me. So in case I can help anyone with a similar issue, every single tutorial I've checked is not updated to work with version 4.

Here is what I've done to make it work

import React from 'react';
import App from './App';

import ReactDOM from 'react-dom';
import {
    HashRouter,
    Route
} from 'react-router-dom';


 ReactDOM.render((
        <HashRouter>
            <div>
                <Route path="/" render={()=><App items={temasArray}/>}/>
            </div>
        </HashRouter >
    ), document.getElementById('root'));

That's the only way I have managed to make it work without any errors or warnings.

In case you want to pass props to your component for me the easiest way is this one:

 <Route path="/" render={()=><App items={temasArray}/>}/>

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

'innerText' works in IE, but not in Firefox

Just reposting from comments under the original post. innerHTML works in all browsers. Thanks stefita.

myElement.innerHTML = "foo";

jQuery: how do I animate a div rotation?

I needed to rotate an object but have a call back function. Inspired by John Kern's answer I created this.

function animateRotate (object,fromDeg,toDeg,duration,callback){
        var dummy = $('<span style="margin-left:'+fromDeg+'px;">')
        $(dummy).animate({
            "margin-left":toDeg+"px"
        },
        {
            duration:duration,
            step: function(now,fx){
                $(object).css('transform','rotate(' + now + 'deg)');
                if(now == toDeg){
                    if(typeof callback == "function"){
                        callback();
                    }
                }
            }
        }
    )};

Doing this you can simply call the rotate on the object like so... (in my case I'm doing it on a disclosure triangle icon that has already been rotated by default to 270 degress and I'm rotating it another 90 degrees to 360 degrees at 1000 milliseconds. The final argument is the callback after the animation has finished.

animateRotate($(".disclosure_icon"),270,360,1000,function(){
                alert('finished rotate');
            });

When & why to use delegates?

Delegates are extremely useful when wanting to declare a block of code that you want to pass around. For example when using a generic retry mechanism.

Pseudo:

function Retry(Delegate func, int numberOfTimes)
    try
    {
       func.Invoke();
    }
    catch { if(numberOfTimes blabla) func.Invoke(); etc. etc. }

Or when you want to do late evaluation of code blocks, like a function where you have some Transform action, and want to have a BeforeTransform and an AfterTransform action that you can evaluate within your Transform function, without having to know whether the BeginTransform is filled, or what it has to transform.

And of course when creating event handlers. You don't want to evaluate the code now, but only when needed, so you register a delegate that can be invoked when the event occurs.

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:

[sdl]
windowresolution=1280x960
output=opengl

Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    /home/USERNAME/.dosbox/dosbox-0.74.conf
    $ vi "$(dosbox -printconf)"
    $ dosbox
    
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf
    

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    [snip]
    ---
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
    [snip]
    
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

How to search for string in an array

more simple Function whichs works on Apple OS too:

Function isInArray(ByVal stringToBeFound As String, ByVal arr As Variant) As Boolean
Dim element
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function

Create an array or List of all dates between two dates

list = list.Where(s => s.startDate >= Input_startDate && s.endDate <= Input_endDate);

 

Print number of keys in Redis

Since Redis 2.6, lua is supported, you can get number of wildcard keys like this

eval "return #redis.call('keys', 'prefix-*')" 0

see eval command

Why am I getting ImportError: No module named pip ' right after installing pip?

turned out i had 2 versions of python on my laptop

both commands worked for me

python -m ensurepip
py -m ensurepip

both with another installation path

c:\tools\python\lib\site-packages
c:\program files (x86)\microsoft visual studio\shared\python36_64\lib\site-packages 

only the first path was in my %PATH% variable

How to export private key from a keystore of self-signed certificate

public static void main(String[] args) {

try {
        String keystorePass = "20174";
        String keyPass = "rav@789";
        String alias = "TyaGi!";
        InputStream keystoreStream = new FileInputStream("D:/keyFile.jks");
        KeyStore keystore = KeyStore.getInstance("JCEKS");
        keystore.load(keystoreStream, keystorePass.toCharArray());
        Key key = keystore.getKey(alias, keyPass.toCharArray());

        byte[] bt = key.getEncoded();
        String s = new String(bt);
        System.out.println("------>"+s);      
        String str12 = Base64.encodeBase64String(bt);

        System.out.println("Fetched Key From JKS : " + str12);

    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
        System.out.println(ex);

    }
}

Shell script "for" loop syntax

There's more than one way to do it.

max=10
for i in `eval "echo {2..$max}"`
do
    echo "$i"
done

Break a previous commit into multiple commits

Easiest thing to do without an interactive rebase is (probably) to make a new branch starting at the commit before the one you want to split, cherry-pick -n the commit, reset, stash, commit the file move, reapply the stash and commit the changes, and then either merge with the former branch or cherry-pick the commits that followed. (Then switch the former branch name to the current head.) (It's probably better to follow MBOs advice and do an interactive rebase.)

Vertical (rotated) text in HTML table

Alternate Solution?

Instead of rotating the text, would it work to have it written "top to bottom?"

Like this:

S  
O  
M  
E  

T  
E  
X  
T  

I think that would be a lot easier - you can pick a string of text apart and insert a line break after each character.

This could be done via JavaScript in the browser like this:

"SOME TEXT".split("").join("\n")

... or you could do it server-side, so it wouldn't depend on the client's JS capabilities. (I assume that's what you mean by "portable?")

Also the user doesn't have to turn his/her head sideways to read it. :)

Update

This thread is about doing this with jQuery.

How to convert a string Date to long millseconds

Easiest way is used the Date Using Date() and getTime()

    Date dte=new Date();
    long milliSeconds = dte.getTime();
    String strLong = Long.toString(milliSeconds);
    System.out.println(milliSeconds)

How to change the background color of the options menu?

This is how i solved mine. I just specified the background color and text color in styles. ie res > values > styles.xml file.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:itemBackground">#ffffff</item>
    <item name="android:textColor">#000000</item>
</style>

How to have a transparent ImageButton: Android

Try using null for the background ...

android:background="@null"

Remove credentials from Git

Using latest version of git for Windows on Windows 10 Professional and I had a similar issue whereby I have two different GitHub accounts and also a Bitbucket account so things got a bit confusing for VS2017, git extensions and git bash.

I first checked how git was handling my credentials with this command (run git bash with elevated commands or you get errors):

git config --list

I found the entry Credential Manager so I clicked on the START button > typed Credential Manager to and left-clicked on the credential manager yellow safe icon which launched the app. I then clicked on the Windows Credentials tabs and found the entry for my current git account which happened to be Bit-bucket so I deleted this account.

But this didn't do the trick so the next step was to unset the credentials and I did this from the repository directory on my laptop that contains the GitHub project I am trying to push to the remote. I typed the following command:

git config --system --unset credential.helper

Then I did a git push and I was prompted for a GitHub username which I entered (the correct one I needed) and then the associated password and everything got pushed correctly.

I am not sure how much of an issue this is going forward most people probably work off the one repository but I have to work across several and using different providers so may encounter this issue again.

How to redirect 404 errors to a page in ExpressJS?

The answer to your question is:

app.use(function(req, res) {
    res.status(404).end('error');
});

And there is a great article about why it is the best way here.

Is there a way to 'uniq' by column?

If you want to retain the last one of the duplicates you could use

 tac a.csv | sort -u -t, -r -k1,1 |tac

Which was my requirement

here

tac will reverse the file line by line

NOW() function in PHP

If you want to get time now including AM / PM

<?php 
    $time_now = date("Y-m-d h:i:s a");
    echo $time_now;
?>

It outputs 2020-05-01 05:45:28 pm

or

<?php 
    $time_now = date("Y-m-d h:i:s A");
    echo $time_now;
?>

It outputs 2020-05-01 05:45:28 PM

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

Since December 2020 xlrd no longer supports xlsx-Files as explained in the official changelog. You can use openpyxl instead:

pip install openpyxl

And in your python-file:

import pandas as pd
pd.read_excel('path/to/file.xlsx', engine='openpyxl')

Clone() vs Copy constructor- which is recommended in java

Have in mind that clone() doesn't work out of the box. You will have to implement Cloneable and override the clone() method making in public.

There are a few alternatives, which are preferable (since the clone() method has lots of design issues, as stated in other answers), and the copy-constructor would require manual work:

How can I encode a string to Base64 in Swift?

@Airspeed Velocity answer in Swift 2.0:

let str = "iOS Developer Tips encoded in Base64"
print("Original: \(str)")
let base64Encoded = str.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions([])
print("Encoded: \(base64Encoded)")
let base64DecodedData = NSData(base64EncodedString: base64Encoded, options: [])!
var base64DecodedString = String(data: base64DecodedData, encoding: NSUTF8StringEncoding)!
print("Decoded: \(base64DecodedString)")

What causes "Unable to access jarfile" error?

I finally pasted my jar file into the same folder as my JDK so I didn't have to include the paths. I also had to open the command prompt as an admin.

  1. Right click Command Prompt and "Run as administrator"
  2. Navigate to the directory where you saved your jdk to
  3. In the command prompt type: java.exe -jar <jar file name>.jar

Search for exact match of string in excel row using VBA Macro

Use worksheet.find (worksheet is your worksheet) and use the row-range for its range-object. You can get the rangeobject like: worksheet.rows(rowIndex) as example

Then give find the required parameters it should find it for you fine. If I recall correctly, find returns the first match per default. I have no Excel at hand, so you have to look up find for yourself, sorry

I would advise against using a for-loop it is more fragile and ages slower than find.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Attempting to provide a concise update, based on Enzero's answer.

  • Install the Bootstrap.Datepicker package.

    PM> install-package Bootstrap.Datepicker
    ...
    Successfully installed 'Bootstrap.Datepicker 1.7.1' to ...
    
  • In AppStart/BundleConfig.cs, add the related scripts and styles in the bundles.

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
          //...,
          "~/Scripts/bootstrap-datepicker.js",
          "~/Scripts/locales/bootstrap-datepicker.YOUR-LOCALE-CODE-HERE.min.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
          ...,
          "~/Content/bootstrap-datepicker3.css"));
    
  • In the related view, in the scripts' section, enable and customize datepicker.

    @section scripts{
        <script type="text/javascript">
            //...
            $('.datepicker').datepicker({
                format: 'dd/mm/yyyy', //choose the date format you prefer
                language: "YOUR-LOCALE-CODE-HERE",
                orientation: 'left bottom'
            });
        </script>
    
  • Eventually add the datepicker class in the related control. For instance, in a TextBox and for a date format in the like of "31/12/2018" this would be:

    @Html.TextBox("YOUR-STRING-FOR-THE-DATE", "{0:dd/MM/yyyy}", new { @class = "datepicker" })
    

AngularJS format JSON string output

In addition to the angular json filter already mentioned, there is also the angular toJson() function.

angular.toJson(obj, pretty);

The second param of this function lets you switch on pretty printing and set the number of spaces to use.

If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

(default: 2)

Fetch: POST json data

After spending some times, reverse engineering jsFiddle, trying to generate payload - there is an effect.

Please take eye (care) on line return response.json(); where response is not a response - it is promise.

var json = {
    json: JSON.stringify({
        a: 1,
        b: 2
    }),
    delay: 3
};

fetch('/echo/json/', {
    method: 'post',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json'
    },
    body: 'json=' + encodeURIComponent(JSON.stringify(json.json)) + '&delay=' + json.delay
})
.then(function (response) {
    return response.json();
})
.then(function (result) {
    alert(result);
})
.catch (function (error) {
    console.log('Request failed', error);
});

jsFiddle: http://jsfiddle.net/egxt6cpz/46/ && Firefox > 39 && Chrome > 42

How can I recover the return value of a function passed to multiprocessing.Process?

Use shared variable to communicate. For example like this:

import multiprocessing


def worker(procnum, return_dict):
    """worker function"""
    print(str(procnum) + " represent!")
    return_dict[procnum] = procnum


if __name__ == "__main__":
    manager = multiprocessing.Manager()
    return_dict = manager.dict()
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i, return_dict))
        jobs.append(p)
        p.start()

    for proc in jobs:
        proc.join()
    print(return_dict.values())

Convert a dataframe to a vector (by rows)

You can try this to get your combination:

as.numeric(rbind(test$x, test$y))

which will return:

26, 34, 21, 29, 20, 28

How to highlight text using javascript

Why using a selfmade highlighting function is a bad idea

The reason why it's probably a bad idea to start building your own highlighting function from scratch is because you will certainly run into issues that others have already solved. Challenges:

  • You would need to remove text nodes with HTML elements to highlight your matches without destroying DOM events and triggering DOM regeneration over and over again (which would be the case with e.g. innerHTML)
  • If you want to remove highlighted elements you would have to remove HTML elements with their content and also have to combine the splitted text-nodes for further searches. This is necessary because every highlighter plugin searches inside text nodes for matches and if your keywords will be splitted into several text nodes they will not being found.
  • You would also need to build tests to make sure your plugin works in situations which you have not thought about. And I'm talking about cross-browser tests!

Sounds complicated? If you want some features like ignoring some elements from highlighting, diacritics mapping, synonyms mapping, search inside iframes, separated word search, etc. this becomes more and more complicated.

Use an existing plugin

When using an existing, well implemented plugin, you don't have to worry about above named things. The article 10 jQuery text highlighter plugins on Sitepoint compares popular highlighter plugins.

Have a look at mark.js

mark.js is such a plugin that is written in pure JavaScript, but is also available as jQuery plugin. It was developed to offer more opportunities than the other plugins with options to:

  • search for keywords separately instead of the complete term
  • map diacritics (For example if "justo" should also match "justò")
  • ignore matches inside custom elements
  • use custom highlighting element
  • use custom highlighting class
  • map custom synonyms
  • search also inside iframes
  • receive not found terms

DEMO

Alternatively you can see this fiddle.

Usage example:

// Highlight "keyword" in the specified context
$(".context").mark("keyword");

// Highlight the custom regular expression in the specified context
$(".context").markRegExp(/Lorem/gmi);

It's free and developed open-source on GitHub (project reference).

Fluid width with equally spaced DIVs

The easiest way to do this now is with a flexbox:

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

The CSS is then simply:

#container {
    display: flex;
    justify-content: space-between;
}

demo: http://jsfiddle.net/QPrk3/

However, this is currently only supported by relatively recent browsers (http://caniuse.com/flexbox). Also, the spec for flexbox layout has changed a few times, so it's possible to cover more browsers by additionally including an older syntax:

http://css-tricks.com/old-flexbox-and-new-flexbox/

http://css-tricks.com/using-flexbox/

Split string to equal length substrings in Java

I'd rather this simple solution:

String content = "Thequickbrownfoxjumps";
while(content.length() > 4) {
    System.out.println(content.substring(0, 4));
    content = content.substring(4);
}
System.out.println(content);

Auto-center map with multiple markers in Google Maps API v3

This work for me in Angular 9:

  import {GoogleMap, GoogleMapsModule} from "@angular/google-maps";
  @ViewChild('Map') Map: GoogleMap; /* Element Map */

  locations = [
   { lat: 7.423568, lng: 80.462287 },
   { lat: 7.532321, lng: 81.021187 },
   { lat: 6.117010, lng: 80.126269 }
  ];

  constructor() {
   var bounds = new google.maps.LatLngBounds();
    setTimeout(() => {
     for (let u in this.locations) {
      var marker = new google.maps.Marker({
       position: new google.maps.LatLng(this.locations[u].lat, 
       this.locations[u].lng),
      });
      bounds.extend(marker.getPosition());
     }

     this.Map.fitBounds(bounds)
    }, 200)
  }

And it automatically centers the map according to the indicated positions.

Result:

enter image description here

reducing number of plot ticks

To solve the issue of customisation and appearance of the ticks, see the Tick Locators guide on the matplotlib website

ax.xaxis.set_major_locator(plt.MaxNLocator(3))

Would set the total number of ticks in the x-axis to 3, and evenly distribute it across the axis.

There is also a nice tutorial about this

Get index of a key in json

Its too late, but it may be simple and useful

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
alert(index);

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

How can I have grep not print out 'No such file or directory' errors?

I redirect stderr to stdout and then use grep's invert-match (-v) to exclude the warning/error string that I want to hide:

grep -r <pattern> * 2>&1 | grep -v "No such file or directory"

How can I trigger a JavaScript event click

Fair warning:

element.onclick() does not behave as expected. It only runs the code within onclick="" attribute, but does not trigger default behavior.

I had similar issue with radio button not setting to checked, even though onclick custom function was running fine. Had to add radio.checked = "true"; to set it. Probably the same goes and for other elements (after a.onclick() there should be also window.location.href = "url";)

UIBarButtonItem in navigation bar programmatically?

Setting LeftBarButton with Original Image.

let menuButton = UIBarButtonItem(image: UIImage(named: "imagename").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(classname.functionname))
self.navigationItem.leftBarButtonItem  = menuButton

How to find the difference in days between two dates?

If the option -d works in your system, here's another way to do it. There is a caveat that it wouldn't account for leap years since I've considered 365 days per year.

date1yrs=`date -d "20100209" +%Y`
date1days=`date -d "20100209" +%j`
date2yrs=`date +%Y`
date2days=`date +%j`
diffyr=`expr $date2yrs - $date1yrs`
diffyr2days=`expr $diffyr \* 365`
diffdays=`expr $date2days - $date1days`
echo `expr $diffyr2days + $diffdays`

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 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) t0,
 (select 0 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) t1,
 (select 0 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) t2,
 (select 0 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) t3,
 (select 0 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) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

How to calculate difference in hours (decimal) between two dates in SQL Server?

SELECT DATEDIFF(hh, firstDate, secondDate) FROM tableName WHERE ...

Searching in a ArrayList with custom objects for certain strings

boolean found;

for(CustomObject obj : ArrayOfCustObj) {

   if(obj.getName.equals("Android")) {

      found = true;
   }
}

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

PHP - check if variable is undefined

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Example:

<?php
    $var1 = '';
    if(isset($var1)){
        echo 'This line is printed, because the $var1 is set.';
    }
?>

This code will output "This line is printed, because the $var1 is set."

read more in https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

How to remove class from all elements jquery

$(".edgetoedge>li").removeClass("highlight");

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'
/

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott
/

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

DECLARE
  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
BEGIN
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
  DBMS_LOB.CLOSE(v_src_loc);
  COMMIT;
END;
/

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

Preloading images with JavaScript

Here is my approach:

var preloadImages = function (srcs, imgs, callback) {
    var img;
    var remaining = srcs.length;
    for (var i = 0; i < srcs.length; i++) {
        img = new Image;
        img.onload = function () {
            --remaining;
            if (remaining <= 0) {
                callback();
            }
        };
        img.src = srcs[i];
        imgs.push(img);
    }
};

Define the selected option with the old input in Laravel / Blade

I have changed the code to include '' on the title value since without the quotes it fails to work

    <select class="form-control" name="team" id="team">
     <option value="">---------Choose Team---------</option>
           @foreach($teams as $team)
    <option value="{{$team->id}}" {{(old('team')==$team->id)? 'selected':''}}>{{$team->name}}</option>

    @endforeach
    </select>

    eg.<select name="title">
    <option value="1"  {{ old('title') == '1' ? 'selected' : '' }}>
        Item 1
    </option>
    <option value="2" {{ old('title') == '2' ? 'selected' : '' }}>
        Item 2
    </option>

    </select>

How do you get a directory listing in C?

The following POSIX program will print the names of the files in the current directory:

#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  struct dirent *ep;     
  dp = opendir ("./");

  if (dp != NULL)
  {
    while (ep = readdir (dp))
      puts (ep->d_name);

    (void) closedir (dp);
  }
  else
    perror ("Couldn't open the directory");

  return 0;
}

Credit: http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html

Tested in Ubuntu 16.04.

linking jquery in html

Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.

jquery, domain, get URL

You can use below codes for get different parameters of Current URL

alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);

Get most recent file in a directory on Linux

Presuming you don't care about hidden files that start with a .

ls -rt | tail -n 1

Otherwise

ls -Art | tail -n 1

TCPDF output without saving file

If You want to open dialogue window in browser to save, not open with PDF browser viewer (I was looking for this solution for a while), You should use 'D':

$pdf->Output('name.pdf', 'D');

Why does ++[[]][+[]]+[+[]] return the string "10"?

Let’s make it simple:

++[[]][+[]]+[+[]] = "10"

var a = [[]][+[]];
var b = [+[]];

// so a == [] and b == [0]

++a;

// then a == 1 and b is still that array [0]
// when you sum the var a and an array, it will sum b as a string just like that:

1 + "0" = "10"

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

If you're using an IIS Server, you could setup IIS URL Rewriting (v2) to rewrite the WWW-Authentication header to None on the requested URL.

Guide here.

The value you want to change is response_www_authenticate.

If you need more info, add a comment and I'll post the web.config file.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

JPA: How to get entity based on field value other than ID?

Using CrudRepository and JPA query works for me:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface TokenCrudRepository extends CrudRepository<Token, Integer> {

 /**
 * Finds a token by using the user as a search criteria.
 * @param user
 * @return  A token element matching with the given user.
 */
    @Query("SELECT t FROM Token t WHERE LOWER(t.user) = LOWER(:user)")
    public Token find(@Param("user") String user);

}

and you invoke the find custom method like this:

public void destroyCurrentToken(String user){
    AbstractApplicationContext context = getContext();

    repository = context.getBean(TokenCrudRepository.class);

    Token token = ((TokenCrudRepository) repository).find(user);

    int idToken = token.getId();

    repository.delete(idToken);

    context.close();
}

How to implement band-pass Butterworth filter with Scipy.signal.butter

For a bandpass filter, ws is a tuple containing the lower and upper corner frequencies. These represent the digital frequency where the filter response is 3 dB less than the passband.

wp is a tuple containing the stop band digital frequencies. They represent the location where the maximum attenuation begins.

gpass is the maximum attenutation in the passband in dB while gstop is the attentuation in the stopbands.

Say, for example, you wanted to design a filter for a sampling rate of 8000 samples/sec having corner frequencies of 300 and 3100 Hz. The Nyquist frequency is the sample rate divided by two, or in this example, 4000 Hz. The equivalent digital frequency is 1.0. The two corner frequencies are then 300/4000 and 3100/4000.

Now lets say you wanted the stopbands to be down 30 dB +/- 100 Hz from the corner frequencies. Thus, your stopbands would start at 200 and 3200 Hz resulting in the digital frequencies of 200/4000 and 3200/4000.

To create your filter, you'd call buttord as

fs = 8000.0
fso2 = fs/2
N,wn = scipy.signal.buttord(ws=[300/fso2,3100/fso2], wp=[200/fs02,3200/fs02],
   gpass=0.0, gstop=30.0)

The length of the resulting filter will be dependent upon the depth of the stop bands and the steepness of the response curve which is determined by the difference between the corner frequency and stopband frequency.

How to Parse JSON Array with Gson

I was looking for a way to parse object arrays in a more generic way; here is my contribution:

CollectionDeserializer.java:

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {

    @Override
    public Collection<?> deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];

        return parseAsArrayList(json, realType);
    }

    /**
     * @param serializedData
     * @param type
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
        ArrayList<T> newArray = new ArrayList<T>();
        Gson gson = new Gson();

        JsonArray array= json.getAsJsonArray();
        Iterator<JsonElement> iterator = array.iterator();

        while(iterator.hasNext()){
            JsonElement json2 = (JsonElement)iterator.next();
            T object = (T) gson.fromJson(json2, (Class<?>)type);
            newArray.add(object);
        }

        return newArray;
    }

}

JSONParsingTest.java:

public class JSONParsingTest {

    List<World> worlds;

    @Test
    public void grantThatDeserializerWorksAndParseObjectArrays(){

        String worldAsString = "{\"worlds\": [" +
            "{\"name\":\"name1\",\"id\":1}," +
            "{\"name\":\"name2\",\"id\":2}," +
            "{\"name\":\"name3\",\"id\":3}" +
        "]}";

        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
        Gson gson = builder.create();
        Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);

        assertNotNull(decoded);
        assertTrue(JSONParsingTest.class.isInstance(decoded));

        JSONParsingTest decodedObject = (JSONParsingTest)decoded;
        assertEquals(3, decodedObject.worlds.size());
        assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
    }
}

World.java:

public class World {
    private String name;
    private Long id;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}

Bash checking if string does not contain other string

Use !=.

if [[ ${testmystring} != *"c0"* ]];then
    # testmystring does not contain c0
fi

See help [[ for more information.

Making a UITableView scroll when text field is selected

I think there is no "right" way to do this. You have to choose the best fit solution for your use case. In my iPad App I have a UIViewController that is presented modal as UIModalPresentationFormSheet and consists of an UITableView. This table contains two UITextFields per cell. Just calling scrollToRowAtIndexPath:atScrollPosition:animated: in the textFieldDidBeginEditing: method doesn't work for me. Therefore I have created a tableFooterView:

- (void)viewDidLoad
{
    [super viewDidLoad];

    m_footerView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, m_tableView.frame.size.width, 300.0f)];
    [m_footerView setBackgroundColor:[UIColor clearColor]];
    [m_tableView setTableFooterView:m_footerView];
    [m_footerView release];
}

The idea is that keyboard hides the tableFooterView and not the UITextFields. So the tableFooterView must be high enough. After that you can use scrollToRowAtIndexPath:atScrollPosition:animated: in the textFieldDidBeginEditing: method.

I think it's also possible to show and hide the tableFooterView dynamically by adding the observers for the keyboard notifications but I haven't tried it yet:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillShow:) 
                                                 name:UIKeyboardWillShowNotification 
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(keyboardWillHide:) 
                                                 name:UIKeyboardWillHideNotification 
                                               object:nil];
}

- (void)keyboardWillShow:(NSNotification *)notification 
{
     [m_tableView setTableFooterView:m_footerView];
}

- (void)keyboardWillHide:(NSNotification *)notification 
{
     [m_tableView setTableFooterView:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

How to check if a user likes my Facebook Page or URL using Facebook's API

I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.

Here's another approach.

In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.

function parsePageSignedRequest() {
    if (isset($_REQUEST['signed_request'])) {
      $encoded_sig = null;
      $payload = null;
      list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
      $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
      $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
      return $data;
    }
    return false;
  }
  if($signed_request = parsePageSignedRequest()) {
    if($signed_request->page->liked) {
      echo "This content is for Fans only!";
    } else {
      echo "Please click on the Like button to view this tab!";
    }
  }

Difference between Git and GitHub

In plain English:

  1. They are all source control as we all know.
  2. In an analogy, if Git is a standalone computer, then GitHub is a network of computers connected by web with bells and whistlers.
  3. So unless you open a GitHub acct and specifically tell VSC or any editor to use GitHub, you'll see your source code up-there otherwise they are only down here, - your local machine.

Check if a column contains text using SQL

Leaving database modeling issues aside. I think you can try

SELECT * FROM STUDENTS WHERE ISNUMERIC(STUDENTID) = 0

But ISNUMERIC returns 1 for any value that seems numeric including things like -1.0e5

If you want to exclude digit-only studentids, try something like

SELECT * FROM STUDENTS WHERE STUDENTID LIKE '%[^0-9]%'

draw diagonal lines in div background with CSS

I needed to draw arbitrary diagonal lines inside any div. My issue with the other answers posted is that none of them allowed to draw an arbitrary line from point A to point B without doing the trigonometry yourself for the angles. With javascript & CSS you can do this. Hope it's helpful, just specify a pair of points and you're golden.

_x000D_
_x000D_
const objToStyleString = (obj) => {_x000D_
  const reducer = (acc, curr) => acc += curr + ": " + obj[curr] + ";"; _x000D_
  return Object.keys(obj).reduce(reducer, "")_x000D_
};_x000D_
_x000D_
const lineStyle = (xy1, xy2, borderStyle) => {_x000D_
  const p1 = {x: xy1[0], y: xy1[1]};_x000D_
  const p2 = {x: xy2[0], y: xy2[1]};_x000D_
  _x000D_
  const a = p2.x - p1.x;_x000D_
  const xOffset = p1.x;_x000D_
  const b = p2.y - p1.y;_x000D_
  const yOffset = p1.y;_x000D_
  _x000D_
  const c = Math.sqrt(a*a + b*b);_x000D_
  _x000D_
  const ang = Math.acos(a/c);_x000D_
  _x000D_
  const tX1 = `translateX(${-c/2 + xOffset}px) `;_x000D_
  const tY1 = `translateY(${yOffset}px) `;_x000D_
  const rot = `rotate(${ang}rad) `;_x000D_
  const tX2 = `translateX(${c/2}px) `;_x000D_
  const tY2 = `translateY(${0}px) `;_x000D_
  _x000D_
  return {_x000D_
    "width": Math.floor(c) + "px",_x000D_
    "height": "0px",_x000D_
    "border-top": borderStyle,_x000D_
    "-webkit-transform": tX1+tY1+rot+tX2+tY2,_x000D_
    "position": "relative",_x000D_
    "top": "0px",_x000D_
    "left": "0px",_x000D_
    "box-sizing": "border-box",_x000D_
  };_x000D_
};_x000D_
_x000D_
function drawLine(parent, p1, p2, borderStyle) {_x000D_
  const style = lineStyle(p1, p2, borderStyle);_x000D_
  const line = document.createElement("div");_x000D_
  line.style = objToStyleString(style);_x000D_
  parent.appendChild(line);_x000D_
}_x000D_
_x000D_
drawLine(container, [100,5], [25,195], "1px dashed purple");_x000D_
drawLine(container, [100,100], [190,190], "1px solid blue");_x000D_
drawLine(container, [25,150], [175,150], "2px solid red");_x000D_
drawLine(container, [25,10], [175,20], "5px dotted green");
_x000D_
#container {_x000D_
  background-color: #BCBCBC;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0; _x000D_
  margin: 0;_x000D_
}
_x000D_
<div id="container">_x000D_
</div>
_x000D_
_x000D_
_x000D_

JavaScript - populate drop down list with array

I had the same requirement, I used "Alex Turpin" solution with small corrections as mentioned below.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];

    var el = document.createElement("option");
    el.text = opt;
    el.value = opt;

    select.add(el);
}?

Corrections because with the appendChild() function is loads when the DOM prepares. So It's not working in old(8 or lesser) IE versions. So with the corrections it's working fine.

Thanks Alex for your solution.

Some notes on differences b/w add() and appendChild()

Difference Between One-to-Many, Many-to-One and Many-to-Many?

First of all, read all the fine print. Note that NHibernate (thus, I assume, Hibernate as well) relational mapping has a funny correspondance with DB and object graph mapping. For example, one-to-one relationships are often implemented as a many-to-one relationship.

Second, before we can tell you how you should write your O/R map, we have to see your DB as well. In particular, can a single Skill be possesses by multiple people? If so, you have a many-to-many relationship; otherwise, it's many-to-one.

Third, I prefer not to implement many-to-many relationships directly, but instead model the "join table" in your domain model--i.e., treat it as an entity, like this:

class PersonSkill 
{
    Person person;
    Skill skill;    
}

Then do you see what you have? You have two one-to-many relationships. (In this case, Person may have a collection of PersonSkills, but would not have a collection of Skills.) However, some will prefer to use many-to-many relationship (between Person and Skill); this is controversial.

Fourth, if you do have bidirectional relationships (e.g., not only does Person have a collection of Skills, but also, Skill has a collection of Persons), NHibernate does not enforce bidirectionality in your BL for you; it only understands bidirectionality of the relationships for persistence purposes.

Fifth, many-to-one is much easier to use correctly in NHibernate (and I assume Hibernate) than one-to-many (collection mapping).

Good luck!

What are database constraints?

  1. UNIQUE constraint (of which a PRIMARY KEY constraint is a variant). Checks that all values of a given field are unique across the table. This is X-axis constraint (records)

  2. CHECK constraint (of which a NOT NULL constraint is a variant). Checks that a certain condition holds for the expression over the fields of the same record. This is Y-axis constraint (fields)

  3. FOREIGN KEY constraint. Checks that a field's value is found among the values of a field in another table. This is Z-axis constraint (tables).

How to remove element from ArrayList by checking its value?

Snippet to remove a element from any arraylist based on the matching condition is as follows:

List<String> nameList = new ArrayList<>();
        nameList.add("Arafath");
        nameList.add("Anjani");
        nameList.add("Rakesh");

Iterator<String> myItr = nameList.iterator();

    while (myItr.hasNext()) {
        String name = myItr.next();
        System.out.println("Next name is: " + name);
        if (name.equalsIgnoreCase("rakesh")) {
            myItr.remove();
        }
    }

How can I strip HTML tags from a string in ASP.NET?

If it is just stripping all HTML tags from a string, this works reliably with regex as well. Replace:

<[^>]*(>|$)

with the empty string, globally. Don't forget to normalize the string afterwards, replacing:

[\s\r\n]+

with a single space, and trimming the result. Optionally replace any HTML character entities back to the actual characters.

Note:

  1. There is a limitation: HTML and XML allow > in attribute values. This solution will return broken markup when encountering such values.
  2. The solution is technically safe, as in: The result will never contain anything that could be used to do cross site scripting or to break a page layout. It is just not very clean.
  3. As with all things HTML and regex:
    Use a proper parser if you must get it right under all circumstances.

HTML text input allow only numeric input

This removes any bad character instantly, allows only one dot, is short, and allows backspace, etc.:

$('.numberInput').keyup(function () {
    s=$(this).val();
    if (!/^\d*\.?\d*$/.test(s)) $(this).val(s.substr(0,s.length-1));
});

How do I make XAML DataGridColumns fill the entire DataGrid?

set ONE column's width to any value, i.e. width="*"

how to run or install a *.jar file in windows?

To run usually click and it should run, that is if you have java installed. If not get java from here Sorry thought it was more general open a command prompt and type java -jar jbpm-installer-3.2.7.jar

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Speed tradeoff of Java's -Xms and -Xmx options

This was always the question I had when I was working on one of my application which created massive number of threads per request.

So this is a really good question and there are two aspects of this:
1. Whether my Xms and Xmx value should be same
       - Most websites and even oracle docs suggest it to be the same. However, I suggest to have some 10-20% of buffer between those values to give heap resizing an option to your application in case sudden high traffic spikes OR a incidental memory leak.

2. Whether I should start my Application with lower heap size
       - So here's the thing - no matter what GC Algo you use (even G1), large heap always has some trade off. The goal is to identify the behavior of your application to what heap size you can allow your GC pauses in terms of latency and throughput.
              - For example, if your application has lot of threads (each thread has 1 MB stack in native memory and not in heap) but does not occupy heavy object space, then I suggest have a lower value of Xms.
              - If your application creates lot of objects with increasing number of threads, then identify to what value of Xms you can set to tolerate those STW pauses. This means identify the max response time of your incoming requests you can tolerate and according tune the minimum heap size.

how can get index & count in vuejs

In case, your data is in the following structure, you get string as an index

items = {
   am:"Amharic",
   ar:"Arabic",
   az:"Azerbaijani",
   ba:"Bashkir",
   be:"Belarusian"
}

In this case, you can use extra variable to get the index in number:

<ul>
  <li v-for="(item, key, index) in items">
    {{ item }} - {{ key }} - {{ index }}
  </li>
</ul>

Source: https://alligator.io/vuejs/iterating-v-for/

NullInjectorError: No provider for AngularFirestore

Change Your Import From :

import { AngularFirestore } from '@angular/fire/firestore/firestore';

To This :

import { AngularFirestore } from '@angular/fire/firestore';

This solve my problem.

Python3 project remove __pycache__ folders and .pyc files

If you need a permanent solution for keeping Python cache files out of your project directories:

Starting with Python 3.8 you can use the environment variable PYTHONPYCACHEPREFIX to define a cache directory for Python.

From the Python docs:

If this is set, Python will write .pyc files in a mirror directory tree at this path, instead of in pycache directories within the source tree. This is equivalent to specifying the -X pycache_prefix=PATH option.

Example

If you add the following line to your ./profile in Linux:

export PYTHONPYCACHEPREFIX="$HOME/.cache/cpython/"

Python won't create the annoying __pycache__ directories in your project directory, instead it will put all of them under ~/.cache/cpython/

How to refresh token with Google API client?

According to Authentication on google: OAuth2 keeps returning 'invalid_grant'

"You should reuse the access token you get after the first successful authentication. You will get an invalid_grant error if your previous token has not expired yet. Cache it somewhere so you can reuse it."

hope it helps

Parsing a JSON string in Ruby

This looks like JavaScript Object Notation (JSON). You can parse JSON that resides in some variable, e.g. json_string, like so:

require 'json'
JSON.parse(json_string)

If you’re using an older Ruby, you may need to install the json gem.


There are also other implementations of JSON for Ruby that may fit some use-cases better:

TortoiseGit-git did not exit cleanly (exit code 1)

This is Just because you have made changes on your remote repository which was not pulled on your local repository.

To resolve simply 1. Pull from remote repository to local repository. It will not undo any changes locally. It will just update local repository. 2. Now push the changes to remote repository. It will work

How to set auto increment primary key in PostgreSQL?

I have tried the following script to successfully auto-increment the primary key in PostgreSQL.

CREATE SEQUENCE dummy_id_seq
    START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;

CREATE table dummyTable (
    id bigint DEFAULT nextval('dummy_id_seq'::regclass) NOT NULL,
    name character varying(50)
);

EDIT:

CREATE table dummyTable (
    id SERIAL NOT NULL,
    name character varying(50)
)

SERIAL keyword automatically create a sequence for respective column.

How can I print literal curly-brace characters in a string and also use .format on it?

If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).

jQuery "blinking highlight" effect on div?

This is a custom blink effect I created, which uses setInterval and fadeTo

HTML -

<div id="box">Box</div>

JS -

setInterval(function(){blink()}, 1000);


    function blink() {
        $("#box").fadeTo(100, 0.1).fadeTo(200, 1.0);
    }

As simple as it gets.

http://jsfiddle.net/Ajey/25Wfn/

Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine

I would also suggest running a few virtual machines rather than running multiple versions of Internet Explorer on the same instance of Windows.

Microsoft provides Virtual PC disk images with Internet Explorer 6, 7, and 8 at the Internet Explorer Application Compatibility VPC Image download page.

The current list of virtual disk images available from the above link are:

  • Internet Explorer 6 on Windows XP SP3
  • Internet Explorer 7 on Windows XP SP3
  • Internet Explorer 8 on Windows XP SP3
  • Internet Explorer 7 on Windows Vista
  • Internet Explorer 8 on Windows Vista

(List is current as of October 11, 2009. All versions have expiration dates.)

List of remotes for a Git repository?

None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:

$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.

The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.

As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.

How to get all subsets of a set? (powerset)

Perhaps the question is getting old, but I hope my code will help someone.

def powSet(set):
    if len(set) == 0:
       return [[]]
    return addtoAll(set[0],powSet(set[1:])) + powSet(set[1:])

def addtoAll(e, set):
   for c in set:
       c.append(e)
   return set

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

How can I split a string into segments of n characters?

str.match(/.{3}/g); // => ['abc', 'def', 'ghi', 'jkl']

SQL Server : GROUP BY clause to get comma-separated values

SELECT  [ReportId], 
        SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
        (
            SELECT DISTINCT [ReportId]
            FROM Table1
        ) a
        CROSS APPLY
        (
            SELECT [Email] + ', ' 
            FROM Table1 AS B 
            WHERE A.[ReportId] = B.[ReportId]
            FOR XML PATH('')
        ) D (EmailList) 

SQLFiddle Demo

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

How to make <input type="date"> supported on all browsers? Any alternatives?

<html>
<head>
<title>Date picker works for all browsers(IE, Firefox, Chrome)</title>
<script>
    var datefield = document.createElement("input")
    datefield.setAttribute("type", "date")
    if (datefield.type != "date") { // if browser doesn't support input type="date", load files for jQuery UI Date Picker
        document.write('<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />\n')
        document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"><\/script>\n')
        document.write('<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"><\/script>\n')
    }
</script>

<script>
    if (datefield.type != "date") { // if browser doesn't support input type="date", initialize date picker widget:
        jQuery(function($) { // on document.ready
            $('#start_date').datepicker({
                dateFormat: 'yy-mm-dd'
            });
            $('#end_date').datepicker({
                dateFormat: 'yy-mm-dd'
            });
        })
    }
</script>
</head>
<body>
    <input name="start_date" id="start_date" type="date" required>
    <input name="end_date" id="end_date" required>
</body>
</html>

How to get current foreground activity context in android?

I'm like 3 years late but I'll answer it anyway in case someone finds this like I did.

I solved this by simply using this:

    if (getIntent().toString().contains("MainActivity")) {
        // Do stuff if the current activity is MainActivity
    }

Note that "getIntent().toString()" includes a bunch of other text such as your package name and any intent filters for your activity. Technically we're checking the current intent, not activity, but the result is the same. Just use e.g. Log.d("test", getIntent().toString()); if you want to see all the text. This solution is a bit hacky but it's much cleaner in your code and the functionality is the same.

How to get text with Selenium WebDriver in Python

This is the correct answer. It worked!!

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome("E:\\Python\\selenium\\webdriver\\chromedriver.exe")
driver.get("https://www.tatacliq.com/global-desi-navy-embroidered-kurta/p-mp000000000876745")
driver.set_page_load_timeout(45)
driver.maximize_window()
driver.implicitly_wait(2)
driver.get_screenshot_as_file("E:\\Python\\Tatacliq.png")
print ("Executed Successfully")
driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").click()
SpecialPrice = driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").text
print(SpecialPrice)

Delegates in swift?

First class:

protocol NetworkServiceDelegate: class {

    func didCompleteRequest(result: String)
}


class NetworkService: NSObject {

    weak var delegate: NetworkServiceDelegate?

    func fetchDataFromURL(url : String) {
        delegate?.didCompleteRequest(url)
    }
}

Second class:

class ViewController: UIViewController, NetworkServiceDelegate {

    let network = NetworkService()

    override func viewDidLoad() {
        super.viewDidLoad()
        network.delegate = self
        network.fetchDataFromURL("Success!")
    }



    func didCompleteRequest(result: String) {
        print(result)
    }


}