Programs & Examples On #Marklogic

MarkLogic is an enterprise NoSQL database. It is document-oriented and can store, manage, and search JSON, XML, plain text, and binary data. MarkLogic is scalable and elastic, has enterprise security and ACID transactions. It also has a REST API and Node.js and Java Client APIs as well as a number of other extensions.

Assign an initial value to radio button as checked

Note that if you have two radio button with same "name" attribute and they have "required" attribute, then adding "checked" attribute to them won't make them checked.

Example: This makes both radio button remain unchecked.

<input type="radio" name="gender" value="male" required <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" required />

This will makes the "male" radio button checked.

<input type="radio" name="gender" value="male" <?php echo "checked"; ?>/>
<input type="radio" name="gender" value="female" />

Five equal columns in twitter bootstrap

By default Bootstrap does not provide grid system that allows us to create five columns layout, you need to create default column definition in the way that Bootstrap do create some custom classes and media queries in your css file

.col-xs-15,
.col-sm-15,
.col-md-15,
.col-lg-15 {
    position: relative;
    min-height: 1px;
    padding-right: 10px;
    padding-left: 10px;
}
.col-xs-15 {
    width: 20%;
    float: left;
}
@media (min-width: 768px) {
.col-sm-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: 992px) {
    .col-md-15 {
        width: 20%;
        float: left;
    }
}
@media (min-width: 1200px) {
    .col-lg-15 {
        width: 20%;
        float: left;
    }
}

and some html code

<div class="row">
    <div class="col-md-15 col-sm-3">
    ...
    </div>
</div>

Install apk without downloading

you can use this code .may be solve the problem

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);

SSL cert "err_cert_authority_invalid" on mobile chrome only

I hope i am not too late, this solution here worked for me, i am using COMODO SSL, the above solutions seem invalid over time, my website lifetanstic.co.ke

Instead of contacting Comodo Support and gain a CA bundle file You can do the following:

When You get your new SSL cert from Comodo (by mail) they have a zip file attached. You need to unzip the zip-file and open the following files in a text editor like notepad:

AddTrustExternalCARoot.crt
COMODORSAAddTrustCA.crt
COMODORSADomainValidationSecureServerCA.crt

Then copy the text of each ".crt" file and paste the texts above eachother in the "Certificate Authority Bundle (optional)" field.

After that just add the SSL cert as usual in the "Certificate" field and click at "Autofil by Certificate" button and hit "Install".

Inspired by this gist: https://gist.github.com/ipedrazas/6d6c31144636d586dcc3

How do you find the sum of all the numbers in an array in Java?

A bit surprised to see None of the above answers considers it can be multiple times faster using a thread pool. Here, parallel uses a fork-join thread pool and automatically break the stream in multiple parts and run them parallel and then merge. If you just remember the following line of code you can use it many places.

So the award for the fastest short and sweet code goes to -

int[] nums = {1,2,3};
int sum =  Arrays.stream(nums).parallel().reduce(0, (a,b)-> a+b);

Lets say you want to do sum of squares , then Arrays.stream(nums).parallel().map(x->x*x).reduce(0, (a,b)-> a+b). Idea is you can still perform reduce , without map .

How to calculate the inverse of the normal cumulative distribution function in python?

# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1

#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763

#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237

#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)

#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)

#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

Here's what I've been doing:

  public void displayError(final String errorText) {
    Runnable doDisplayError = new Runnable() {
        public void run() {
            Toast.makeText(getApplicationContext(), errorText, Toast.LENGTH_LONG).show();
        }
    };
    messageHandler.post(doDisplayError);
}

That should allow the method to be called from either thread.

Where messageHandler is declared in the activity as ..

Handler messageHandler = new Handler();

No plot window in matplotlib

If you are starting IPython with the --pylab option, you shouldn't need to call show() or draw(). Try this:

ipython  --pylab=inline

MySQL Query - Records between Today and Last 30 Days

DATE_FORMAT returns a string, so you're using two strings in your BETWEEN clause, which isn't going to work as you expect.

Instead, convert the date to your format in the SELECT and do the BETWEEN for the actual dates. For example,

SELECT DATE_FORMAT(create_date, '%m/%d/%y') as create_date_formatted
FROM table
WHERE create_date BETWEEN (CURDATE() - INTERVAL 30 DAY) AND CURDATE()

How to set shadows in React Native for android?

The elevation style property on Android does not work unless backgroundColor has been specified for the element.

Android - elevation style property does not work without backgroundColor

Example:

{
  shadowColor: 'black',
  shadowOpacity: 0.26,
  shadowOffset: { width: 0, height: 2},
  shadowRadius: 10,
  elevation: 3,
  backgroundColor: 'white'
}

Automatically get loop index in foreach loop in Perl

perldoc perlvar does not seem to suggest any such variable.

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

For those who still have problems (Cannot pass parameter 2 by reference), define a variable with null value, not just pass null to PDO:

bindValue(':param', $n = null, PDO::PARAM_INT);

Hope this helps.

Reverse of JSON.stringify?

You need to JSON.parse() the string.

_x000D_
_x000D_
var str = '{"hello":"world"}';
try {
  var obj = JSON.parse(str); // this is how you parse a string into JSON 
  document.body.innerHTML += obj.hello;
} catch (ex) {
  console.error(ex);
}
_x000D_
_x000D_
_x000D_

Move column by name to front of table in pandas

I didn't like how I had to explicitly specify all the other column in the other solutions so this worked best for me. Though it might be slow for large dataframes...?

df = df.set_index('Mid').reset_index()

How are iloc and loc different?

  • DataFrame.loc() : Select rows by index value
  • DataFrame.iloc() : Select rows by rows number

example :

  1. Select first 5 rows of a table, df1 is your dataframe

df1.iloc[:5]

  1. Select first A, B rows of a table, df1 is your dataframe

df1.loc['A','B']

ImportError: No module named PyQt4

You have to check which Python you are using. I had the same problem because the Python I was using was not the same one that brew was using. In your command line:

  1. which python
    output: /usr/bin/python
  2. which brew
    output: /usr/local/bin/brew     //so they are different
  3. cd /usr/local/lib/python2.7/site-packages
  4. ls   //you can see PyQt4 and sip are here
  5. Now you need to add usr/local/lib/python2.7/site-packages to your python path.
  6. open ~/.bash_profile   //you will open your bash_profile file in your editor
  7. Add 'export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH' to your bash file and save it
  8. Close your terminal and restart it to reload the shell
  9. python
  10. import PyQt4    // it is ok now

How to click or tap on a TextView text

This may not be quite what you are looking for but this is what worked for what I'm doing. All of this is after my onCreate:

boilingpointK = (TextView) findViewById(R.id.boilingpointK);

boilingpointK.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if ("Boiling Point K".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("2792");
        else if ("2792".equals(boilingpointK.getText().toString()))
            boilingpointK.setText("Boiling Point K");
    }
});

What's the difference between `raw_input()` and `input()` in Python 3?

The difference is that raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). (Remember that eval() is evil. Try to use safer ways of parsing your input if possible.)

Is there a way to make mv create the directory to be moved to if it doesn't exist?

You can even use brace extensions:

mkdir -p directory{1..3}/subdirectory{1..3}/subsubdirectory{1..2}      
  • which creates 3 directories (directory1, directory2, directory3),
    • and in each one of them two subdirectories (subdirectory1, subdirectory2),
      • and in each of them two subsubdirectories (subsubdirectory1 and subsubdirectory2).

You have to use bash 3.0 or newer.

Setting the Textbox read only property to true using JavaScript

document.getElementById('textbox-id').readOnly=true should work

How to add parameters to a HTTP GET request in Android?

As of HttpComponents 4.2+ there is a new class URIBuilder, which provides convenient way for generating URIs.

You can use either create URI directly from String URL:

List<NameValuePair> listOfParameters = ...;

URI uri = new URIBuilder("http://example.com:8080/path/to/resource?mandatoryParam=someValue")
    .addParameter("firstParam", firstVal)
    .addParameter("secondParam", secondVal)
    .addParameters(listOfParameters)
    .build();

Otherwise, you can specify all parameters explicitly:

URI uri = new URIBuilder()
    .setScheme("http")
    .setHost("example.com")
    .setPort(8080)
    .setPath("/path/to/resource")
    .addParameter("mandatoryParam", "someValue")
    .addParameter("firstParam", firstVal)
    .addParameter("secondParam", secondVal)
    .addParameters(listOfParameters)
    .build();

Once you have created URI object, then you just simply need to create HttpGet object and perform it:

//create GET request
HttpGet httpGet = new HttpGet(uri);
//perform request
httpClient.execute(httpGet ...//additional parameters, handle response etc.

Automatic exit from Bash shell script on error

Here is how to do it:

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE *** 
************
'

Versioning SQL Server database

A while ago I found a VB bas module that used DMO and VSS objects to get an entire db scripted off and into VSS. I turned it into a VB Script and posted it here. You can easily take out the VSS calls and use the DMO stuff to generate all the scripts, and then call SVN from the same batch file that calls the VBScript to check them in.

What's the fastest way to read a text file line-by-line?

You can't get any faster if you want to use an existing API to read the lines. But reading larger chunks and manually find each new line in the read buffer would probably be faster.

repaint() in Java

You may need to call frame.repaint() as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.

Various ways to remove local Git changes

The best way is checking out the changes.

Changing the file pom.xml in a project named project-name you can do it:

git status

# modified:   project-name/pom.xml

git checkout project-name/pom.xml
git checkout master

# Checking out files: 100% (491/491), done.
# Branch master set up to track remote branch master from origin.
# Switched to a new branch 'master'

Microsoft.Office.Core Reference Missing

Now there is a nuget package for that.

https://www.nuget.org/packages/NetOffice.Core.Net40/

First I didn't find office in COM, so tried this nuget and it worked!

Visual Studio Code Search and Replace with Regular Expressions

Make sure Match Case is selected with Use Regular Expression so this matches. [A-Z]* If match case is not selected, this matches all letters.

How to Delete a topic in apache kafka

Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable to true) on all brokers first.

Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable is by default true.

Follow this step by step process for manual deletion of topics

  1. Stop Kafka server
  2. Delete the topic directory, on each broker (as defined in the logs.dirs and log.dir properties) with rm -rf command
  3. Connect to Zookeeper instance: zookeeper-shell.sh host:port
  4. From within the Zookeeper instance:
    1. List the topics using: ls /brokers/topics
    2. Remove the topic folder from ZooKeeper using: rmr /brokers/topics/yourtopic
    3. Exit the Zookeeper instance (Ctrl+C)
  5. Restart Kafka server
  6. Confirm if it was deleted or not by using this command kafka-topics.sh --list --zookeeper host:port

How to solve privileges issues when restore PostgreSQL Database

Use the postgres (admin) user to dump the schema, recreate it and grant priviledges for use before you do your restore. In one command:

sudo -u postgres psql -c "DROP SCHEMA public CASCADE;
create SCHEMA public;
grant usage on schema public to public;
grant create on schema public to public;" myDBName

Show Image View from file path?

You may use this to access a specific folder and get particular image

 public void Retrieve(String path, String Name)
   {
    File imageFile = new File(path+Name);

    if(imageFile.exists()){

        Bitmap myBitmap = BitmapFactory.decodeFile(path+Name);
        myImage = (ImageView) findViewById(R.id.savedImage);
        myImage.setImageBitmap(myBitmap);
        Toast.makeText(SaveImage.this, myBitmap.toString(), Toast.LENGTH_LONG).show();

    }
}

And then you can call it by

Retrieve(Environment.getExternalStorageDirectory().toString()+"/Aqeel/Images/","Image2.PNG");
Toast.makeText(SaveImage.this, "Saved", Toast.LENGTH_LONG).show();

Git Bash is extremely slow on Windows 7 x64

Do you have Git information showing in your Bash prompt? If so, maybe you're inadvertently doing way too much work on every command. To test this theory try the following temporary change in Bash:

export PS1='$'

Check for false

If you want an explicit check against false (and not undefined, null and others which I assume as you are using !== instead of !=) then yes, you have to use that.

Also, this is the same in a slightly smaller footprint:

if(borrar() !== !1)

How do malloc() and free() work?

malloc and free are implementation dependent. A typical implementation involves partitioning available memory into a "free list" - a linked list of available memory blocks. Many implementations artificially divide it into small vs large objects. Free blocks start with information about how big the memory block is and where the next one is, etc.

When you malloc, a block is pulled from the free list. When you free, the block is put back in the free list. Chances are, when you overwrite the end of your pointer, you are writing on the header of a block in the free list. When you free your memory, free() tries to look at the next block and probably ends up hitting a pointer that causes a bus error.

What does Java option -Xmx stand for?

C:\java -X

    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

Deleting specific rows from DataTable

the easy way use this in button :

 var table = $('#example1').DataTable();
 table.row($(`#yesmediasec-${id}`).closest('tr')).remove( ).draw();

example1 = id table . yesmediasec = id of the button in the row

use it and every thing will be ok

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

UICollectionView Set number of columns

CollectionViews are very powerful, and they come at a price. Lots, and lots of options. As omz said:

there are multiple ways you could change the number of columns

I'd suggest implementing the <UICollectionViewDelegateFlowLayout> Protocol, giving you access to the following methods in which you can have greater control over the layout of your UICollectionView, without the need for subclassing it:

  • collectionView:layout:insetForSectionAtIndex:
  • collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
  • collectionView:layout:minimumLineSpacingForSectionAtIndex:
  • collectionView:layout:referenceSizeForFooterInSection:
  • collectionView:layout:referenceSizeForHeaderInSection:
  • collectionView:layout:sizeForItemAtIndexPath:

Also, implementing the following method will force your UICollectionView to update it's layout on an orientation change: (say you wanted to re-size the cells for landscape and make them stretch)

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                               duration:(NSTimeInterval)duration{

    [self.myCollectionView.collectionViewLayout invalidateLayout];
}

Additionally, here are 2 really good tutorials on UICollectionViews:

http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12

http://skeuo.com/uicollectionview-custom-layout-tutorial

How do I make a self extract and running installer

Okay I have got it working, hope this information is useful.

  1. First of all I now realize that not only do self-extracting zip start extracting with doubleclick, but they require no extraction application to be installed on the users computer because the extractor code is in the archive itself. This means that you will get a different user experience depending on what you application you use to create the sfx

  2. I went with WinRar as follows, this does not require you to create an sfx file, everything can be created via the gui:

    • Select files, right click and select Add to Archive
    • Use Browse.. to create the archive in the folder above
    • Change Archive Format to Zip
    • Enable Create SFX archive
    • Select Advanced tab
    • Select SFX Options
    • Select Setup tab
    • Enter setup.exe into the Run after Extraction field
    • Select Modes tab
    • Enable Unpack to temporary folder
    • Select text and Icon tab
    • Enter a more appropriate title for your task
    • Select OK
    • Select OK

The resultant exe unzips to a temporary folder and then starts the installer

Collision resolution in Java HashMap

There is no collision in your example. You use the same key, so the old value gets replaced with the new one. Now, if you used two keys that map to the same hash code, then you'd have a collision. But even in that case, HashMap would replace your value! If you want the values to be chained in case of a collision, you have to do it yourself, e.g. by using a list as a value.

JavaScript module pattern with example

I thought i'd expand on the above answer by talking about how you'd fit modules together into an application. I'd read about this in the doug crockford book but being new to javascript it was all still a bit mysterious.

I come from a c# background so have added some terminology I find useful from there.

Html

You'll have some kindof top level html file. It helps to think of this as your project file. Every javascript file you add to the project wants to go into this, unfortunately you dont get tool support for this (I'm using IDEA).

You need add files to the project with script tags like this:

        <script type="text/javascript" src="app/native/MasterFile.js" /></script>
        <script type="text/javascript" src="app/native/SomeComponent.js" /></script>

It appears collapsing the tags causes things to fail - whilst it looks like xml it's really something with crazier rules!

Namespace file

MasterFile.js

myAppNamespace = {};

that's it. This is just for adding a single global variable for the rest of our code to live in. You could also declare nested namespaces here (or in their own files).

Module(s)

SomeComponent.js

myAppNamespace.messageCounter= (function(){

    var privateState = 0;

    var incrementCount = function () {
        privateState += 1;
    };

    return function (message) {
        incrementCount();
        //TODO something with the message! 
    }
})();

What we're doing here is assigning a message counter function to a variable in our application. It's a function which returns a function which we immediately execute.

Concepts

I think it helps to think of the top line in SomeComponent as being the namespace where you are declaring something. The only caveat to this is all your namespaces need to appear in some other file first - they are just objects rooted by our application variable.

I've only taken minor steps with this at the moment (i'm refactoring some normal javascript out of an extjs app so I can test it) but it seems quite nice as you can define little functional units whilst avoiding the quagmire of 'this'.

You can also use this style to define constructors by returning a function which returns an object with a collection of functions and not calling it immediately.

Can't install any packages in Node.js using "npm install"

Npm repository is currently down. See issue #2694 on npm github

EDIT:
To use a mirror in the meanwhile:

 npm set registry http://ec2-46-137-149-160.eu-west-1.compute.amazonaws.com

you can reset this later with:

 npm set registry https://registry.npmjs.org/

source

How to use if-else option in JSTL

I got away with simply using two if tags, thought I'd add an answer in case it's of use to anyone else:

<c:if test="${condition}">
  ...
</c:if>
<c:if test="${!condition}">
  ...
</c:if>

whilst technically not an if-else per se, the behaviour is the same and avoids the clunky approach of using the choose tag, so depending on how complex your requirement is this might be preferable.

CodeIgniter: 404 Page Not Found on Live Server

I was able to fix similar errors by changeing

http://ip-address/html/ci3-fire-starter/htdocs/index.php/

on the application/config/config.php line 26.

Compare every item to every other item in ArrayList

What's the problem with using for loop inside, just like outside?

for (int j = i + 1; j < list.size(); ++j) {
    ...
}

In general, since Java 5, I used iterators only once or twice.

Difference between SelectedItem, SelectedValue and SelectedValuePath

Every control that uses Collections to store data have SelectedValue, SelectedItem property. Examples of these controls are ListBox, Dropdown, RadioButtonList, CheckBoxList.

To be more specific if you literally want to retrieve Text of Selected Item then you can write:

ListBox1.SelectedItem.Text;

Your ListBox1 can also return Text using SelectedValue property if value has set to that before. But above is more effective way to get text.

Now, the value is something that is not visible to user but it is used mostly to store in database. We don't insert Text of ListBox1, however we can insert it also, but we used to insert value of selected item. To get value we can use

ListBox1.SelectedValue

Source

What is the proper way to check and uncheck a checkbox in HTML5?

Complementary answer to Robert's answer http://jsfiddle.net/ak9Sb/ in jQuery

When getting/setting checkbox state, one may encounter these phenomenons:

.trigger("click");

Does check an unchecked checkbox, but do not add the checked attribute. If you use triggers, do not try to get the state with "checked" attribute.

.attr("checked", "");

Does not uncheck the checkbox...

Find the max of 3 numbers in Java with different data types

you can use this:

 Collections.max(Arrays.asList(1,2,3,4));

or create a function

public static int max(Integer... vals) {
    return Collections.max(Arrays.asList(vals)); 
}

read file from assets

Here is what I do in an activity for buffered reading extend/modify to match your needs

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt")));

    // do reading, usually loop until end of file reading  
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}

EDIT : My answer is perhaps useless if your question is on how to do it outside of an activity. If your question is simply how to read a file from asset then the answer is above.

UPDATE :

To open a file specifying the type simply add the type in the InputStreamReader call as follow.

BufferedReader reader = null;
try {
    reader = new BufferedReader(
        new InputStreamReader(getAssets().open("filename.txt"), "UTF-8")); 

    // do reading, usually loop until end of file reading 
    String mLine;
    while ((mLine = reader.readLine()) != null) {
       //process line
       ...
    }
} catch (IOException e) {
    //log the exception
} finally {
    if (reader != null) {
         try {
             reader.close();
         } catch (IOException e) {
             //log the exception
         }
    }
}

EDIT

As @Stan says in the comment, the code I am giving is not summing up lines. mLine is replaced every pass. That's why I wrote //process line. I assume the file contains some sort of data (i.e a contact list) and each line should be processed separately.

In case you simply want to load the file without any kind of processing you will have to sum up mLine at each pass using StringBuilder() and appending each pass.

ANOTHER EDIT

According to the comment of @Vincent I added the finally block.

Also note that in Java 7 and upper you can use try-with-resources to use the AutoCloseable and Closeable features of recent Java.

CONTEXT

In a comment @LunarWatcher points out that getAssets() is a class in context. So, if you call it outside of an activity you need to refer to it and pass the context instance to the activity.

ContextInstance.getAssets();

This is explained in the answer of @Maneesh. So if this is useful to you upvote his answer because that's him who pointed that out.

How do I Search/Find and Replace in a standard string?

In C++11, you can do this as a one-liner with a call to regex_replace:

#include <string>
#include <regex>

using std::string;

string do_replace( string const & in, string const & from, string const & to )
{
  return std::regex_replace( in, std::regex(from), to );
}

string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;

output:

Removeallspaces

apache server reached MaxClients setting, consider raising the MaxClients setting

Here's an approach that could resolve your problem, and if not would help with troubleshooting.

  1. Create a second Apache virtual server identical to the current one

  2. Send all "normal" user traffic to the original virtual server

  3. Send special or long-running traffic to the new virtual server

Special or long-running traffic could be report-generation, maintenance ops or anything else you don't expect to complete in <<1 second. This can happen serving APIs, not just web pages.

If your resource utilization is low but you still exceed MaxClients, the most likely answer is you have new connections arriving faster than they can be serviced. Putting any slow operations on a second virtual server will help prove if this is the case. Use the Apache access logs to quantify the effect.

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

Rails: Get Client IP address

request.remote_ip is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.

How to print a debug log?

A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents('php://stderr', print_r($foo, TRUE)) will nicely dump the value of $foo into the Apache error log.

jQuery: how to get which button was clicked upon form submission?

You can create input type="hidden" as holder for a button id information.

<input type="hidden" name="button" id="button">
<input type="submit" onClick="document.form_name.button.value = 1;" value="Do something" name="do_something">

In this case form passes value "1" (id of your button) on submit. This works if onClick occurs before submit (?), what I am not sure if it is always true.

How to make the web page height to fit screen height

Don't give exact heights, but relative ones, adding up to 100%. For example:

  #content {height: 80%;}
  #footer {height: 20%;}

Add in

 html, body {height: 100%;}

Override hosts variable of Ansible playbook from the command line

We use a simple fail task to force the user to specify the Ansible limit option, so that we don't execute on all hosts by default/accident.

The easiest way I found is this:

---
- name: Force limit
  # 'all' is okay here, because the fail task will force the user to specify a limit on the command line, using -l or --limit
  hosts: 'all'

  tasks:
  - name: checking limit arg
    fail:
      msg: "you must use -l or --limit - when you really want to use all hosts, use -l 'all'"
    when: ansible_limit is not defined
    run_once: true

Now we must use the -l (= --limit option) when we run the playbook, e.g.

ansible-playbook playbook.yml -l www.example.com

Limit option docs:

Limit to one or more hosts This is required when one wants to run a playbook against a host group, but only against one or more members of that group.

Limit to one host

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1"

Limit to multiple hosts

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit "host1,host2"

Negated limit.
NOTE: Single quotes MUST be used to prevent bash interpolation.

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'all:!host1'

Limit to host group

ansible-playbook playbooks/PLAYBOOK_NAME.yml --limit 'group1'

How can I replace every occurrence of a String in a file with PowerShell?

Here's a fairly simple one that supports multiline regular expressions, multiple files (using the pipeline), specifying output encoding, etc. Not recommended for very large files due to the ReadAllText method.

# Update-FileText.ps1

#requires -version 2

<#
.SYNOPSIS
Updates text in files using a regular expression.

.DESCRIPTION
Updates text in files using a regular expression.

.PARAMETER Pattern
Specifies the regular expression pattern.

.PARAMETER Replacement
Specifies the regular expression replacement pattern.

.PARAMETER Path
Specifies the path to one or more files. Wildcards are not supported. Each file is read entirely into memory to support multi-line searching and replacing, so performance may be slow for large files.

.PARAMETER CaseSensitive
Specifies case-sensitive matching. The default is to ignore case.

.PARAMETER SimpleMatch
Specifies a simple match rather than a regular expression match (i.e., the Pattern parameter specifies a simple string rather than a regular expression).

.PARAMETER Multiline
Changes the meaning of ^ and $ so they match at the beginning and end, respectively, of any line, and not just the beginning and end of the entire file. The default is that ^ and $, respectively, match the beginning and end of the entire file.

.PARAMETER UnixText
Causes $ to match only linefeed (\n) characters. By default, $ matches carriage return+linefeed (\r\n). (Windows-based text files usually use \r\n as line terminators, while Unix-based text files usually use only \n.)

.PARAMETER Overwrite
Overwrites a file by creating a temporary file containing all replacements and then replacing the original file with the temporary file. The default is to output but not overwrite.

.PARAMETER Force
Allows overwriting of read-only files. Note that this parameter cannot override security restrictions.

.PARAMETER Encoding
Specifies the encoding for the file when -Overwrite is used. Possible values for this parameter are ASCII, BigEndianUnicode, Unicode, UTF32, UTF7, and UTF8. The default value is ASCII.

.INPUTS
System.IO.FileInfo.

.OUTPUTS
System.String (single-line file) or System.String[] (file with more than one line) without the -Overwrite parameter, or nothing with the -Overwrite parameter.

.LINK
about_Regular_Expressions

.EXAMPLE
C:\> Update-FileText.ps1 '(Ferb) and (Phineas)' '$2 and $1' Story.txt

This command replaces the text 'Ferb and Phineas' with the text 'Phineas and Ferb' in the file Story.txt and outputs the content. Note that the pattern and replacement strings are enclosed in single quotes to prevent variable expansion.

.EXAMPLE
C:\> Update-FileText.ps1 'Perry' 'Agent P' Story2.txt -Overwrite

This command replaces the text 'Perry' with the text 'Agent P' in the file Story2.txt.
#>

[CmdletBinding(SupportsShouldProcess = $true,ConfirmImpact = "High")]
param(
  [Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true)]
  [String[]] $Path,

  [Parameter(Mandatory = $true,Position = 1)]
  [String] $Pattern,

  [Parameter(Mandatory = $true,Position = 2)]
  [AllowEmptyString()]
  [String] $Replacement,

  [Switch] $CaseSensitive,

  [Switch] $SimpleMatch,

  [Switch] $Multiline,

  [Switch] $UnixText,

  [Switch] $Overwrite,

  [Switch] $Force,

  [ValidateSet("ASCII","BigEndianUnicode","Unicode","UTF32","UTF7","UTF8")]
  [String] $Encoding = "ASCII"
)

begin {
  function Get-TempName {
    param(
      $path
    )
    do {
      $tempName = Join-Path $path ([IO.Path]::GetRandomFilename())
    }
    while ( Test-Path $tempName )
    $tempName
  }

  if ( $SimpleMatch ) {
      $Pattern = [Regex]::Escape($Pattern)
  }
  else {
    if ( -not $UnixText ) {
      $Pattern = $Pattern -replace '(?<!\\)\$','\r$'
    }
  }

  function New-Regex {
    $regexOpts = [Text.RegularExpressions.RegexOptions]::None
    if ( -not $CaseSensitive ) {
      $regexOpts = $regexOpts -bor [Text.RegularExpressions.RegexOptions]::IgnoreCase
    }
    if ( $Multiline ) {
      $regexOpts = $regexOpts -bor [Text.RegularExpressions.RegexOptions]::Multiline
    }
    New-Object Text.RegularExpressions.Regex $Pattern,$regexOpts
  }

  $Regex = New-Regex

  function Update-FileText {
    param(
      $path
    )
    $pathInfo = Resolve-Path -LiteralPath $path
    if ( $pathInfo ) {
      if ( (Get-Item $pathInfo).GetType().FullName -eq "System.IO.FileInfo" ) {
        $fullName = $pathInfo.Path
        Write-Verbose "Reading '$fullName'"
        $text = [IO.File]::ReadAllText($fullName)
        Write-Verbose "Finished reading '$fullName'"
        if ( -not $Overwrite ) {
          $regex.Replace($text,$Replacement)
        }
        else {
          $tempName = Get-TempName (Split-Path $fullName -Parent)
          Set-Content $tempName $null -Confirm:$false
          if ( $? ) {
            Write-Verbose "Created file '$tempName'"
            try {
              Write-Verbose "Started writing '$tempName'"
              [IO.File]::WriteAllText("$tempName",$Regex.Replace($text,$Replacement),[Text.Encoding]::$Encoding)
              Write-Verbose "Finished writing '$tempName'"
              Write-Verbose "Started copying '$tempName' to '$fullName'"
              Copy-Item $tempName $fullName -Force:$Force -ErrorAction Continue
              if ( $? ) {
                Write-Verbose "Finished copying '$tempName' to '$fullName'"
              }
              Remove-Item $tempName
              if ( $? ) {
                Write-Verbose "Removed file '$tempName'"
              }
            }
            catch [Management.Automation.MethodInvocationException] {
              Write-Error $Error[0]
            }
          }
        }
      }
      else {
        Write-Error "The item '$path' must be a file in the file system." -Category InvalidType
      }
    }
  }
}

process {
  foreach ( $PathItem in $Path ) {
    if ( $Overwrite ) {
      if ( $PSCmdlet.ShouldProcess("'$PathItem'","Overwrite file") ) {
        Update-FileText $PathItem
      }
    }
    else {
      Update-FileText $PathItem
    }
  }
}

Also available as a gist on Github.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

This is a helper function for mustacheJS, without pre-formatting the data and instead getting it during render.

var data = {
    valueFromMap: function() {
        return function(text, render) {
            // "this" will be an object with map key property
            // text will be color that we have between the mustache-tags
            // in the template
            // render is the function that mustache gives us

            // still need to loop since we have no idea what the key is
            // but there will only be one
            for ( var key in this) {
                if (this.hasOwnProperty(key)) {
                    return render(this[key][text]);
                }
            }
        };
    },

    list: {
        blueHorse: {
            color: 'blue'
        },

        redHorse: {
            color: 'red'
        }
    }
};

Template:

{{#list}}
    {{#.}}<span>color: {{#valueFromMap}}color{{/valueFromMap}}</span> <br/>{{/.}}
{{/list}}

Outputs:

color: blue
color: red

(order might be random - it's a map) This might be useful if you know the map element that you want. Just watch out for falsy values.

Simple http post example in Objective-C?

You can do using two options:

Using NSURLConnection:

NSURL* URL = [NSURL URLWithString:@"http://www.example.com/path"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
request.HTTPMethod = @"POST";
// Form URL-Encoded Body

NSDictionary* bodyParameters = @{
    @"username": @"reallyrambody",
    @"password": @"123456"
};
request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];

// Connection

NSURLConnection* connection = [NSURLConnection connectionWithRequest:request delegate:nil];
[connection start];

/*
 * Utils: Add this section before your class implementation
 */

/**
 This creates a new query parameters string from the given NSDictionary. For
 example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
 string will be @"day=Tuesday&month=January".
 @param queryParameters The input dictionary.
 @return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
            [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
            [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
        ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

/**
 Creates a new URL by adding the given query parameters.
 @param URL The input URL.
 @param queryParameters The query parameter dictionary to add.
 @return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
        [URL absoluteString],
        NSStringFromQueryParameters(queryParameters)
    ];
    return [NSURL URLWithString:URLString];
}

Using NSURLSession

- (void)sendRequest:(id)sender
{
    /* Configure session, choose between:
       * defaultSessionConfiguration
       * ephemeralSessionConfiguration
       * backgroundSessionConfigurationWithIdentifier:
     And set session-wide properties, such as: HTTPAdditionalHeaders,
     HTTPCookieAcceptPolicy, requestCachePolicy or timeoutIntervalForRequest.
     */
    NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

    /* Create session, and optionally set a NSURLSessionDelegate. */
    NSURLSession* session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:nil delegateQueue:nil];

    /* Create the Request:
       Token Duplicate (POST http://www.example.com/path)
     */

    NSURL* URL = [NSURL URLWithString:@"http://www.example.com/path"];
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";

    // Form URL-Encoded Body

    NSDictionary* bodyParameters = @{
        @"username": @"reallyram",
        @"password": @"123456"
    };
    request.HTTPBody = [NSStringFromQueryParameters(bodyParameters) dataUsingEncoding:NSUTF8StringEncoding];

    /* Start a new Task */
    NSURLSessionDataTask* task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error == nil) {
            // Success
            NSLog(@"URL Session Task Succeeded: HTTP %ld", ((NSHTTPURLResponse*)response).statusCode);
        }
        else {
            // Failure
            NSLog(@"URL Session Task Failed: %@", [error localizedDescription]);
        }
    }];
    [task resume];
}

/*
 * Utils: Add this section before your class implementation
 */

/**
 This creates a new query parameters string from the given NSDictionary. For
 example, if the input is @{@"day":@"Tuesday", @"month":@"January"}, the output
 string will be @"day=Tuesday&month=January".
 @param queryParameters The input dictionary.
 @return The created parameters string.
*/
static NSString* NSStringFromQueryParameters(NSDictionary* queryParameters)
{
    NSMutableArray* parts = [NSMutableArray array];
    [queryParameters enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
        NSString *part = [NSString stringWithFormat: @"%@=%@",
            [key stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding],
            [value stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]
        ];
        [parts addObject:part];
    }];
    return [parts componentsJoinedByString: @"&"];
}

/**
 Creates a new URL by adding the given query parameters.
 @param URL The input URL.
 @param queryParameters The query parameter dictionary to add.
 @return A new NSURL.
*/
static NSURL* NSURLByAppendingQueryParameters(NSURL* URL, NSDictionary* queryParameters)
{
    NSString* URLString = [NSString stringWithFormat:@"%@?%@",
        [URL absoluteString],
        NSStringFromQueryParameters(queryParameters)
    ];
    return [NSURL URLWithString:URLString];
}

How should I escape strings in JSON?

Consider Moshi's JsonWriter class. It has a wonderful API and it reduces copying to a minimum, everything can be nicely streamed to a filed, OutputStream, etc.

OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.buffer(Okio.sink(os)));
json.beginObject();
json.name("id").value(getId());
json.name("scores");
json.beginArray();
for (Double score : getScores()) {
  json.value(score);
}
json.endArray();
json.endObject();

If you want the string in hand:

Buffer b = new Buffer(); // okio.Buffer
JsonWriter writer = new JsonWriter(b);
//...
String jsonString = b.readUtf8();

How to force NSLocalizedString to use a specific language

NSLocalizedString() reads the value for the key AppleLanguages from the standard user defaults ([NSUserDefaults standardUserDefaults]). It uses that value to choose an appropriate localization among all existing localizations at runtime. When Apple builds the user defaults dictionary at app launch, they look up the preferred language(s) key in the system preferences and copy the value from there. This also explains for example why changing the language settings in OS X has no effect on running apps, only on apps started thereafter. Once copied, the value is not updated just because the settings change. That's why iOS restarts all apps if you change then language.

However, all values of the user defaults dictionary can be overwritten by command line arguments. See NSUserDefaults documentation on the NSArgumentDomain. This even includes those values that are loaded from the app preferences (.plist) file. This is really good to know if you want to change a value just once for testing.

So if you want to change the language just for testing, you probably don't want to alter your code (if you forget to remove this code later on ...), instead tell Xcode to start your app with a command line parameters (e.g. use Spanish localization):

enter image description here

No need to touch your code at all. Just create different schemes for different languages and you can quickly start the app once in one language and once in another one by just switching the scheme.

How to use npm with ASP.NET Core

Install the Bundler and Minifier into Visual Studio Extensions

Then you create a bundleconfig.json and enter the following like :

// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
 {
    "outputFileName": "wwwroot/js/jquery.min.js",
    "inputFiles": [
      "node_modules/jquery/dist/jquery.js"
    ],
    // Optionally specify minification options
    "minify": {
      "enabled": true,
      "renameLocals": false
    },
    // Optionally generate .map file
    "sourceMap": false
  }
]

So the bundler and minifier (gulp based) has access to the source files (which should be excluded from Visual Studio and also excluded from GIT) and puts them into the wwwroot as specified

only side effect every time you save it will run this (but you can set it to run it manually)

Ruby: character to ascii from a string

puts "string".split('').map(&:ord).to_s

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

Splitting on last delimiter in Python string?

I just did this for fun

    >>> s = 'a,b,c,d'
    >>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
    ['a,b,c', 'd']

Caution: Refer to the first comment in below where this answer can go wrong.

Using CSS td width absolute, position

Use table-layout property and the "fixed" value on your table.

table {
   table-layout: fixed;
   width: 300px; /* your desired width */
}

After setting up the entire width of the table, you can now setup the width in % of the td's.

td:nth-child(1), td:nth-child(2) {
   width: 15%;  
}

You can learn more about in on this link: http://www.w3schools.com/cssref/pr_tab_table-layout.asp

How to check if a registry value exists using C#?

Of course, "Fagner Antunes Dornelles" is correct in its answer. But it seems to me that it is worth checking the registry branch itself in addition, or be sure of the part that is exactly there.

For example ("dirty hack"), i need to establish trust in the RMS infrastructure, otherwise when i open Word or Excel documents, i will be prompted for "Active Directory Rights Management Services". Here's how i can add remote trust to me servers in the enterprise infrastructure.

foreach (var strServer in listServer)
{
    try
    {
        RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC\\{strServer}", false);
        if (regCurrentUser == null)
            throw new ApplicationException("Not found registry SubKey ...");
        if (regCurrentUser.GetValueNames().Contains("UserConsent") == false)
            throw new ApplicationException("Not found value in SubKey ...");
    }
    catch (ApplicationException appEx)
    {
        Console.WriteLine(appEx);
        try
        {
            RegistryKey regCurrentUser = Registry.CurrentUser.OpenSubKey($"Software\\Classes\\Local Settings\\Software\\Microsoft\\MSIPC", true);
            RegistryKey newKey = regCurrentUser.CreateSubKey(strServer, true);
            newKey.SetValue("UserConsent", 1, RegistryValueKind.DWord);
        }
        catch(Exception ex)
        {
            Console.WriteLine($"{ex} Pipec kakoito ...");
        }
    }
}

What is the difference between LATERAL and a subquery in PostgreSQL?

Database table

Having the following blog database table storing the blogs hosted by our platform:

Blog table

And, we have two blogs currently hosted:

id created_on title url
1 2013-09-30 Vlad Mihalcea's Blog https://vladmihalcea.com
2 2017-01-22 Hypersistence https://hypersistence.io

Getting our report without using the SQL LATERAL JOIN

We need to build a report that extracts the following data from the blog table:

  • the blog id
  • the blog age, in years
  • the date for the next blog anniversary
  • the number of days remaining until the next anniversary.

If you're using PostgreSQL, then you have to execute the following SQL query:

SELECT
  b.id as blog_id,
  extract(
    YEAR FROM age(now(), b.created_on)
  ) AS age_in_years,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (
      extract(YEAR FROM age(now(), b.created_on)) + 1
    ) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
ORDER BY blog_id

As you can see, the age_in_years has to be defined three times because you need it when calculating the next_anniversary and days_to_next_anniversary values.

And, that's exactly where LATERAL JOIN can help us.

Getting the report using the SQL LATERAL JOIN

The following relational database systems support the LATERAL JOIN syntax:

  • Oracle since 12c
  • PostgreSQL since 9.3
  • MySQL since 8.0.14

SQL Server can emulate the LATERAL JOIN using CROSS APPLY and OUTER APPLY.

LATERAL JOIN allows us to reuse the age_in_years value and just pass it further when calculating the next_anniversary and days_to_next_anniversary values.

The previous query can be rewritten to use the LATERAL JOIN, as follows:

SELECT
  b.id as blog_id,
  age_in_years,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) AS next_anniversary,
  date(
    created_on + (age_in_years + 1) * interval '1 year'
  ) - date(now()) AS days_to_next_anniversary
FROM blog b
CROSS JOIN LATERAL (
  SELECT
    cast(
      extract(YEAR FROM age(now(), b.created_on)) AS int
    ) AS age_in_years
) AS t
ORDER BY blog_id

And, the age_in_years value can be calculated one and reused for the next_anniversary and days_to_next_anniversary computations:

blog_id age_in_years next_anniversary days_to_next_anniversary
1 7 2021-09-30 295
2 3 2021-01-22 44

Much better, right?

The age_in_years is calculated for every record of the blog table. So, it works like a correlated subquery, but the subquery records are joined with the primary table and, for this reason, we can reference the columns produced by the subquery.

Specify a Root Path of your HTML directory for script links?

I recommend using the HTML <base> element:

<head>
    <base href="http://www.example.com/default/">
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
</head>

In this example, the stylesheet is located in http://www.example.com/default/style.css, the script in http://www.example.com/default/script.js. The advantage of <base> over / is that it is more flexible. Your whole website can be located in a subdirectory of a domain, and you can easily alter the default directory of your website.

Disabling swap files creation in vim

I found the answer here:

vim -n <file>

opens file without swapfile.

In addition:

set dir=/tmp

in .vimrc creates the swapfiles in /tmp.

Find intersection of two nested lists?

The & operator takes the intersection of two sets.

{1, 2, 3} & {2, 3, 4}
Out[1]: {2, 3}

Calculate RSA key fingerprint

Run the following command to retrieve the SHA256 fingerprint of your SSH key (-l means "list" instead of create a new key, -f means "filename"):

$ ssh-keygen -lf /path/to/ssh/key

So for example, on my machine the command I ran was (using RSA public key):

$ ssh-keygen -lf ~/.ssh/id_rsa.pub
2048 00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff /Users/username/.ssh/id_rsa.pub (RSA)

To get the GitHub (MD5) fingerprint format with newer versions of ssh-keygen, run:

$ ssh-keygen -E md5 -lf <fileName>

Bonus information:

ssh-keygen -lf also works on known_hosts and authorized_keys files.

To find most public keys on Linux/Unix/OS X systems, run

$ find /etc/ssh /home/*/.ssh /Users/*/.ssh -name '*.pub' -o -name 'authorized_keys' -o -name 'known_hosts'

(If you want to see inside other users' homedirs, you'll have to be root or sudo.)

The ssh-add -l is very similar, but lists the fingerprints of keys added to your agent. (OS X users take note that magic passwordless SSH via Keychain is not the same as using ssh-agent.)

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

In case someone missed the obvious; note that if you build a GUI application and use
"-subsystem:windows" in the link-args, the application entry is WinMain@16. Not main(). Hence you can use this snippet to call your main():

#include <stdlib.h>
#include <windows.h>

#ifdef __GNUC__
#define _stdcall  __attribute__((stdcall))
#endif

int _stdcall
WinMain (struct HINSTANCE__ *hInstance,
         struct HINSTANCE__ *hPrevInstance,
         char               *lpszCmdLine,
         int                 nCmdShow)
{
  return main (__argc, __argv);
}

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

How to disable a particular checkstyle rule for a particular line of code?

What also works well is the SuppressWithNearbyCommentFilter which uses individual comments to suppress audit events.

For example

// CHECKSTYLE IGNORE check FOR NEXT 1 LINES
public void onClick(View view) { ... }

To configure a filter so that CHECKSTYLE IGNORE check FOR NEXT var LINES avoids triggering any audits for the given check for the current line and the next var lines (for a total of var+1 lines):

<module name="SuppressWithNearbyCommentFilter">
    <property name="commentFormat" value="CHECKSTYLE IGNORE (\w+) FOR NEXT (\d+) LINES"/>
    <property name="checkFormat" value="$1"/>
    <property name="influenceFormat" value="$2"/>
</module>

http://checkstyle.sourceforge.net/config.html

How to drop a PostgreSQL database if there are active connections to it?

PostgreSQL 9.2 and above:

SELECT pg_terminate_backend(pid)FROM pg_stat_activity WHERE datname = 'YOUR_DATABASE_NAME_HERE'

iOS start Background Thread

Swift 2.x answer:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        self.getResultSetFromDB(docids)
    }

Convert to/from DateTime and Time in Ruby

While making such conversions one should take into consideration the behavior of timezones while converting from one object to the other. I found some good notes and examples in this stackoverflow post.

Custom "confirm" dialog in JavaScript?

SweetAlert

You should take a look at SweetAlert as an option to save some work. It's beautiful from the default state and is highly customizable.

Confirm Example

sweetAlert(
  {
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",   
    showCancelButton: true,   
    confirmButtonColor: "#DD6B55",
    confirmButtonText: "Yes, delete it!"
  }, 
  deleteIt()
);

Sample Alert

Case statement in MySQL

Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

How to determine whether code is running in DEBUG / RELEASE build?

Apple already includes a DEBUG flag in debug builds, so you don't need to define your own.

You might also want to consider just redefining NSLog to a null operation when not in DEBUG mode, that way your code will be more portable and you can just use regular NSLog statements:

//put this in prefix.pch

#ifndef DEBUG
#undef NSLog
#define NSLog(args, ...)
#endif

Objective-C: Reading a file line by line

Use this script, it works great:

NSString *path = @"/Users/xxx/Desktop/names.txt";
NSError *error;
NSString *stringFromFileAtPath = [NSString stringWithContentsOfFile: path
                                                           encoding: NSUTF8StringEncoding
                                                              error: &error];
if (stringFromFileAtPath == nil) {
    NSLog(@"Error reading file at %@\n%@", path, [error localizedFailureReason]);
}
NSLog(@"Contents:%@", stringFromFileAtPath);

Get real path from URI, Android KitKat new storage access framework

Note: This answer addresses part of the problem. For a complete solution (in the form of a library), look at Paul Burke's answer.

You could use the URI to obtain document id, and then query either MediaStore.Images.Media.EXTERNAL_CONTENT_URI or MediaStore.Images.Media.INTERNAL_CONTENT_URI (depending on the SD card situation).

To get document id:

// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uriThatYouCurrentlyHave);

// Split at colon, use second item in the array
String id = wholeID.split(":")[1];

String[] column = { MediaStore.Images.Media.DATA };     

// where id is equal to             
String sel = MediaStore.Images.Media._ID + "=?";

Cursor cursor = getContentResolver().
                          query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, 
                          column, sel, new String[]{ id }, null);

String filePath = "";

int columnIndex = cursor.getColumnIndex(column[0]);

if (cursor.moveToFirst()) {
    filePath = cursor.getString(columnIndex);
}   

cursor.close();

Reference: I'm not able to find the post that this solution is taken from. I wanted to ask the original poster to contribute here. Will look some more tonight.

Difference between FetchType LAZY and EAGER in Java Persistence API?

EAGER loading of collections means that they are fetched fully at the time their parent is fetched. So if you have Course and it has List<Student>, all the students are fetched from the database at the time the Course is fetched.

LAZY on the other hand means that the contents of the List are fetched only when you try to access them. For example, by calling course.getStudents().iterator(). Calling any access method on the List will initiate a call to the database to retrieve the elements. This is implemented by creating a Proxy around the List (or Set). So for your lazy collections, the concrete types are not ArrayList and HashSet, but PersistentSet and PersistentList (or PersistentBag)

Can I get image from canvas element and use it in img src tag?

Corrected the Fiddle - updated shows the Image duplicated into the Canvas...

And right click can be saved as a .PNG

http://jsfiddle.net/gfyWK/67/

<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>

Plus the JS on the fiddle page...

Cheers Si

Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....

Check a collection size with JSTL

You can use like this

${fn:length(numList)}

Call a global variable inside module

If it is something that you reference but never mutate, then use const:

declare const bootbox;

How to stop a setTimeout loop?

I know this is an old question, I'd like to post my approach anyway. This way you don't have to handle the 0 trick that T. J. Crowder expained.

var keepGoing = true;

function myLoop() {
    // ... Do something ...

    if(keepGoing) {
        setTimeout(myLoop, 1000);
    }
}

function startLoop() {
    keepGoing = true;
    myLoop();
}

function stopLoop() {
    keepGoing = false;
}

How does the Spring @ResponseBody annotation work?

The first basic thing to understand is the difference in architectures.

One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:

Browser <---> Controller <---> Model
               |      |
               +-View-+

The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.

On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.

But when we use @ResponseBody, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use

@RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)

to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces to MediaType.APPLICATION_XML_VALUE and I believe you need to configure the HttpMessageConverter for JAXB. As for the JSON MappingJacksonHttpMessageConverter configured, when we have Jackson on the classpath.

I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.

How can I take a screenshot with Selenium WebDriver?

Java

I could not get the accepted answer to work, but as per the current WebDriver documentation, the following worked fine for me with Java 7 on OS X v10.9 (Mavericks):

import java.io.File;
import java.net.URL;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

   public void myTest() throws Exception {
       WebDriver driver = new RemoteWebDriver(
               new URL("http://localhost:4444/wd/hub"),
               DesiredCapabilities.firefox());

       driver.get("http://www.google.com");

       // RemoteWebDriver does not implement the TakesScreenshot class
       // if the driver does have the Capabilities to take a screenshot
       // then Augmenter will add the TakesScreenshot methods to the instance
       WebDriver augmentedDriver = new Augmenter().augment(driver);
       File screenshot = ((TakesScreenshot)augmentedDriver).
               getScreenshotAs(OutputType.FILE);
   }
}

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

When your app and the libraries it references exceed 65,536 methods, you encounter a build error that indicates your app has reached the limit of the Android build architecture

To avoid this limitation you have to configure your app for multidex

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in your module-level build.gradle file, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 21 
        multiDexEnabled true
    }
    ...   
}

Else, if your minSdkVersion is set to 20 or lower, then you must use the multidex support library as follows:

1.Modify the module-level build.gradle file to enable multidex and add the multidex library as a dependency, as shown here:

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        multiDexEnabled true
    }
    ...
 }

dependencies {
        implementation 'com.android.support:multidex:1.0.3'
}

2.Depending on whether you override the Application class, perform one of the following:

  • If you do not override the Application class, edit your manifest file to set android:name in the tag as follows:

    <application
        android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
  • Else If you do override the Application class, change it to extend MultiDexApplication (if possible) as follows:

   public class MyApplication extends MultiDexApplication { ... }
  • Else you do override the Application class but it's not possible to change the base class, then you can instead override the attachBaseContext() method and call MultiDex.install(this) to enable multidex:

   public class MyApplication extends SomeOtherApplication {
     @Override
     protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
     }
   }

Best way to specify whitespace in a String.Split operation

If repeating the same code is the issue, write an extension method on the String class that encapsulates the splitting logic.

Tab key == 4 spaces and auto-indent after curly braces in Vim

The auto-indent is based on the current syntax mode. I know that if you are editing Foo.java, then entering a { and hitting Enter indents the following line.

As for tabs, there are two settings. Within Vim, type a colon and then "set tabstop=4" which will set the tabs to display as four spaces. Hit colon again and type "set expandtab" which will insert spaces for tabs.

You can put these settings in a .vimrc (or _vimrc on Windows) in your home directory, so you only have to type them once.

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

I am now using Google Apps (for Email) and Heroku as web server. I am using Google Apps 301 Permanent Redirect feature to redirect the naked domain to WWW.your_domain.com

You can find the step-by-step instructions here https://stackoverflow.com/a/20115583/1440255

expected assignment or function call: no-unused-expressions ReactJS

The error - "Expected an assignment or function call and instead saw an expression no-unused-expressions" comes when we use curly braces i.e {} to return an object literal expression. In such case we can fix it with 2 options

  1. Use the parentheses i.e ()
  2. Use return statement with curly braces i.e {}

Example :

const items = ["Test1", "Test2", "Test3", "Test4"];
console.log(articles.map(item => { `this is ${item}` })); // wrong
console.log(items.map(item => (`this is ${item}`))); // Option1
console.log(items.map(item => { return `this is ${item}` })); // Option2

CSS div 100% height

try setting the body style to:

body { position:relative;}

it worked for me

Javascript-Setting background image of a DIV via a function and function parameter

You need to concatenate your string.

document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';

The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.

I would even suggest creating the string separate:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    var urlString = 'url(buttons/' + imagePrefix + '.png)';
    document.getElementById(tabName).style.backgroundImage =  urlString;
}

As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html

Storing C++ template function definitions in a .CPP file

There is nothing wrong with the example you have given. But i must say i believe it's not efficient to store function definitions in a cpp file. I only understand the need to separate the function's declaration and definition.

When used together with explicit class instantiation, the Boost Concept Check Library (BCCL) can help you generate template function code in cpp files.

Case insensitive string as HashMap key

Subclass HashMap and create a version that lower-cases the key on put and get (and probably the other key-oriented methods).

Or composite a HashMap into the new class and delegate everything to the map, but translate the keys.

If you need to keep the original key you could either maintain dual maps, or store the original key along with the value.

Run Excel Macro from Outside Excel Using VBScript From Command Line

Hi used this thread to get the solution , then i would like to share what i did just in case someone could use it.

What i wanted was to call a macro that change some cells and erase some rows, but i needed for more than 1500 excels( approximately spent 3 minuts for each file)

Mainly problem: -when calling the macro from vbe , i got the same problem, it was imposible to call the macro from PERSONAL.XLSB, when the script oppened the excel didnt execute personal.xlsb and wasnt any option in the macro window

I solved this by keeping open one excel file with the macro loaded(a.xlsm)(before executing the script)

Then i call the macro from the excel oppened by the script

    Option Explicit
    Dim xl
    Dim counter

   counter =10



  Do

  counter = counter + 1

  Set xl = GetObject(, "Excel.Application")
  xl.Application.Workbooks.open "C:\pruebas\macroxavi\IA_030-08-026" & counter & ".xlsx"
  xl.Application.Visible = True
  xl.Application.run "'a.xlsm'!eraserow" 
  Set xl = Nothing


  Loop Until counter = 517

  WScript.Echo "Finished."
  WScript.Quit

Swap two variables without using a temporary variable

First of all, swapping without a temporary variable in a language as C# is a very bad idea.

But for the sake of answer, you can use this code:

startAngle = startAngle + stopAngle;
stopAngle = startAngle - stopAngle;
startAngle = startAngle - stopAngle;

Problems can however occur with rounding off if the two numbers differ largely. This is due to the nature of floating point numbers.

If you want to hide the temporary variable, you can use a utility method:

public static class Foo {

    public static void Swap<T> (ref T lhs, ref T rhs) {
        T temp = lhs;
        lhs = rhs;
        rhs = temp;
    }
}

Python functions call by reference

Technically python do not pass arguments by value: all by reference. But ... since python has two types of objects: immutable and mutable, here is what happens:

  • Immutable arguments are effectively passed by value: string, integer, tuple are all immutable object types. While they are technically "passed by reference" (like all parameters), since you can't change them in-place inside the function it looks/behaves as if it is passed by value.

  • Mutable arguments are effectively passed by reference: lists or dictionaries are passed by its pointers. Any in-place change inside the function like (append or del) will affect the original object.

This is how Python is designed: no copies and all are passed by reference. You can explicitly pass a copy.

def sort(array):
    # do sort
    return array

data = [1, 2, 3]
sort(data[:]) # here you passed a copy

Last point I would like to mention which is a function has its own scope.

def do_any_stuff_to_these_objects(a, b): 
    a = a * 2 
    del b['last_name']

number = 1 # immutable
hashmap = {'first_name' : 'john', 'last_name': 'legend'} # mutable
do_any_stuff_to_these_objects(number, hashmap) 
print(number) # 1 , oh  it should be 2 ! no a is changed inisde the function scope
print(hashmap) # {'first_name': 'john'}

What is the best way to redirect a page using React Router?

One of the simplest way: use Link as follows:

import { Link } from 'react-router-dom';

<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>

If we want to cover the whole div section as link:

 <div>
     <Card as={Link} to={'path-name'}>
         .... 
           card content here
         ....
     </Card>
 </div>

Class method differences in Python: bound, unbound and static

The second one won't work because when you call it like that python internally tries to call it with the a_test instance as the first argument, but your method_two doesn't accept any arguments, so it wont work, you'll get a runtime error. If you want the equivalent of a static method you can use a class method. There's much less need for class methods in Python than static methods in languages like Java or C#. Most often the best solution is to use a method in the module, outside a class definition, those work more efficiently than class methods.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.

We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.

We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.

When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

Pythonic way of checking if a condition holds for any element of a list

Python has a built in any() function for exactly this purpose.

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

How to pull remote branch from somebody else's repo

GitHub has a new option relative to the preceding answers, just copy/paste the command lines from the PR:

  1. Scroll to the bottom of the PR to see the Merge or Squash and merge button
  2. Click the link on the right: view command line instructions
  3. Press the Copy icon to the right of Step 1
  4. Paste the commands in your terminal

Initialize array of strings

This example program illustrates initialization of an array of C strings.

#include <stdio.h>

const char * array[] = {
    "First entry",
    "Second entry",
    "Third entry",
};

#define n_array (sizeof (array) / sizeof (const char *))

int main ()
{
    int i;

    for (i = 0; i < n_array; i++) {
        printf ("%d: %s\n", i, array[i]);
    }
    return 0;
}

It prints out the following:

0: First entry
1: Second entry
2: Third entry

What reference do I need to use Microsoft.Office.Interop.Excel in .NET?

I found it located under Assemblies->Extensions in VS2013.

Add Reference

Angles between two n-dimensional vectors in Python

import math

def dotproduct(v1, v2):
  return sum((a*b) for a, b in zip(v1, v2))

def length(v):
  return math.sqrt(dotproduct(v, v))

def angle(v1, v2):
  return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))

Note: this will fail when the vectors have either the same or the opposite direction. The correct implementation is here: https://stackoverflow.com/a/13849249/71522

String, StringBuffer, and StringBuilder

Mutability Difference:

String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.

Thread-Safety Difference:

The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

Situations:

  • If your string is not going to change use a String class because a String object is immutable.
  • If your string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
  • If your string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous so you have thread-safety.

nil detection in Go

The language spec mentions comparison operators' behaviors:

comparison operators

In any comparison, the first operand must be assignable to the type of the second operand, or vice versa.


Assignability

A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:

  • x's type is identical to T.
  • x's type V and T have identical underlying types and at least one of V or T is not a named type.
  • T is an interface type and x implements T.
  • x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
  • x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
  • x is an untyped constant representable by a value of type T.

Android LinearLayout Gradient Background

With Kotlin you can do that in just 2 lines

Change color values in the array

                  val gradientDrawable = GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM,
                        intArrayOf(Color.parseColor("#008000"),
                                   Color.parseColor("#ADFF2F"))
                    );
                    gradientDrawable.cornerRadius = 0f;

                   //Set Gradient
                   linearLayout.setBackground(gradientDrawable);

Result

enter image description here

Java 8 Lambda Stream forEach with multiple statements

Forgot to relate to the first code snippet. I wouldn't use forEach at all. Since you are collecting the elements of the Stream into a List, it would make more sense to end the Stream processing with collect. Then you would need peek in order to set the ID.

List<Entry> updatedEntries = 
    entryList.stream()
             .peek(e -> e.setTempId(tempId))
             .collect (Collectors.toList());

For the second snippet, forEach can execute multiple expressions, just like any lambda expression can :

entryList.forEach(entry -> {
  if(entry.getA() == null){
    printA();
  }
  if(entry.getB() == null){
    printB();
  }
  if(entry.getC() == null){
    printC();
  }
});

However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null) if you do.

Returning IEnumerable<T> vs. IQueryable<T>

The top answer is good but it doesn't mention expression trees which explain "how" the two interfaces differ. Basically, there are two identical sets of LINQ extensions. Where(), Sum(), Count(), FirstOrDefault(), etc all have two versions: one that accepts functions and one that accepts expressions.

  • The IEnumerable version signature is: Where(Func<Customer, bool> predicate)

  • The IQueryable version signature is: Where(Expression<Func<Customer, bool>> predicate)

You've probably been using both of those without realizing it because both are called using identical syntax:

e.g. Where(x => x.City == "<City>") works on both IEnumerable and IQueryable

  • When using Where() on an IEnumerable collection, the compiler passes a compiled function to Where()

  • When using Where() on an IQueryable collection, the compiler passes an expression tree to Where(). An expression tree is like the reflection system but for code. The compiler converts your code into a data structure that describes what your code does in a format that's easily digestible.

Why bother with this expression tree thing? I just want Where() to filter my data. The main reason is that both the EF and Linq2SQL ORMs can convert expression trees directly into SQL where your code will execute much faster.

Oh, that sounds like a free performance boost, should I use AsQueryable() all over the place in that case? No, IQueryable is only useful if the underlying data provider can do something with it. Converting something like a regular List to IQueryable will not give you any benefit.

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

How to make a JFrame button open another JFrame class in Netbeans?

new SecondForm().setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Splitting strings in PHP and get last part

As has been mentioned by others, if you don't assign the result of explode() to a variable, you get the message:

E_STRICT: Strict standards: Only variables should be passed by reference

The correct way is:

$words = explode('-', 'hello-world-123');
$id = array_pop($words); // 123
$slug = implode('-', $words); // hello-world

Possible reason for NGINX 499 error codes

I encountered this issue and the cause was due to Kaspersky Protection plugin on the browser. If you are encountering this, try to disable your plugins and see if that fixes your issue.

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

How to convert OutputStream to InputStream?

If you want to make an OutputStream from an InputStream there is one basic problem. A method writing to an OutputStream blocks until it is done. So the result is available when the writing method is finished. This has 2 consequences:

  1. If you use only one thread, you need to wait until everything is written (so you need to store the stream's data in memory or disk).
  2. If you want to access the data before it is finished, you need a second thread.

Variant 1 can be implemented using byte arrays or filed. Variant 1 can be implemented using pipies (either directly or with extra abstraction - e.g. RingBuffer or the google lib from the other comment).

Indeed with standard java there is no other way to solve the problem. Each solution is an implementataion of one of these.

There is one concept called "continuation" (see wikipedia for details). In this case basically this means:

  • there is a special output stream that expects a certain amount of data
  • if the ammount is reached, the stream gives control to it's counterpart which is a special input stream
  • the input stream makes the amount of data available until it is read, after that, it passes back the control to the output stream

While some languages have this concept built in, for java you need some "magic". For example "commons-javaflow" from apache implements such for java. The disadvantage is that this requires some special bytecode modifications at build time. So it would make sense to put all the stuff in an extra library whith custom build scripts.

IIS AppPoolIdentity and file system write access permissions

  1. Right click on folder.

  2. Click Properties

  3. Click Security Tab. You will see something like this:

enter image description here

  1. Click "Edit..." button in above screen. You will see something like this:

enter image description here

  1. Click "Add..." button in above screen. You will see something like this:

enter image description here

  1. Click "Locations..." button in above screen. You will see something like this. Now, go to the very of top of this tree structure and select your computer name, then click OK.

enter image description here

  1. Now type "iis apppool\your_apppool_name" and click "Check Names" button. If the apppool exists, you will see your apppool name in the textbox with underline in it. Click OK button.

enter image description here

  1. Check/uncheck whatever access you need to grant to the account

  2. Click Apply button and then OK.

How do I change the default library path for R packages

See help(Startup) and help(.libPaths) as you have several possibilities where this may have gotten set. Among them are

  • setting R_LIBS_USER
  • assigning .libPaths() in .Rprofile or Rprofile.site

and more.

In this particular case you need to go backwards and unset whereever \\\\The library/path/I/don't/want is set.

To otherwise ignore it you need to override it use explicitly i.e. via

library("somePackage", lib.loc=.libPaths()[-1])

when loading a package.

How do I flush the cin buffer?

I have found two solutions to this.

The first, and simplest, is to use std::getline() for example:

std::getline(std::cin, yourString);

... that will discard the input stream when it gets to a new-line. Read more about this function here.

Another option that directly discards the stream is this...

#include <limits>
// Possibly some other code here
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');

Good luck!

counting the number of lines in a text file

with for-loop:

std::ifstream myFile;
std::string line;
int lines;

myFile.open(path);

for(lines = 0; std::getline(myFile,line); lines++);

std::cout << lines << std::endl;

Get total of Pandas column

You should use sum:

Total = df['MyColumn'].sum()
print (Total)
319

Then you use loc with Series, in that case the index should be set as the same as the specific column you need to sum:

df.loc['Total'] = pd.Series(df['MyColumn'].sum(), index = ['MyColumn'])
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

because if you pass scalar, the values of all rows will be filled:

df.loc['Total'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A        84   13.0   69.0
1        B        76   77.0  127.0
2        C        28   69.0   16.0
3        D        28   28.0   31.0
4        E        19   20.0   85.0
5        F        84  193.0   70.0
Total  319       319  319.0  319.0

Two other solutions are with at, and ix see the applications below:

df.at['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

df.ix['Total', 'MyColumn'] = df['MyColumn'].sum()
print (df)
         X  MyColumn      Y      Z
0        A      84.0   13.0   69.0
1        B      76.0   77.0  127.0
2        C      28.0   69.0   16.0
3        D      28.0   28.0   31.0
4        E      19.0   20.0   85.0
5        F      84.0  193.0   70.0
Total  NaN     319.0    NaN    NaN

Note: Since Pandas v0.20, ix has been deprecated. Use loc or iloc instead.

How to check if $_GET is empty?

Easy.

if (empty($_GET)) {
    // $_GET is empty
}

How to send POST in angularjs with multiple params?

Client Side

Data needs to be grouped in an object array as payload - Indata:

var Indata = {'product': $scope.product, 'product2': $scope.product2 };

Pass the payload through $http.post as the second argument:

$http.post("http://localhost:53263/api/Products/", Indata).then(function (data, status, headers, config) { 
    alert("success"); 
},function (data, status, headers, config) { 
    alert("error"); 
});

Server Side

Create a Data Transfer Object(DTO) class as such:

public class ExampleRequest {
   public string product {get; set;};
   public string product2 {get; set;};
}

The class below accepts DTO with the same property names which the payload is carrying.

public void Post(ExampleRequest request)
{
    var productRepository = new ProductRepository();
    var newProduct = productRepository.Save(request.product);
}

In above class, request contains 2 properties with values of product and product2

Replace only text inside a div using jquery

You need to set the text to something other than an empty string. In addition, the .html() function should do it while preserving the HTML structure of the div.

$('#one').html($('#one').html().replace('text','replace'));

Entity Framework .Remove() vs. .DeleteObject()

If you really want to use Deleted, you'd have to make your foreign keys nullable, but then you'd end up with orphaned records (which is one of the main reasons you shouldn't be doing that in the first place). So just use Remove()

ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

A thing worth noting is that setting .State = EntityState.Deleted does not trigger automatically detected change. (archive)

CSS @media print issues with background-color;

Despite !important usage being generally frowned upon, this is the offending code in bootstrap.css which prevents table rows from being printed with background-color.

.table td,
.table th {
    background-color: #fff !important;
}

Let's assume you are trying to style the following HTML:

<table class="table">
    <tr class="highlighted">
      <td>Name</td>
      <td>School</td>
      <td>Height</td>
      <td>Weight</td>
    </tr>
</table>

To override this CSS, place the following (more specific) rule in your stylesheet:

@media print {
    table tr.highlighted > td {
        background-color: rgba(247, 202, 24, 0.3) !important;
    }
}

This works because the rule is more specific than the bootstrap default.

Check if object value exists within a Javascript array of objects and if not add a new object to array

Accepted answer can also be written in following way using arrow function on .some

 function checkAndAdd(name) {
     var id = arr.length + 1;
     var found = arr.some((el) => {
           return el.username === name;
     });
     if (!found) { arr.push({ id: id, username: name }); }
 }

What generates the "text file busy" message in Unix?

It's a while since I've seen that message, but it used to be prevalent in System V R3 or thereabouts a good couple of decades ago. Back then, it meant that you could not change a program executable while it was running.

For example, I was building a make workalike called rmk, and after a while it was self-maintaining. I would run the development version and have it build a new version. To get it to work, it was necessary to use the workaround:

gcc -g -Wall -o rmk1 main.o -L. -lrmk -L/Users/jleffler/lib/64 -ljl
if [ -f rmk ] ; then mv rmk rmk2 ; else true; fi ; mv rmk1 rmk

So, to avoid problems with the 'text file busy', the build created a new file rmk1, then moved the old rmk to rmk2 (rename wasn't a problem; unlink was), and then moved the newly built rmk1 to rmk.

I haven't seen the error on a modern system in quite a while...but I don't all that often have programs rebuilding themselves.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

SimpleDateFormat and locale based format string

Java8

 import java.time.format.DateTimeFormatter;         
 myDate.format(DateTimeFormatter.ofPattern("dd-MMM-YYYY",new Locale("ar")))

How to prevent Browser cache on Angular 2 site?

You can control client cache with HTTP headers. This works in any web framework.

You can set the directives these headers to have fine grained control over how and when to enable|disable cache:

  • Cache-Control
  • Surrogate-Control
  • Expires
  • ETag (very good one)
  • Pragma (if you want to support old browsers)

Good caching is good, but very complex, in all computer systems. Take a look at https://helmetjs.github.io/docs/nocache/#the-headers for more information.

Regular expression: find spaces (tabs/space) but not newlines

Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000) is not included in \s for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000 with \u0020), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000].

If you're using Perl or PCRE, you have the option of using the \h shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.

However, this \h shorthand has not been implemented for .NET and C#, as best I've been able to tell.

Using an HTML button to call a JavaScript function

SIMPLE ANSWER:

   onclick="functionName(ID.value);

Where ID is the ID of the input field.

Android toolbar center title and custom font

No one has mentioned this, but there are some attributes for Toolbar:

app:titleTextColor for setting the title text color

app:titleTextAppearance for setting the title text appearance

app:titleMargin for setting the margin

And there are other specific-side margins such as marginStart, etc.

Why does one use dependency injection?

Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH environment variable (or other language equivalent, like PYTHONPATH, LD_LIBRARY_PATH) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like

var logger = new Logger() //sane, simple code

And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.

No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.

P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.

Remove a character at a certain position in a string - javascript

var str = 'Hello World',
    i = 3,
    result = str.substr(0, i-1)+str.substring(i);

alert(result);

Value of i should not be less then 1.

How to remove default mouse-over effect on WPF buttons?

Using a template trigger:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="White"></Setter>
    ...
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="White"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

click command in selenium webdriver does not work

This is a long standing issue with chromedriver(still present in 2020).

In Chrome I changed from a zoom of 90% to 100% and that solved the problem. ref

I find TheLifeOfSteve's answer more reliable.

Border around each cell in a range

Here's another way

Sub testborder()

    Dim rRng As Range

    Set rRng = Sheet1.Range("B2:D5")

    'Clear existing
    rRng.Borders.LineStyle = xlNone

    'Apply new borders
    rRng.BorderAround xlContinuous
    rRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
    rRng.Borders(xlInsideVertical).LineStyle = xlContinuous

End Sub

Most efficient way to create a zero filled JavaScript array?

As of ECMAScript2016, there is one clear choice for large arrays.

Since this answer still shows up near the top on google searches, here's an answer for 2017.

Here's a current jsbench with a few dozen popular methods, including many proposed up to now on this question. If you find a better method please add, fork and share.

I want to note that there is no true most efficient way to create an arbitrary length zero filled array. You can optimize for speed, or for clarity and maintainability - either can be considered the more efficient choice depending on the needs of the project.

When optimizing for speed, you want to: create the array using literal syntax; set the length, initialize iterating variable, and iterate through the array using a while loop. Here's an example.

_x000D_
_x000D_
const arr = [];_x000D_
arr.length = 120000;_x000D_
let i = 0;_x000D_
while (i < 120000) {_x000D_
  arr[i] = 0;_x000D_
  i++;_x000D_
}
_x000D_
_x000D_
_x000D_

Another possible implementation would be:

(arr = []).length = n;
let i = 0;
while (i < n) {
    arr[i] = 0;
    i++;
}

But I strongly discourage using this second implantation in practice as it's less clear and doesn't allow you to maintain block scoping on your array variable.

These are significantly faster than filling with a for loop, and about 90% faster than the standard method of

const arr = Array(n).fill(0);

But this fill method is still the most efficient choice for smaller arrays due to it's clarity, conciseness and maintainability. The performance difference likely won't kill you unless you're making a lot of arrays with lengths on the order of thousands or more.

A few other important notes. Most style guides recommend you no longer use varwithout a very special reason when using ES6 or later. Use const for variables that won't be redefined and let for variables that will. The MDN and Airbnb's Style Guide are great places to go for more information on best practices. The questions wasn't about syntax, but it's important that people new to JS know about these new standards when searching through these reams of old and new answers.

Making a button invisible by clicking another button in HTML

  1. getElementById returns a single object for which you can specify the style.So, the above explanation is correct.

  2. getElementsByTagName returns multiple objects(array of objects and properties) for which we cannot apply the style directly.

Regex to validate date format dd/mm/yyyy

Another answer which validates day (dd) depending upon the month (mm) and the year (yyyy) (i.e., also validates 29th Feb in leap years) and allows years ranging from 0001 to 9999 (0000 in a invalid year according to the Gregorian calendar)

^(?:(?:(?:0[1-9]|[12]\d|3[01])/(?:0[13578]|1[02])|(?:0[1-9]|[12]\d|30)/(?:0[469]|11)|(?:0[1-9]|1\d|2[0-8])/02)/(?!0000)\d{4}|(?:(?:0[1-9]|[12]\d)/02/(?:(?!0000)(?:[02468][048]|[13579][26])00|(?!..00)\d{2}(?:[02468][048]|[13579][26]))))$

How do you get the current page number of a ViewPager for Android?

There is no any method getCurrentItem() in viewpager.i already checked the API

How to convert FileInputStream to InputStream?

InputStream is;

try {
    is = new FileInputStream("c://filename");

    is.close(); 
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

return is;

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

I wrote this in HLSL for our rendering engine, it has no conditions in it:

    float3  HSV2RGB( float3 _HSV )
    {
        _HSV.x = fmod( 100.0 + _HSV.x, 1.0 );                                       // Ensure [0,1[

        float   HueSlice = 6.0 * _HSV.x;                                            // In [0,6[
        float   HueSliceInteger = floor( HueSlice );
        float   HueSliceInterpolant = HueSlice - HueSliceInteger;                   // In [0,1[ for each hue slice

        float3  TempRGB = float3(   _HSV.z * (1.0 - _HSV.y),
                                    _HSV.z * (1.0 - _HSV.y * HueSliceInterpolant),
                                    _HSV.z * (1.0 - _HSV.y * (1.0 - HueSliceInterpolant)) );

        // The idea here to avoid conditions is to notice that the conversion code can be rewritten:
        //    if      ( var_i == 0 ) { R = V         ; G = TempRGB.z ; B = TempRGB.x }
        //    else if ( var_i == 2 ) { R = TempRGB.x ; G = V         ; B = TempRGB.z }
        //    else if ( var_i == 4 ) { R = TempRGB.z ; G = TempRGB.x ; B = V     }
        // 
        //    else if ( var_i == 1 ) { R = TempRGB.y ; G = V         ; B = TempRGB.x }
        //    else if ( var_i == 3 ) { R = TempRGB.x ; G = TempRGB.y ; B = V     }
        //    else if ( var_i == 5 ) { R = V         ; G = TempRGB.x ; B = TempRGB.y }
        //
        // This shows several things:
        //  . A separation between even and odd slices
        //  . If slices (0,2,4) and (1,3,5) can be rewritten as basically being slices (0,1,2) then
        //      the operation simply amounts to performing a "rotate right" on the RGB components
        //  . The base value to rotate is either (V, B, R) for even slices or (G, V, R) for odd slices
        //
        float   IsOddSlice = fmod( HueSliceInteger, 2.0 );                          // 0 if even (slices 0, 2, 4), 1 if odd (slices 1, 3, 5)
        float   ThreeSliceSelector = 0.5 * (HueSliceInteger - IsOddSlice);          // (0, 1, 2) corresponding to slices (0, 2, 4) and (1, 3, 5)

        float3  ScrollingRGBForEvenSlices = float3( _HSV.z, TempRGB.zx );           // (V, Temp Blue, Temp Red) for even slices (0, 2, 4)
        float3  ScrollingRGBForOddSlices = float3( TempRGB.y, _HSV.z, TempRGB.x );  // (Temp Green, V, Temp Red) for odd slices (1, 3, 5)
        float3  ScrollingRGB = lerp( ScrollingRGBForEvenSlices, ScrollingRGBForOddSlices, IsOddSlice );

        float   IsNotFirstSlice = saturate( ThreeSliceSelector );                   // 1 if NOT the first slice (true for slices 1 and 2)
        float   IsNotSecondSlice = saturate( ThreeSliceSelector-1.0 );              // 1 if NOT the first or second slice (true only for slice 2)

        return  lerp( ScrollingRGB.xyz, lerp( ScrollingRGB.zxy, ScrollingRGB.yzx, IsNotSecondSlice ), IsNotFirstSlice );    // Make the RGB rotate right depending on final slice index
    }

REST / SOAP endpoints for a WCF service

If you only want to develop a single web service and have it hosted on many different endpoints (i.e. SOAP + REST, with XML, JSON, CSV, HTML outputes). You should also consider using ServiceStack which I've built for exactly this purpose where every service you develop is automatically available on on both SOAP and REST endpoints out-of-the-box without any configuration required.

The Hello World example shows how to create a simple with service with just (no config required):

public class Hello {
    public string Name { get; set; }
}

public class HelloResponse {
    public string Result { get; set; }
}

public class HelloService : IService
{
    public object Any(Hello request)
    {
        return new HelloResponse { Result = "Hello, " + request.Name };
    }
}

No other configuration is required, and this service is immediately available with REST in:

It also comes in-built with a friendly HTML output (when called with a HTTP client that has Accept:text/html e.g a browser) so you're able to better visualize the output of your services.

Handling different REST verbs are also as trivial, here's a complete REST-service CRUD app in 1 page of C# (less than it would take to configure WCF ;):

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

Exit a Script On Error

Are you looking for exit?

This is the best bash guide around. http://tldp.org/LDP/abs/html/

In context:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
    exit 1 # terminate and indicate error
fi

...

Dropping Unique constraint from MySQL table

The constraint could be removed with syntax:

ALTER TABLE

As of MySQL 8.0.19, ALTER TABLE permits more general (and SQL standard) syntax for dropping and altering existing constraints of any type, where the constraint type is determined from the constraint name: ALTER TABLE tbl_name DROP CONSTRAINT symbol;

Example:

CREATE TABLE tab(id INT, CONSTRAINT unq_tab_id UNIQUE(id));

-- checking constraint name if autogenerated
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME = 'tab';

-- dropping constraint
ALTER TABLE tab DROP CONSTRAINT unq_tab_id;

db<>fiddle demo

Running a command as Administrator using PowerShell?

A number of the answers here are close, but a little more work than needed.

Create a shortcut to your script and configure it to "Run as Administrator":

  • Create the shortcut.
  • Right-click shortcut and open Properties...
  • Edit Target from <script-path> to powershell <script-path>
  • Click Advanced... and enable Run as administrator

How do I validate a date in this format (yyyy-mm-dd) using jquery?

Rearrange the regex to:

/^(\d{4})([\/-])(\d{1,2})\2(\d{1,2})$/

I have done a little more than just rearrange the terms, I've also made it so that it won't accept "broken" dates like yyyy-mm/dd.

After that, you need to adjust your dtMonth etc. variables like so:

dtYear = dtArray[1];
dtMonth = dtArray[3];
dtDay = dtArray[4];

After that, the code should work just fine.

'Framework not found' in Xcode

  1. Delete the framework link from the Xcode project setting.
  2. Move the framework to the Project Folder.
  3. Re-add the framework in the Xcode project setting.
  4. clean the project and re-compile it.

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

Waiting till the async task finish its work

wait until this call is finish its executing

You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.

To get result back in UI Thread start AsyncTask as :

String str_result= new RunInBackGround().execute().get();

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I've updated com.google.gms:google-services from 3.1.1 to 3.2.0 and the warning stopped appearing.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

    classpath 'com.google.gms:google-services:3.2.0'
    }
}

How to create a template function within a class? (C++)

Your guess is the correct one. The only thing you have to remember is that the member function template definition (in addition to the declaration) should be in the header file, not the cpp, though it does not have to be in the body of the class declaration itself.

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

Another scenario where you might see this is when you are attempting to connect to another SQL server from an SSMS session that was already logged-in while you changed your password. Sequence of events might go something like:

  1. RDP to Server-A (your SQL Server), open SSMS and login
  2. RDP to Server-B in the same domain and change your password
  3. Return to RDP session on Server-A and via SSMS attempt to add another DB into an existing AlwaysOn availability group. When connecting to replicas you get "untrusted domain"-login-error

To resolve, simply logoff and log back in

Combining multiple commits before pushing in Git

You can squash (join) commits with an Interactive Rebase. There is a pretty nice YouTube video which shows how to do this on the command line or with SmartGit:

If you are already a SmartGit user then you can select all your outgoing commits (by holding down the Ctrl key) and open the context menu (right click) to squash your commits.

It's very comfortable:

enter image description here

There is also a very nice tutorial from Atlassian which shows how it works:

pandas groupby sort descending order

Other instance of preserving the order or sort by descending:

In [97]: import pandas as pd                                                                                                    

In [98]: df = pd.DataFrame({'name':['A','B','C','A','B','C','A','B','C'],'Year':[2003,2002,2001,2003,2002,2001,2003,2002,2001]})

#### Default groupby operation:
In [99]: for each in df.groupby(["Year"]): print each                                                                           
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)

### order preserved:
In [100]: for each in df.groupby(["Year"], sort=False): print each                                                               
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)

In [106]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"]))                        
Out[106]: 
        Year name
Year             
2003 0  2003    A
     3  2003    A
     6  2003    A
2002 1  2002    B
     4  2002    B
     7  2002    B
2001 2  2001    C
     5  2001    C
     8  2001    C

In [107]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"])).reset_index(drop=True)
Out[107]: 
   Year name
0  2003    A
1  2003    A
2  2003    A
3  2002    B
4  2002    B
5  2002    B
6  2001    C
7  2001    C
8  2001    C

Required maven dependencies for Apache POI to work

Add this dependency to work with Apache POI

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16-beta1</version>
 </dependency>

SEVERE: Unable to create initial connections of pool - tomcat 7 with context.xml file

I use sprint-boot (2.1.1), and mysql version is 8.0.13. I add dependency in pom, solve my problem.

 <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.13</version>
 </dependency>

MySQL Connector/J » 8.0.13 link: https://mvnrepository.com/artifact/mysql/mysql-connector-java/8.0.13
MySQL Connector/J » All the version link: https://mvnrepository.com/artifact/mysql/mysql-connector-java

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

What evaluates to True/False in R?

This is documented on ?logical. The pertinent section of which is:

Details:

     ‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
     in the R language, whereas ‘T’ and ‘F’ are global variables whose
     initial values set to these.  All four are ‘logical(1)’ vectors.

     Logical vectors are coerced to integer vectors in contexts where a
     numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
     ‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.

The second paragraph there explains the behaviour you are seeing, namely 5 == 1L and 5 == 0L respectively, which should both return FALSE, where as 1 == 1L and 0 == 0L should be TRUE for 1 == TRUE and 0 == FALSE respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE and FALSE in R, i.e. what numeric values they take when coerced to numeric.

However, only TRUE is guaranteed to the be TRUE:

> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE

isTRUE is a wrapper for identical(x, TRUE), and from ?isTRUE we note:

Details:
....

     ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
     true if and only if ‘x’ is a length-one logical vector whose only
     element is ‘TRUE’ and which has no attributes (not even names).

So by the same virtue, only FALSE is guaranteed to be exactly equal to FALSE.

> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE

If this concerns you, always use isTRUE() or identical(x, FALSE) to check for equivalence with TRUE and FALSE respectively. == is not doing what you think it is.

JAXB :Need Namespace Prefix to all the elements

To specify more than one namespace to provide prefixes, use something like:

@javax.xml.bind.annotation.XmlSchema(
    namespace = "urn:oecd:ties:cbc:v1", 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
    xmlns ={@XmlNs(prefix="cbc", namespaceURI="urn:oecd:ties:cbc:v1"), 
            @XmlNs(prefix="iso", namespaceURI="urn:oecd:ties:isocbctypes:v1"),
            @XmlNs(prefix="stf", namespaceURI="urn:oecd:ties:stf:v4")})

... in package-info.java

AndroidStudio: Failed to sync Install build tools

I have the same problem. i have solved this issue by the following point.

First one is go to inside build.gradle app file and change this

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"
}

with this one

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"
}

I hope this will solve your issue.

How do I specify unique constraint for multiple columns in MySQL?

MySql 5 or higher behaves like this (I've just tested):

  • you can define unique constraints involving nullable columns. Say you define a constraint unique (A, B) where A is not nullable but B is
  • when evaluating such a constraint you can have (A, null) as many times you want (same A value!)
  • you can only have one (A, not null B) pair

Example: PRODUCT_NAME, PRODUCT_VERSION 'glass', null 'glass', null 'wine', 1

Now if you try to insert ('wine' 1) again it will report a constraint violation Hope this helps

How to remove part of a string?

If you're specifically targetting "11223344", then use str_replace:

// str_replace($search, $replace, $subject)
echo str_replace("11223344", "","REGISTER 11223344 here");

Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)

All good and valid courses of investigation especially the logs for more info.

For those hitting this it might be a simple gotcha where when you have created the DB User you may have enforced a password policy and left the user to change the password on first login (i.e. left the checkboxes around the password field at their default values).

Very easily done in SQL Management Studio and can of course cause authentication issues off the bat that are masked unless you look into the logs.

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

Find all controls in WPF Window by type

For some reason, none of the answers posted here helped me to get all controls of given type contained in a given control in my MainWindow. I needed to find all menu items in one menu to iterate them. They were not all direct descendants of the menu, so i managed to collect only the first lilne of them using any of the code above. This extension method is my solution for the problem for anyone who will continue to read all the way down here.

public static void FindVisualChildren<T>(this ICollection<T> children, DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            var brethren = LogicalTreeHelper.GetChildren(depObj);
            var brethrenOfType = LogicalTreeHelper.GetChildren(depObj).OfType<T>();
            foreach (var childOfType in brethrenOfType)
            {
                children.Add(childOfType);
            }

            foreach (var rawChild in brethren)
            {
                if (rawChild is DependencyObject)
                {
                    var child = rawChild as DependencyObject;
                    FindVisualChildren<T>(children, child);
                }
            }
        }
    }

Hope it helps.

flutter corner radius with transparent background

If both containers are siblings and the bottom container has rounded corners and the top container is dynamic then you will have to use the stack widget

Stack(
 children: [
   /*your_widget_1*/,
  /*your_widget_2*/,
 ],
);

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

Create a function with optional call variables

Powershell provides a lot of built-in support for common parameter scenarios, including mandatory parameters, optional parameters, "switch" (aka flag) parameters, and "parameter sets."

By default, all parameters are optional. The most basic approach is to simply check each one for $null, then implement whatever logic you want from there. This is basically what you have already shown in your sample code.

If you want to learn about all of the special support that Powershell can give you, check out these links:

about_Functions

about_Functions_Advanced

about_Functions_Advanced_Parameters

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

Failed to load the JNI shared Library (JDK)

Downloaded 64 bit JVM from site and installed it manually and updated the system path variable. That solved the issue.

  1. Default JVM is installed in my system was in "C:\Program Files
    (x86)\Java\jre7"
  2. Manually installed JVM got installed in "C:\Program Files\Java\jre7" and after updating this pate to system path variable it worked.

How to get Java Decompiler / JD / JD-Eclipse running in Eclipse Helios

JAD Decomplier plug-in for Eclipse version 3.x and 4.x.

update site: http://feeling.sourceforge.net/update

Steps:

  1. Open Eclipse IDE.
  2. Click Help->Install New software
  3. Paste above URL and give name as JAD.
  4. Select the Eclipse Class Decompiler
  5. Click on Next and accept agreements
  6. Install it.
  7. Restart Eclipse and check now.

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

You actually need 3 meta tags to support Android, iPhone and Windows Phone

<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">

Less than or equal to

In batch, the > is a redirection sign used to output data into a text file. The compare op's available (And recommended) for cmd are below (quoted from the if /? help):

where compare-op may be one of:

    EQU - equal
    NEQ - not equal
    LSS - less than
    LEQ - less than or equal
    GTR - greater than
    GEQ - greater than or equal

That should explain what you want. The only other compare-op is == which can be switched with the if not parameter. Other then that rely on these three letter ones.

jQuery make global variable

You can avoid declaration of global variables by adding them directly to the global object:

(function(global) {

  ...

  global.varName = someValue;

  ...

}(this));

A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.

You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.

Ansible: copy a directory content to another directory

To copy a directory's content to another directory you can use ansibles copy module:

- name: Copy content of directory 'files'
  copy:
    src: files/    # note the '/' <-- !!!
    dest: /tmp/files/

From the docs about the src parameter:

If (src!) path is a directory, it is copied recursively...
... if path ends with "/", only inside contents of that directory are copied to destination.
... if it does not end with "/", the directory itself with all contents is copied.

adb devices command not working

One thing I didn't try was editing /etc/udev/rules.d/70-android.rules. Is that likely to be the issue?

Any particular reason why you didn't do that? To answer the question - YES! The udev rules are what informs Ubuntu what your device is and allows user-space tools to therefore access it.

You will not be able to use adb without correctly following the instructions.

With that in mind however, you don't say what version of Ubuntu you're using but I had issues with 10.10 - let me know if you need me to post the contents of my rules file.

Don't worry about running adb via sudo, you don't need it. The MODE="0666" from the udev rule allows you to access the device as any user.


EDIT:

Don't forget to reload the rules:

sudo udevadm control --reload-rules

EDIT #2:

As @Jesse Glick correctly points out, if adb is already running in daemon mode, you'll also need to restart it for this to work:

sudo adb kill-server

I've used sudo here, since that will guarantee that adb will be killed , and it's the officially supported method to stop the server. It will be automatically restarted the next time adb is used, but this time with the correct environment.

Google Maps API v3: Can I setZoom after fitBounds?

If I'm not mistaken, I'm assuming you want all your points to be visible on the map with the highest possible zoom level. I accomplished this by initializing the zoom level of the map to 16(not sure if it's the highest possible zoom level on V3).

var map = new google.maps.Map(document.getElementById('map_canvas'), {
  zoom: 16,
  center: marker_point,
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

Then after that I did the bounds stuff:

var bounds = new google.maps.LatLngBounds();

// You can have a loop here of all you marker points
// Begin loop
bounds.extend(marker_point);
// End loop

map.fitBounds(bounds);

Result: Success!

PermissionError: [Errno 13] Permission denied

I had a similar problem. I thought it might be with the system. But, using shutil.copytree() from the shutil module solved the problem for me!

how to parse json using groovy

        def jsonFile = new File('File Path');
        JsonSlurper jsonSlurper = new JsonSlurper();
        def parseJson = jsonSlurper.parse(jsonFile)
        String json = JsonOutput.toJson(parseJson)
        def prettyJson = JsonOutput.prettyPrint(json)
        println(prettyJson)

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

Handling null values in Freemarker

Use ?? operator at the end of your <#if> statement.

This example demonstrates how to handle null values for two lists in a Freemaker template.

List of cars:
<#if cars??>
    <#list cars as car>${car.owner};</#list>
</#if>
List of motocycles:
<#if motocycles??>
    <#list motocycles as motocycle>${motocycle.owner};</#list>
</#if>

Bin size in Matplotlib (Histogram)

For a histogram with integer x-values I ended up using

plt.hist(data, np.arange(min(data)-0.5, max(data)+0.5))
plt.xticks(range(min(data), max(data)))

The offset of 0.5 centers the bins on the x-axis values. The plt.xticks call adds a tick for every integer.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

Why are unnamed namespaces used and what are their benefits?

Unnamed namespaces are a utility to make an identifier translation unit local. They behave as if you would choose a unique name per translation unit for a namespace:

namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }

The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like ::name that are defined in that namespace, since the using directive already took place.

This means you can have free functions called (for example) help that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the static keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.

namespace { int a1; }
static int a2;

Both a's are translation unit local and won't clash at link time. But the difference is that the a1 in the anonymous namespace gets a unique name.

Read the excellent article at comeau-computing Why is an unnamed namespace used instead of static? (Archive.org mirror).