Programs & Examples On #Scrap your boilerplate

This Haskell package contains the generics system described in the Scrap Your Boilerplate papers (see http://www.cs.uu.nl/wiki/GenericProgramming/SYB). It defines the Data class of types permitting folding and unfolding of constructor applications, instances of this class for primitive types, and a variety of traversals.

Javascript: formatting a rounded number to N decimals

I found a way. This is Christoph's code with a fix:

function toFixed(value, precision) {
    var precision = precision || 0,
        power = Math.pow(10, precision),
        absValue = Math.abs(Math.round(value * power)),
        result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));

    if (precision > 0) {
        var fraction = String(absValue % power),
            padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
        result += '.' + padding + fraction;
    }
    return result;
}

Read the details of repeating a character using an array constructor here if you are curious as to why I added the "+ 1".

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Look at https://expressjs.com/en/resources/middleware/cors.html You have to use cors.

Install:

$ npm install cors
const cors = require('cors');
app.use(cors());

You have to put this code in your node server.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Vuejs and Vue.set(), update array

One alternative - and more lightweight approach to your problem - might be, just editing the array temporarily and then assigning the whole array back to your variable. Because as Vue does not watch individual items it will watch the whole variable being updated.

So you this should work as well:

var tempArray[];

tempArray = this.items;

tempArray[targetPosition]  = value;

this.items = tempArray;

This then should also update your DOM.

Removing the password from a VBA project

I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.

This one does not use SendKeys.

Let me know if this helps! JFV

Jinja2 template variable if None Object set a default value

Following this doc you can do this that way:

{{ p.User['first_name']|default('NONE') }}

NSDictionary - Need to check whether dictionary contains key-value pair or not

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

What's the difference between compiled and interpreted language?

Here is the Basic Difference between Compiler vs Interpreter Language.

Compiler Language

  • Takes entire program as single input and converts it into object code which is stored in the file.
  • Intermediate Object code is generated
  • e.g: C,C++
  • Compiled programs run faster because compilation is done before execution.
  • Memory requirement is more due to the creation of object code.
  • Error are displayed after the entire program is compiled
  • Source code ---Compiler ---Machine Code ---Output

Interpreter Language:

  • Takes single instruction as single input and executes instructions.
  • Intermediate Object code is NOT generated
  • e.g: Perl, Python, Matlab
  • Interpreted programs run slower because compilation and execution take place simultaneously.
  • Memory requirement is less.
  • Error are displayed for every single instruction.
  • Source Code ---Interpreter ---Output

How to display length of filtered ng-repeat data

Since AngularJS 1.3 you can use aliases:

item in items | filter:x as results

and somewhere:

<span>Total {{results.length}} result(s).</span>

From docs:

You can also provide an optional alias expression which will then store the intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message when a filter is active on the repeater, but the filtered result set is empty.

For example: item in items | filter:x as results will store the fragment of the repeated items as results, but only after the items have been processed through the filter.

How do I write a for loop in bash

if you're intereased only in bash the "for(( ... ))" solution presented above is the best, but if you want something POSIX SH compliant that will work on all unices you'll have to use "expr" and "while", and that's because "(())" or "seq" or "i=i+1" are not that portable among various shells

Bootstrap control with multiple "data-toggle"

Not yet. However, it has been suggested that someone add this feature one day.

The following bootstrap Github issue shows a perfect example of what you are wishing for. It is possible- but not without writing your own workaround code at this stage though.

Check it out... :-)

https://github.com/twitter/bootstrap/issues/7011

How to overload functions in javascript?

I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:

var out = def({
    'int': function(a) {
        alert('Here is int '+a);
    },

    'float': function(a) {
        alert('Here is float '+a);
    },

    'string': function(a) {
        alert('Here is string '+a);
    },

    'int,string': function(a, b) {
        alert('Here is an int '+a+' and a string '+b);
    },
    'default': function(obj) {
        alert('Here is some other value '+ obj);
    }

});

out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);

The methods used to achieve this:

var def = function(functions, parent) {
 return function() {
    var types = [];
    var args = [];
    eachArg(arguments, function(i, elem) {
        args.push(elem);
        types.push(whatis(elem));
    });
    if(functions.hasOwnProperty(types.join())) {
        return functions[types.join()].apply(parent, args);
    } else {
        if (typeof functions === 'function')
            return functions.apply(parent, args);
        if (functions.hasOwnProperty('default'))
            return functions['default'].apply(parent, args);        
    }
  };
};

var eachArg = function(args, fn) {
 var i = 0;
 while (args.hasOwnProperty(i)) {
    if(fn !== undefined)
        fn(i, args[i]);
    i++;
 }
 return i-1;
};

var whatis = function(val) {

 if(val === undefined)
    return 'undefined';
 if(val === null)
    return 'null';

 var type = typeof val;

 if(type === 'object') {
    if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
        return 'array';
    if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
        return 'date';
    if(val.hasOwnProperty('toExponential'))
        type = 'number';
    if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
        return 'string';
 }

 if(type === 'number') {
    if(val.toString().indexOf('.') > 0)
        return 'float';
    else
        return 'int';
 }

 return type;
};

IntelliJ Organize Imports

Shortcut for the Mac: (ctrl + opt + o)

How to create RecyclerView with multiple view type?

Create different ViewHolder for different layout

enter image description here
RecyclerView can have any number of viewholders you want but for better readability lets see how to create one with two ViewHolders.

It can be done in three simple steps

  1. Override public int getItemViewType(int position)
  2. Return different ViewHolders based on the ViewType in onCreateViewHolder() method
  3. Populate View based on the itemViewType in onBindViewHolder() method

Here is a small code snippet

public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

   private static final int LAYOUT_ONE= 0;
   private static final int LAYOUT_TWO= 1;

   @Override
   public int getItemViewType(int position)
   {
      if(position==0)
        return LAYOUT_ONE;
      else
        return LAYOUT_TWO;
   }

   @Override
   public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

      View view =null;
      RecyclerView.ViewHolder viewHolder = null;

      if(viewType==LAYOUT_ONE)
      {
          view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
          viewHolder = new ViewHolderOne(view);
      }
      else
      {
          view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
          viewHolder= new ViewHolderTwo(view);
      }

      return viewHolder;
   }

   @Override
   public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

      if(holder.getItemViewType()== LAYOUT_ONE)
      {
            // Typecast Viewholder 
            // Set Viewholder properties 
            // Add any click listener if any 
      }
      else {

        ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
        vaultItemHolder.name.setText(displayText);
        vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
            .......
           }
         });

       }

   }

  //****************  VIEW HOLDER 1 ******************//

   public class ViewHolderOne extends RecyclerView.ViewHolder {

      public TextView name;

      public ViewHolderOne(View itemView) {
         super(itemView);
         name = (TextView)itemView.findViewById(R.id.displayName);
     }
   }


   //****************  VIEW HOLDER 2 ******************//

   public class ViewHolderTwo extends RecyclerView.ViewHolder{

      public ViewHolderTwo(View itemView) {
         super(itemView);

        ..... Do something
      }
   }
}

getItemViewType(int position) is the key

In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.

Lets see one example to prove my point. If you want to show two layout at alternate positions do this

@Override
public int getItemViewType(int position)
{
   if(position%2==0)       // Even position 
     return LAYOUT_ONE;
   else                   // Odd position 
     return LAYOUT_TWO;
}

Relevant Links:

Check out the project where I have implemented this

How to darken a background using CSS?

Use an :after psuedo-element:

.overlay {
    position: relative;
    transition: all 1s;
}

.overlay:after {
    content: '\A';
    position: absolute;
    width: 100%; 
    height:100%;
    top:0; 
    left:0;
    background:rgba(0,0,0,0.5);
    opacity: 1;
    transition: all 0.5s;
    -webkit-transition: all 0.5s;
    -moz-transition: all 0.5s;
}
.overlay:hover:after {
    opacity: 0;
}

Check out my pen >

http://codepen.io/craigocurtis/pen/KzXYad

How best to read a File into List<string>

Don't store it if possible. Just read through it if you are memory constrained. You can use a StreamReader:

using (var reader = new StreamReader("file.txt"))
{
    var line = reader.ReadLine();
    // process line here
}

This can be wrapped in a method which yields strings per line read if you want to use LINQ.

count number of lines in terminal output

Piping to 'wc' could be better IF the last line ends with a newline (I know that in this case, it will)
However, if the last line does not end with a newline 'wc -l' gives back a false result.

For example:

$ echo "asd" | wc -l

Will return 1 and

$ echo -n "asd" | wc -l

Will return 0


So what I often use is grep <anything> -c

$ echo "asd" | grep "^.*$" -c
1

$ echo -n "asd" | grep "^.*$" -c
1

This is closer to reality than what wc -l will return.

Laravel Eloquent - Get one Row

Laravel 5.2

$sql = "SELECT * FROM users WHERE email = $email";

$user = collect(\User::select($sql))->first();

or

$user = User::table('users')->where('email', $email)->pluck();

gradlew: Permission Denied

You could use "bash" before command:

bash ./gradlew compileDebug --stacktrace

How to color the Git console?

Well, if you are not satisfied with the default setting, you can use ANSI escape code to help you set the color, and if you want to modify some text, you can write bash to help you. see as below:

Eaxmplae

# .gitconfig

[alias]
    st-color = "!f() { \
        echo -n -e '\\033[38;2;255;0;01m\\033[4m' ;\
        git status -s | grep ' D' | \
        sed -e 's/^ ./DELETE:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[48;2;128;128;128m' ;\
        echo -n -e '\\033[38;2;0;255;01m' ;\
        git status -s | grep ' [AM]' | \
        sed -e 's/^ ./NEW OR MODIFY:/' ; \
        echo -n -e '\\033[m' ;\
        \
        echo -n -e '\\033[38;2;255;0;255m' ;\
        echo Rename ;\
        git status -s | grep 'R ' | \
        sed -e 's/^..//' ; \
        echo -n -e '\\033[m' ;\
    }; f"

demo

enter image description here

Explanation

  1. you can write the long script on .gitconfig use the syntax as below:

    [alias]
        your-cmd = !f() { \
            \
        }; f"
    
  2. echo -n -e (see more echo)

    • -n = Do not output a trailing newline.
    • -e Enable interpretation of the following backslash-escaped
  3. \\033[38;2;255;0;0m\\033[4m (see more SGR parameters)

    • \\033[38;2;255;0;0m : 38 mean fore color. 255;0;0 = Red | r;g;b
    • \\033[4m : underline
  4. grep : The grep command is used to search text.

  5. sed -e 's/be_replace_string/new_string/' replace string to new string.

Escaping single quote in PHP when inserting into MySQL

mysql_real_escape_string() or str_replace() function will help you to solve your problem.

http://phptutorial.co.in/php-echo-print/

Download files in laravel using Response::download

// Try this to download any file. laravel 5.*

// you need to use facade "use Illuminate\Http\Response;"

public function getDownload()
{

//PDF file is stored under project/public/download/info.pdf

    $file= public_path(). "/download/info.pdf";   

    return response()->download($file);
}

How to find when a web page was last updated

There is another way to find the page update which could be useful for some occasions (if works:).

If the page has been indexed by Google, or by Wayback Machine you can try to find out what date(s) was(were) saved by them (these methods do not work for any page, and have some limitations, which are extensively investigated in this webmasters.stackexchange question's answers. But in many cases they can help you to find out the page update date(s):

  1. Google way: Go by link https://www.google.com.ua/search?q=site%3Awww.example.com&biw=1855&bih=916&source=lnt&tbs=cdr%3A1%2Ccd_min%3A1%2F1%2F2000%2Ccd_max%3A&tbm=
    • You can change text in search field by any page URL you want.
    • For example, the current stackoverflow question page search gives us as a result May 14, 2014 - which is the question creation date: enter image description here
  2. Wayback machine way: Go by link https://web.archive.org/web/*/www.example.com
    • for this stackoverflow page wayback machine gives us more results: Saved 6 times between June 7, 2014 and November 23, 2016., and you can view all saved copies for each date

What are functional interfaces used for in Java 8?

Not at all. Lambda expressions are the one and only point of that annotation.

How to split csv whose columns may contain ,

Use a library like LumenWorks to do your CSV reading. It'll handle fields with quotes in them and will likely overall be more robust than your custom solution by virtue of having been around for a long time.

Javascript ajax call on page onload

This is really easy using a JavaScript library, e.g. using jQuery you could write:

$(document).ready(function(){
$.ajax({ url: "database/update.html",
        context: document.body,
        success: function(){
           alert("done");
        }});
});

Without jQuery, the simplest version might be as follows, but it does not account for browser differences or error handling:

<html>
  <body onload="updateDB();">
  </body>
  <script language="javascript">
    function updateDB() {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "database/update.html", true);
      xhr.send(null);
      /* ignore result */
    }
  </script>
</html>

See also:

Multi-select dropdown list in ASP.NET

HTML does not support a dropdown list with checkboxes. You can have a dropdown list, or a checkbox list. You could possibly fake a dropdowncheckbox list using javascript and hiding divs, but that would be less reliable than just a standard checkbox list.

There are of course 3rd party controls that look like a dropdown checkboxlist, but they are using the div tricks.

you could also use a double listbox, which handles multi select by moving items back and forth between two lists. This has the added benefit of being easily to see all the selected items at once, even though the list of total items is long

(Imagine a list of every city in the world, with only the first and last selected)

Best way to generate xml?

An optional way if you want to use pure Python:

ElementTree is good for most cases, but it can't CData and pretty print.

So, if you need CData and pretty print you should use minidom:

minidom_example.py:

from xml.dom import minidom

doc = minidom.Document()

root = doc.createElement('root')
doc.appendChild(root)

leaf = doc.createElement('leaf')
text = doc.createTextNode('Text element with attributes')
leaf.appendChild(text)
leaf.setAttribute('color', 'white')
root.appendChild(leaf)

leaf_cdata = doc.createElement('leaf_cdata')
cdata = doc.createCDATASection('<em>CData</em> can contain <strong>HTML tags</strong> without encoding')
leaf_cdata.appendChild(cdata)
root.appendChild(leaf_cdata)

branch = doc.createElement('branch')
branch.appendChild(leaf.cloneNode(True))
root.appendChild(branch)

mixed = doc.createElement('mixed')
mixed_leaf = leaf.cloneNode(True)
mixed_leaf.setAttribute('color', 'black')
mixed_leaf.setAttribute('state', 'modified')
mixed.appendChild(mixed_leaf)
mixed_text = doc.createTextNode('Do not use mixed elements if it possible.')
mixed.appendChild(mixed_text)
root.appendChild(mixed)

xml_str = doc.toprettyxml(indent="  ")
with open("minidom_example.xml", "w") as f:
    f.write(xml_str)

minidom_example.xml:

<?xml version="1.0" ?>
<root>
  <leaf color="white">Text element with attributes</leaf>
  <leaf_cdata>
<![CDATA[<em>CData</em> can contain <strong>HTML tags</strong> without encoding]]>  </leaf_cdata>
  <branch>
    <leaf color="white">Text element with attributes</leaf>
  </branch>
  <mixed>
    <leaf color="black" state="modified">Text element with attributes</leaf>
    Do not use mixed elements if it possible.
  </mixed>
</root>

fatal: does not appear to be a git repository

I was facing same issue with my one of my feature branch. I tried above mentioned solution nothing worked. I resolved this issue by doing following things.

  • git pull origin feature-branch-name
  • git push

Unable to create Genymotion Virtual Device

We had the same issues, it was because we had wrong version of Oracle VM Virtual Box. Make sure you uninstall wrong version and re-install Compatible Oracle VM Virtual Box.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

They are exactly the same. When you use it be consistent. Use one of them in your database

Storing Data in MySQL as JSON

json characters are nothing special when it comes down to storage, chars such as

{,},[,],',a-z,0-9.... are really nothing special and can be stored as text.

the first problem your going to have is this

{ profile_id: 22, username: 'Robert', password: 'skhgeeht893htgn34ythg9er' }

that stored in a database is not that simple to update unless you had your own proceedure and developed a jsondecode for mysql

UPDATE users SET JSON(user_data,'username') = 'New User';

So as you cant do that you would Have to first SELECT the json, Decode it, change it, update it, so in theory you might as well spend more time constructing a suitable database structure!

I do use json to store data but only Meta Data, data that dont get updated often, not related to the user specific.. example if a user adds a post, and in that post he adds images ill parse the images and create thumbs and then use the thumb urls in a json format.

How to Execute stored procedure from SQL Plus?

You forgot to put z as an bind variable.

The following EXECUTE command runs a PL/SQL statement that references a stored procedure:

SQL> EXECUTE -
> :Z := EMP_SALE.HIRE('JACK','MANAGER','JONES',2990,'SALES')

Note that the value returned by the stored procedure is being return into :Z

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Screenshot1

Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.

Screenshot2

Then you are good to go. For more information you can always refer to the developer site.

Calculating the sum of two variables in a batch script

According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.

Hope I Helped!

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

Git keeps prompting me for a password

Microsoft Stack solution (Windows and Azure DevOps)

First open the .git/config file to make sure the address looks like:

protocol://something@url

E.g. .git/config for Azure DevOps:

[remote "origin"]
    url = https://[email protected]/mystore/myproject/
    fetch = +refs/heads/*:refs/remotes/origin/*

If the problem still persists, open Windows Credential Manager, click on the safebox named Windows Credentials and remove all the git related credentials.

Now the next time you log into git, it won't go away anymore.

How to check if any fields in a form are empty in php

Specify POST method in form
<form name="registrationform" action="register.php" method="post">


your form code

</form>

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

How to change theme for AlertDialog

I was having this AlertDialog theme related issue using sdk 1.6 as described here: http://markmail.org/message/mj5ut56irkrkc4nr

I solved the issue by doing the following:

  new AlertDialog.Builder(
  new ContextThemeWrapper(context, android.R.style.Theme_Dialog))

Hope this helps.

Test if executable exists in Python?

See os.path module for some useful functions on pathnames. To check if an existing file is executable, use os.access(path, mode), with the os.X_OK mode.

os.X_OK

Value to include in the mode parameter of access() to determine if path can be executed.

EDIT: The suggested which() implementations are missing one clue - using os.path.join() to build full file names.

Is there a MessageBox equivalent in WPF?

As the others say, there is a MessageBox in the WPF namespace (System.Windows).

The problem is that it is the same old messagebox with OK, Cancel, etc. Windows Vista and Windows 7 have moved on to use Task Dialogs instead.

Unfortunately there is no easy standard interface for task dialogs. I use an implementation from CodeProject KB.

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

Visual Studio 2010 - recommended extensions

Quick Open File for Visual Studio 2010 - free. Simulates the feature known to Eclipse users as Open Resource. This plugin gives Visual Studio equivalently quick method for opening any solution file.

VS10x Editor View Enhancer - free beta. Type and member definitions emphasizing, end-of-block details, clickable hotspots (C# and VB documents)

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

It is more flexible to use curl instead of fopen and file_get_content for opening a webpage.

Is it possible to specify the schema when connecting to postgres with JDBC?

In Go with "sql.DB" (note the search_path with underscore):

postgres://user:password@host/dbname?sslmode=disable&search_path=schema

Flutter Circle Design

Try This!

demo

I have added 5 circles you can add more. And instead of RaisedButton use InkResponse.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new ExampleWidget()));
}

class ExampleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Widget bigCircle = new Container(
      width: 300.0,
      height: 300.0,
      decoration: new BoxDecoration(
        color: Colors.orange,
        shape: BoxShape.circle,
      ),
    );

    return new Material(
      color: Colors.black,
      child: new Center(
        child: new Stack(
          children: <Widget>[
            bigCircle,
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.favorite_border),
              top: 10.0,
              left: 130.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.timer),
              top: 120.0,
              left: 10.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.place),
              top: 120.0,
              right: 10.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.local_pizza),
              top: 240.0,
              left: 130.0,
            ),
            new Positioned(
              child: new CircleButton(onTap: () => print("Cool"), iconData: Icons.satellite),
              top: 120.0,
              left: 130.0,
            ),
          ],
        ),
      ),
    );
  }
}

class CircleButton extends StatelessWidget {
  final GestureTapCallback onTap;
  final IconData iconData;

  const CircleButton({Key key, this.onTap, this.iconData}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double size = 50.0;

    return new InkResponse(
      onTap: onTap,
      child: new Container(
        width: size,
        height: size,
        decoration: new BoxDecoration(
          color: Colors.white,
          shape: BoxShape.circle,
        ),
        child: new Icon(
          iconData,
          color: Colors.black,
        ),
      ),
    );
  }
}

How to deep watch an array in angularjs?

Here is a comparison of the 3 ways you can watch a scope variable with examples:

$watch() is triggered by:

$scope.myArray = [];
$scope.myArray = null;
$scope.myArray = someOtherArray;

$watchCollection() is triggered by everything above AND:

$scope.myArray.push({}); // add element
$scope.myArray.splice(0, 1); // remove element
$scope.myArray[0] = {}; // assign index to different value

$watch(..., true) is triggered by EVERYTHING above AND:

$scope.myArray[0].someProperty = "someValue";

JUST ONE MORE THING...

$watch() is the only one that triggers when an array is replaced with another array even if that other array has the same exact content.

For example where $watch() would fire and $watchCollection() would not:

$scope.myArray = ["Apples", "Bananas", "Orange" ];

var newArray = [];
newArray.push("Apples");
newArray.push("Bananas");
newArray.push("Orange");

$scope.myArray = newArray;

Below is a link to an example JSFiddle that uses all the different watch combinations and outputs log messages to indicate which "watches" were triggered:

http://jsfiddle.net/luisperezphd/2zj9k872/

adb devices command not working

HTC One m7 running fresh Cyanogenmod 11.

Phone is connected USB and tethering my data connection.

Then I get this surprise:

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
????????????    no permissions

SOLUTION: Turn tethering OFF on phone.

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858    device

Why is semicolon allowed in this python snippet?

Python does let you use a semi-colon to denote the end of a statement if you are including more than one statement on a line.

How to enable ASP classic in IIS7.5

I found some detailed instructions here: http://digitallibraryworld.com/?p=6

The key piece of advice seems to be, don't use the 64-bit ASP.DLL (found in system32) if you've configured the app pool to run 32-bit applications (instead, use the 32-bit ASP.DLL).

Add a script map using the following setting:

Request Path: *.asp
Executable: C:\Windows\system32\inetsrv\asp.dll
Name: whatever you want. I named my Classic ASP

The executable above is 64 BIT ASP handler for your asp script. If you want your ASP script to be handled in 32 bit environment, you need to use executable from this location: C:\Windows\SysWOW64\inetsrv\asp.dll.

Of course, if you don't need to load any 32-bit libraries (or data providers, etc.), just make your life easier by running the 64-bit ASP.DLL!

Run batch file as a Windows service

On Windows 2019 Server, you can run a Minecraft java server with these commands:

sc create minecraft-server DisplayName= "minecraft-server" binpath= "cmd.exe /C C:\Users\Administrator\Desktop\rungui1151.lnk" type= own start= auto

The .lnk file is a standard windows shortcut to a batch file.

--- .bat file begins ---

java -Xmx40960M -Xms40960M -d64 -jar minecraft_server.1.15.1.jar

--- .bat file ends ---

All this because:

service does not know how to start in a folder,

cmd.exe does not know how to start in a folder

Starting the service will produce "timely manner" error, but the log file reveals the server is running.

If you need to shut down the server, just go into task manager and find the server java in background processes and end it, or terminate the server from in the game using the /stop command, or for other programs/servers, use the methods relevant to the server.

How do I calculate square root in Python?

This might be a little late to answer but most simple and accurate way to compute square root is newton's method.

You have a number which you want to compute its square root (num) and you have a guess of its square root (estimate). Estimate can be any number bigger than 0, but a number that makes sense shortens the recursive call depth significantly.

new_estimate = (estimate + num / estimate) / 2

This line computes a more accurate estimate with those 2 parameters. You can pass new_estimate value to the function and compute another new_estimate which is more accurate than the previous one or you can make a recursive function definition like this.

def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num / estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)

For example we need to find 30's square root. We know that the result is between 5 and 6.

newtons_method(30,5)

number is 30 and estimate is 5. The result from each recursive calls are:

5.5
5.477272727272727
5.4772255752546215
5.477225575051661

The last result is the most accurate computation of the square root of number. It is the same value as the built-in function math.sqrt().

SQL Server add auto increment primary key to existing table

No - you have to do it the other way around: add it right from the get go as INT IDENTITY - it will be filled with identity values when you do this:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY

and then you can make it the primary key:

ALTER TABLE dbo.YourTable
   ADD CONSTRAINT PK_YourTable
   PRIMARY KEY(ID)

or if you prefer to do all in one step:

ALTER TABLE dbo.YourTable
   ADD ID INT IDENTITY
       CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

Is there a real solution to debug cordova apps

You can debug Cordova Android Applications which are installed on your phone remotely from your computer via the USB cable (you can also remotely click on the web application as if you were viewing the web application from your compueter) with "Chrome Remote Debugging". You can also debug web application viewed in the Stock Android browser or Chrome on Android this way.

  1. Enable developer mode on your Android device (go to settings -> about phone -> tap 7x on the build number).

  2. Connect your computer with your phone via USB cable.

  3. Lunch Chrome on your computer and navigate to chrome://inspect and click the "Inspect" button next to the remote device which you want to debug (under the "Devices" tab). OR right click inside Chrome on your computer -> Inspect -> Costumize and control DevTools (3 vertical dots - top right corner of the developer tools) -> More tools -> Remote Devices -> under Devices on the left side, click on your device to which you are connected via USB -> click on the Inspect button for the application you want.

  4. Then click on "Console" and you can debug JavaScript the same way, as you would on a normal web application with Chrome developer tools.

How can I get the username of the logged-in user in Django?

request.user.get_username() will return a string of the users email.

request.user.username will return a method.

Filter dataframe rows if value in column is in a set list of values

you can also use ranges by using:

b = df[(df['a'] > 1) & (df['a'] < 5)]

Homebrew: Could not symlink, /usr/local/bin is not writable

The other answers are correct, as far as they go, but they don't answer why this issue might be occurring, and how to address that root cause.

Cause

There are two possible causes to this issue:

  1. The homebrew installation was performed with a user other than the one you are currently using. Homebrew expects that only the user that installed it originally would ever want to use it.
  2. You installed some software that writes to /usr/local without using brew. This is the cause brew doctor suggests, if you run it.

Solution

Multiuser Homebrew

If you have multiple user accounts, and you want more than one of them to be able to use brew, you need to run through a few steps, otherwise you will constantly have to change ownership of the Homebrew file structure every time you switch users, and that's not a great idea.

Detailed instructions can be found online, but the quick answer is this:

  1. Create a group named brew:

    1. Open System preferences
    2. Click Accounts
    3. Click the "+" (unlock first if necessary)
    4. Under New account select Group
    5. enter brew
    6. Click Create Group
  2. Select the brew group, and add the user accounts you want to use brew to it.
  3. change the /usr/local folder group ownership: sudo chgrp -R brew /usr/local
  4. change the permissions to add write to /usr/local as group: sudo chmod -R g+w /usr/local
  5. change homebrew cache directory group: sudo chgrp -R brew /Library/Caches/Homebrew
  6. change the homebrew cache directory permissions: sudo chmod -R g+w /Library/Caches/Homebrew

Single User Homebrew

If you're not trying to use more than one user with Homebrew, then the solution provided by the other answers, based on the suggestions of brew doctor is probably sufficient:

sudo chown -R $(whoami) /usr/local

sudo chown -R $(whoami) /Library/Caches/Homebrew

Verification

After these steps, brew doctor should report success by any user in the brew group, assuming you've logged out and back in to apply the new group memberships (if you went the multiuser route). If you just corrected things for single user homebrew, then logging out and back in shouldn't be necessary as none of your group memberships have changed.

Move SQL data from one table to another

Use this single sql statement which is safe no need of commit/rollback with multiple statements.

INSERT Table2 (
      username,password
) SELECT username,password
      FROM    (
           DELETE Table1
           OUTPUT
                   DELETED.username,
                   DELETED.password
           WHERE username = 'X' and password = 'X'
      ) AS RowsToMove ;

Works on SQL server make appropriate changes for MySql

Convert NSDate to NSString

+(NSString*)date2str:(NSDate*)myNSDateInstance onlyDate:(BOOL)onlyDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (onlyDate) {
        [formatter setDateFormat:@"yyyy-MM-dd"];
    }else{
        [formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    }

    //Optionally for time zone conversions
    //   [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

    NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
    return stringFromDate;
}

+(NSDate*)str2date:(NSString*)dateStr{
    if ([dateStr isKindOfClass:[NSDate class]]) {
        return (NSDate*)dateStr;
    }

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    return date;
}

Pythonic way to combine FOR loop and IF statement

You can use generators too, if generator expressions become too involved or complex:

def gen():
    for x in xyz:
        if x in a:
            yield x

for x in gen():
    print x

Can I run javascript before the whole page is loaded?

You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.

So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded event or functions like $.ready in jQuery.

Declaring a python function with an array parameters and passing an array argument to the function call?

Maybe you want unpack elements of array, I don't know if I got it, but below a example:

def my_func(*args):
    for a in args:
        print a

my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)

When should an Excel VBA variable be killed or set to Nothing?

VB6/VBA uses deterministic approach to destoying objects. Each object stores number of references to itself. When the number reaches zero, the object is destroyed.

Object variables are guaranteed to be cleaned (set to Nothing) when they go out of scope, this decrements the reference counters in their respective objects. No manual action required.

There are only two cases when you want an explicit cleanup:

  1. When you want an object to be destroyed before its variable goes out of scope (e.g., your procedure is going to take long time to execute, and the object holds a resource, so you want to destroy the object as soon as possible to release the resource).

  2. When you have a circular reference between two or more objects.

    If objectA stores a references to objectB, and objectB stores a reference to objectA, the two objects will never get destroyed unless you brake the chain by explicitly setting objectA.ReferenceToB = Nothing or objectB.ReferenceToA = Nothing.

The code snippet you show is wrong. No manual cleanup is required. It is even harmful to do a manual cleanup, as it gives you a false sense of more correct code.

If you have a variable at a class level, it will be cleaned/destroyed when the class instance is destructed. You can destroy it earlier if you want (see item 1.).

If you have a variable at a module level, it will be cleaned/destroyed when your program exits (or, in case of VBA, when the VBA project is reset). You can destroy it earlier if you want (see item 1.).

Access level of a variable (public vs. private) does not affect its life time.

How can I save a base64-encoded image to disk?

This did it for me simply and perfectly.

Excellent explanation by Scott Robinson

From image to base64 string

let buff = fs.readFileSync('stack-abuse-logo.png');
let base64data = buff.toString('base64');

From base64 string to image

let buff = new Buffer(data, 'base64');
fs.writeFileSync('stack-abuse-logo-out.png', buff);

Make content horizontally scroll inside a div

if you remove the float: left from the a and add white-space: nowrap to the outer div

#myWorkContent{
    width:530px;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}
#myWorkContent a {
    display: inline;
}

this should work for any size or amount of images..

or even:

#myWorkContent a {
    display: inline-block;
    vertical-align: middle;
}

which would also vertically align images of different heights if required

test code

Add class to <html> with Javascript?

You should append class not overwrite it

var headCSS = document.getElementsByTagName("html")[0].getAttribute("class") || "";
document.getElementsByTagName("html")[0].setAttribute("class",headCSS +"foo");

I would still recommend using jQuery to avoid browser incompatibilities

UIButton title text color

In Swift:

Changing the label text color is quite different than changing it for a UIButton. To change the text color for a UIButton use this method:

self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)

Get file path of image on Android

You can do like that In Kotlin If you need kotlin code in the future

val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))

fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
    val bytes = ByteArrayOutputStream()
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
    return Uri.parse(path)
}

fun getRealPathFromURI(uri: Uri): String {
    val cursor = contentResolver.query(uri, null, null, null, null)
    cursor!!.moveToFirst()
    val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
    return cursor.getString(idx)
}

Guid is all 0's (zeros)?

Try this instead:

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = new Guid.NewGuid()
});

This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid();   // g4 is not all zeroes

Compare this to doing the same thing with an int:

int i1;                     // i1 is 0
int i2 = new int();         // i2 is 0
int i3 = default(int);      // i3 is 0

Difference between Hashing a Password and Encrypting it

Hashing is a one way function (well, a mapping). It's irreversible, you apply the secure hash algorithm and you cannot get the original string back. The most you can do is to generate what's called "a collision", that is, finding a different string that provides the same hash. Cryptographically secure hash algorithms are designed to prevent the occurrence of collisions. You can attack a secure hash by the use of a rainbow table, which you can counteract by applying a salt to the hash before storing it.

Encrypting is a proper (two way) function. It's reversible, you can decrypt the mangled string to get original string if you have the key.

The unsafe functionality it's referring to is that if you encrypt the passwords, your application has the key stored somewhere and an attacker who gets access to your database (and/or code) can get the original passwords by getting both the key and the encrypted text, whereas with a hash it's impossible.

People usually say that if a cracker owns your database or your code he doesn't need a password, thus the difference is moot. This is naïve, because you still have the duty to protect your users' passwords, mainly because most of them do use the same password over and over again, exposing them to a greater risk by leaking their passwords.

Send POST request with JSON data using Volley

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

refer

How do I get the key at a specific index from a Dictionary in Swift?

SWIFT 4


Slightly off-topic: But here is if you have an Array of Dictionaries i.e: [ [String : String] ]

var array_has_dictionary = [ // Start of array

   // Dictionary 1

   [ 
     "name" : "xxxx",
     "age" : "xxxx",
     "last_name":"xxx"
   ],

   // Dictionary 2

   [ 
     "name" : "yyy",
     "age" : "yyy",
     "last_name":"yyy"
   ],

 ] // end of array


cell.textLabel?.text =  Array(array_has_dictionary[1])[1].key
// Output: age -> yyy

Remove all subviews?

This does only apply to OSX since in iOS a copy of the array is kept

When removing all the subviews, it is a good idea to start deleting at the end of the array and keep deleting until you reach the beginning. This can be accomplished with this two lines of code:

for (int i=mySuperView.subviews.count-1; i>=0; i--)
        [[mySuperView.subviews objectAtIndex:i] removeFromSuperview];

SWIFT 1.2

for var i=mySuperView.subviews.count-1; i>=0; i-- {
    mySuperView.subviews[i].removeFromSuperview();
}

or (less efficient, but more readable)

for subview in mySuperView.subviews.reverse() {
    subview.removeFromSuperview()
}

NOTE

You should NOT remove the subviews in normal order, since it may cause a crash if a UIView instance is deleted before the removeFromSuperview message has been sent to all objects of the array. (Obviously, deleting the last element would not cause a crash)

Therefore, the code

[[someUIView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

should NOT be used.

Quote from Apple documentation about makeObjectsPerformSelector:

Sends to each object in the array the message identified by a given selector, starting with the first object and continuing through the array to the last object.

(which would be the wrong direction for this purpose)

Django: Calling .update() on a single model instance retrieved by .get()?

I am using the following code in such cases:

obj, created = Model.objects.get_or_create(id=some_id)

if not created:
   resp= "It was created"
else:
   resp= "OK"
   obj.save()

Unable to connect to any of the specified mysql hosts. C# MySQL

I was having the exact same error.

Here's what you need to do:

If you are using MAMP, close your server. Then click on the preferences button when you open up MAMP again (before restarting your server of course).

Then you will need to click on the ports tab, and click the button "Set Web and MySQL Ports to 80 & 3306".

Array initialization syntax when not in a declaration

Why is this blocked by Java?

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

But "why" is immaterial ... the restriction is there, and you have to live with it.

I know how to work around it, but from time to time it would be simpler.

You can write this:

AClass[] array;
...
array = new AClass[]{object1, object2};

difference between @size(max = value ) and @min(value) @max(value)

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

How to implement Rate It feature in Android App

Make sure the below is implemented For in-app reviews:

implementation 'com.google.android.play:core:1.8.0'

OnCreate

public void RateApp(Context mContext) {
    try {
        ReviewManager manager = ReviewManagerFactory.create(mContext);
        manager.requestReviewFlow().addOnCompleteListener(new OnCompleteListener<ReviewInfo>() {
            @Override
            public void onComplete(@NonNull Task<ReviewInfo> task) {
                if(task.isSuccessful()){
                    ReviewInfo reviewInfo = task.getResult();
                    manager.launchReviewFlow((Activity) mContext, reviewInfo).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(Exception e) {
                            Toast.makeText(mContext, "Rating Failed", Toast.LENGTH_SHORT).show();
                        }
                    }).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            Toast.makeText(mContext, "Review Completed, Thank You!", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Toast.makeText(mContext, "In-App Request Failed", Toast.LENGTH_SHORT).show();
            }
        });
    } catch (ActivityNotFoundException e) {
        e.printStackTrace();
    }
}

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

Adapted from Timmmm to PYQT5

from PyQt5.QtGui import QPixmap
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QLabel


class Label(QLabel):

    def __init__(self):
        super(Label, self).__init__()
        self.pixmap_width: int = 1
        self.pixmapHeight: int = 1

    def setPixmap(self, pm: QPixmap) -> None:
        self.pixmap_width = pm.width()
        self.pixmapHeight = pm.height()

        self.updateMargins()
        super(Label, self).setPixmap(pm)

    def resizeEvent(self, a0: QResizeEvent) -> None:
        self.updateMargins()
        super(Label, self).resizeEvent(a0)

    def updateMargins(self):
        if self.pixmap() is None:
            return
        pixmapWidth = self.pixmap().width()
        pixmapHeight = self.pixmap().height()
        if pixmapWidth <= 0 or pixmapHeight <= 0:
            return
        w, h = self.width(), self.height()
        if w <= 0 or h <= 0:
            return

        if w * pixmapHeight > h * pixmapWidth:
            m = int((w - (pixmapWidth * h / pixmapHeight)) / 2)
            self.setContentsMargins(m, 0, m, 0)
        else:
            m = int((h - (pixmapHeight * w / pixmapWidth)) / 2)
            self.setContentsMargins(0, m, 0, m)

Count number of rows per group and add result to original data frame

This should do your work :

df_agg <- aggregate(num~name+type,df,FUN=NROW)
names(df_agg)[3] <- "count"
df <- merge(df,df_agg,by=c('name','type'),all.x=TRUE)

Storage permission error in Marshmallow

From marshmallow version, developers need to ask for runtime permissions to user. Let me give you whole process for asking runtime permissions.

I am using reference from here : marshmallow runtime permissions android.

First create a method which checks whether all permissions are given or not

private  boolean checkAndRequestPermissions() {
        int camerapermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        int writepermission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permissionLocation = ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);
        int permissionRecordAudio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);


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

        if (camerapermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }
        if (writepermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (permissionRecordAudio != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.RECORD_AUDIO);
        }
        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
        }
        return true;
    } 

Now here is the code which is run after above method. We will override onRequestPermissionsResult() method :

 @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        Log.d(TAG, "Permission callback called-------");
        switch (requestCode) {
            case REQUEST_ID_MULTIPLE_PERMISSIONS: {

                Map<String, Integer> perms = new HashMap<>();
                // Initialize the map with both permissions
                perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                // Fill with actual results from user
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);
                    // Check for both permissions
                    if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                            && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED 
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
&& perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "sms & location services permission granted");
                        // process the normal flow
                        Intent i = new Intent(MainActivity.this, WelcomeActivity.class);
                        startActivity(i);
                        finish();
                        //else any one or both the permissions are not granted
                    } else {
                        Log.d(TAG, "Some permissions are not granted ask again ");
                        //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
//                        // shouldShowRequestPermissionRationale will return true
                        //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) 
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) 
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
 || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                            showDialogOK("Service Permissions are required for this app",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (which) {
                                                case DialogInterface.BUTTON_POSITIVE:
                                                    checkAndRequestPermissions();
                                                    break;
                                                case DialogInterface.BUTTON_NEGATIVE:
                                                    // proceed with logic by disabling the related features or quit the app.
                                                    finish();
                                                    break;
                                            }
                                        }
                                    });
                        }
                        //permission is denied (and never ask again is  checked)
                        //shouldShowRequestPermissionRationale will return false
                        else {
                            explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
                            //                            //proceed with logic by disabling the related features or quit the app.
                        }
                    }
                }
            }
        }

    }

If user clicks on Deny option then showDialogOK() method will be used to show dialog

If user clicks on Deny and also clicks a checkbox saying "never ask again", then explain() method will be used to show dialog.

methods to show dialogs :

 private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", okListener)
                .create()
                .show();
    }
    private void explain(String msg){
        final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
        dialog.setMessage(msg)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        //  permissionsclass.requestPermission(type,code);
                        startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:com.exampledemo.parsaniahardik.marshmallowpermission")));
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        finish();
                    }
                });
        dialog.show();
    }

Above code snippet asks for four permissions at a time. You can also ask for any number of permissions in your any activity as per your requirements.

How to print a stack trace in Node.js?

If you want to only log the stack trace of the error (and not the error message) Node 6 and above automatically includes the error name and message inside the stack trace, which is a bit annoying if you want to do some custom error handling:

console.log(error.stack.replace(error.message, ''))

This workaround will log only the error name and stack trace (so you can, for example, format the error message and display it how you want somewhere else in your code).

The above example would print only the error name follow by the stack trace, for example:

Error: 
    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

Instead of:

Error: Error: Command failed: sh ./commands/getBranchCommitCount.sh HEAD
git: 'rev-lists' is not a git command. See 'git --help'.

Did you mean this?
        rev-list

    at /Users/cfisher/Git/squashed/execProcess.js:6:17
    at ChildProcess.exithandler (child_process.js:213:5)
    at emitTwo (events.js:106:13)
    at ChildProcess.emit (events.js:191:7)
    at maybeClose (internal/child_process.js:877:16)
    at Socket.<anonymous> (internal/child_process.js:334:11)
    at emitOne (events.js:96:13)
    at Socket.emit (events.js:188:7)
    at Pipe._handle.close [as _onclose] (net.js:498:12)

C function that counts lines in file

You have a ; at the end of the if. Change:

  if (fp == NULL);
  return 0;

to

  if (fp == NULL) 
    return 0;

Directory Chooser in HTML page

In case if you are the server and the user (e.g. you are creating an app which works via browser and you need to choose a folder) then try to call JFileChooser from the server when some button is clicked in the browser

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

This code snipped is from here

ASP.NET Core 1.0 on IIS error 502.5

I had the same problem.

To find out the exact source of it I switched on logging in web.config file:

<aspNetCore processPath="dotnet" arguments=".\MyWebService.dll" stdoutLogEnabled="**true**" stdoutLogFile=".\logs\stdout" />

and created logs subfolder in MyWebService root folder.

After restarting IIS and trying to execute API I got an error and it was missing of proper Core Runtime. After downloading an installing DotNetCore.1.0.5_1.1.2-WindowsHosting the error gone.

scroll up and down a div on button click using jquery

scrollBottom is not a method in jQuery.

UPDATED DEMO - http://jsfiddle.net/xEFq5/10/

Try this:

   $("#upClick").on("click" ,function(){
     scrolled=scrolled-300;
        $(".cover").animate({
          scrollTop:  scrolled
     });
   });

Java escape JSON String?

Apache Commons

If you're already using Apache commons, it provides a static method for this:

StringEscapeUtils.escapeJson("some string")

It converts any string into one that's properly escaped for inclusion in JSON

See the documentation here

Check if a parameter is null or empty in a stored procedure

Here is the general pattern:

IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '')

'' is an empty string in SQL Server.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Taking up @ZF007's answer, this is not answering your question as a whole, but can be the solution for the same error. I post it here since I have not found a direct solution as an answer to this error message elsewhere on Stack Overflow.

The error appears when you check whether an array was empty or not.

  • if np.array([1,2]): print(1) --> ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().

  • if np.array([1,2])[0]: print(1) --> no ValueError, but: if np.array([])[0]: print(1) --> IndexError: index 0 is out of bounds for axis 0 with size 0.

  • if np.array([1]): print(1) --> no ValueError, but again will not help at an array with many elements.

  • if np.array([]): print(1) --> DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use 'array.size > 0' to check that an array is not empty.

Doing so:

  • if np.array([]).size: print(1) solved the error.

How to set cursor to input box in Javascript?

Sometimes you do get focus but no cursor in a text field. In this case you would do this:

document.getElementById(frmObj.id).select();

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

For limit 1 use methods FirstOrDefault() or First().

Example

var y = (from x in q select x).FirstOrDefault();

cast class into another class or convert class to another

Use JSON serialization and deserialization:

using Newtonsoft.Json;

Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));

Or:

public class Class1
{
    public static explicit operator Class2(Class1 obj)
    {
        return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
    }
}

Which then allows you to do something like

Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;

Upload failed You need to use a different version code for your APK because you already have one with version code 2

(For Flutter App) You need to use a different version code for your APK or Android App Bundle because you already have one with version code 1.

Don't be panic...

You need to change in Flutter Version from pubspec.yaml file and Version Code from local.properties file.

First go to your pubspec.yaml file. The first three lines should be name, description and version of App.

Before Release -

For you the version might look something like this:

version: 1.0.0+1

So before creating an apk for release (for update your exiting app on Google Play Console i.e for new update) make sure you increment this number by 1. (You should increment it as there's no requirement on increment step) .

Solution

Just change that version to (As per your need )

version: 1.0.1+2

And Second if

flutter.versionCode in Project -> android -> local.properties is

flutter.versionCode=1 then change it or upgrade it to the flutter.versionCode=2 or any other greater number than previous code.

And finally release the app as per documentation.

How do you migrate an IIS 7 site to another server?

Microsoft Web Deploy v3 can export and import all your files, the configuration settings, etc. It puts it all into a zip archive ready to import on the new server. It can even upgrade to newer versions of IIS (v7-v8).

http://www.iis.net/extensions/WebDeploymentTool

After installing the tool: Right click your server or website in IIS Management Console, select 'Deploy', 'Export Application...' and run through the export.

On the new server, import the exported zip archive in the same way.

POST request with a simple string in body with Alamofire

If you use Alamofire, it is enough to encoding type to "URLEncoding.httpBody"

With that, you can send your data as a string in the httpbody allthough you defined it json in your code.

It worked for me..

UPDATED for

  var url = "http://..."
    let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
    let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]

    let url =  NSURL(string:"url" as String)

    request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody , headers: _headers).responseJSON(completionHandler: {
        response in response

        let jsonResponse = response.result.value as! NSDictionary

        if jsonResponse["access_token"] != nil
        {
            access_token = String(describing: jsonResponse["accesstoken"]!)

        }

    })

Make XAMPP / Apache serve file outside of htdocs folder

A VirtualHost would also work for this and may work better for you as you can host several projects without the need for subdirectories. Here's how you do it:

httpd.conf (or extra\httpd-vhosts.conf relative to httpd.conf. Trailing slashes "\" might cause it not to work):

NameVirtualHost *:80
# ...
<VirtualHost *:80>  
    DocumentRoot C:\projects\transitCalculator\trunk\
    ServerName transitcalculator.localhost
    <Directory C:\projects\transitCalculator\trunk\>  
        Order allow,deny  
        Allow from all  
    </Directory>
</VirtualHost> 

HOSTS file (c:\windows\system32\drivers\etc\hosts usually):

# localhost entries
127.0.0.1 localhost transitcalculator.localhost

Now restart XAMPP and you should be able to access http://transitcalculator.localhost/ and it will map straight to that directory.

This can be helpful if you're trying to replicate a production environment where you're developing a site that will sit on the root of a domain name. You can, for example, point to files with absolute paths that will carry over to the server:

<img src="/images/logo.png" alt="My Logo" />

whereas in an environment using aliases or subdirectories, you'd need keep track of exactly where the "images" directory was relative to the current file.

onclick open window and specific size

These are the best practices from Mozilla Developer Network's window.open page :

<script type="text/javascript">
var windowObjectReference = null; // global variable

function openFFPromotionPopup() {
  if(windowObjectReference == null || windowObjectReference.closed)
  /* if the pointer to the window object in memory does not exist
     or if such pointer exists but the window was closed */

  {
    windowObjectReference = window.open("http://www.spreadfirefox.com/",
   "PromoteFirefoxWindowName", "resizable,scrollbars,status");
    /* then create it. The new window will be created and
       will be brought on top of any other window. */
  }
  else
  {
    windowObjectReference.focus();
    /* else the window reference must exist and the window
       is not closed; therefore, we can bring it back on top of any other
       window with the focus() method. There would be no need to re-create
       the window or to reload the referenced resource. */
  };
}
</script>

<p><a
 href="http://www.spreadfirefox.com/"
 target="PromoteFirefoxWindowName"
 onclick="openFFPromotionPopup(); return false;" 
 title="This link will create a new window or will re-use an already opened one"
>Promote Firefox adoption</a></p>

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

Good examples using java.util.logging

I'd use minlog, personally. It's extremely simple, as the logging class is a few hundred lines of code.

Performing user authentication in Java EE / JSF using j_security_check

I suppose you want form based authentication using deployment descriptors and j_security_check.

You can also do this in JSF by just using the same predefinied field names j_username and j_password as demonstrated in the tutorial.

E.g.

<form action="j_security_check" method="post">
    <h:outputLabel for="j_username" value="Username" />
    <h:inputText id="j_username" />
    <br />
    <h:outputLabel for="j_password" value="Password" />
    <h:inputSecret id="j_password" />
    <br />
    <h:commandButton value="Login" />
</form>

You could do lazy loading in the User getter to check if the User is already logged in and if not, then check if the Principal is present in the request and if so, then get the User associated with j_username.

package com.stackoverflow.q2206911;

import java.io.IOException;
import java.security.Principal;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

@ManagedBean
@SessionScoped
public class Auth {

    private User user; // The JPA entity.

    @EJB
    private UserService userService;

    public User getUser() {
        if (user == null) {
            Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
            if (principal != null) {
                user = userService.find(principal.getName()); // Find User by j_username.
            }
        }
        return user;
    }

}

The User is obviously accessible in JSF EL by #{auth.user}.

To logout do a HttpServletRequest#logout() (and set User to null!). You can get a handle of the HttpServletRequest in JSF by ExternalContext#getRequest(). You can also just invalidate the session altogether.

public String logout() {
    FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    return "login?faces-redirect=true";
}

For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.


Update: you can also use the new Servlet 3.0 HttpServletRequest#login() to do a programmatic login instead of using j_security_check which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username and password properties and a login method which look like this:

<h:form>
    <h:outputLabel for="username" value="Username" />
    <h:inputText id="username" value="#{auth.username}" required="true" />
    <h:message for="username" />
    <br />
    <h:outputLabel for="password" value="Password" />
    <h:inputSecret id="password" value="#{auth.password}" required="true" />
    <h:message for="password" />
    <br />
    <h:commandButton value="Login" action="#{auth.login}" />
    <h:messages globalOnly="true" />
</h:form>

And this view scoped managed bean which also remembers the initially requested page:

@ManagedBean
@ViewScoped
public class Auth {

    private String username;
    private String password;
    private String originalURL;

    @PostConstruct
    public void init() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

        if (originalURL == null) {
            originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
        } else {
            String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

            if (originalQuery != null) {
                originalURL += "?" + originalQuery;
            }
        }
    }

    @EJB
    private UserService userService;

    public void login() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();
        HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();

        try {
            request.login(username, password);
            User user = userService.find(username, password);
            externalContext.getSessionMap().put("user", user);
            externalContext.redirect(originalURL);
        } catch (ServletException e) {
            // Handle unknown username/password in request.login().
            context.addMessage(null, new FacesMessage("Unknown login"));
        }
    }

    public void logout() throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.invalidateSession();
        externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
    }

    // Getters/setters for username and password.
}

This way the User is accessible in JSF EL by #{user}.

LEFT INNER JOIN vs. LEFT OUTER JOIN - Why does the OUTER take longer?

Wait -- did you actually mean that "the same number of rows ... are being processed" or that "the same number of rows are being returned"? In general, the outer join would process many more rows, including those for which there is no match, even if it returns the same number of records.

When should we call System.exit in Java

If you have another program running in the JVM and you use System.exit, that second program will be closed, too. Imagine for example that you run a java job on a cluster node and that the java program that manages the cluster node runs in the same JVM. If the job would use System.exit it would not only quit the job but also "shut down the complete node". You would not be able to send another job to that cluster node since the management program has been closed accidentally.

Therefore, do not use System.exit if you want to be able to control your program from another java program within the same JVM.

Use System.exit if you want to close the complete JVM on purpose and if you want to take advantage of the possibilities that have been described in the other answers (e.g. shut down hooks: Java shutdown hook, non-zero return value for command line calls: How to get the exit status of a Java program in Windows batch file).

Also have a look at Runtime Exceptions: System.exit(num) or throw a RuntimeException from main?

In PowerShell, how can I test if a variable holds a numeric value?

I ran into this topic while working on input validation with read-host. If I tried to specify the data type for the variable as part of the read-host command and the user entered something other than that data type then read-host would error out. This is how I got around that and ensured that the user enters the data type I wanted:

do
    {
    try
        {
        [int]$thing = read-host -prompt "Enter a number or else"
        $GotANumber = $true
        }
    catch
        {
        $GotANumber = $false
        }
    }
until
    ($gotanumber)

Force an Android activity to always use landscape mode

That's it!! Long waiting for this fix.

I've an old Android issue about double-start an activity that required (programmatically) landscape mode: setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)

Now Android make Landscape mode on start.

how to make a cell of table hyperlink

Here is my solution:

<td>
   <a href="/yourURL"></a>
   <div class="item-container">
      <img class="icon" src="/iconURL" />
      <p class="name">
         SomeText
      </p>
   </div>
</td>

(LESS)

td {
  padding: 1%;
  vertical-align: bottom;
  position:relative;

     a {
        height: 100%;
        display: block;
        position: absolute;
        top:0;
        bottom:0;
        right:0;
        left:0;
       }

     .item-container {
         /*...*/
     }
}

Like this you can still benefit from some table cell properties like vertical-align.(Tested on Chrome)

Multiple modals overlay

I realize an answer has been accepted, but I strongly suggest not hacking bootstrap to fix this.

You can pretty easily achieve the same effect by hooking the shown.bs.modal and hidden.bs.modal event handlers and adjusting the z-index there.

Here's a working example

A bit more info is available here.

This solution works automatically with arbitrarily deeply stacks modals.

The script source code:

$(document).ready(function() {

    $('.modal').on('hidden.bs.modal', function(event) {
        $(this).removeClass( 'fv-modal-stack' );
        $('body').data( 'fv_open_modals', $('body').data( 'fv_open_modals' ) - 1 );
    });

    $('.modal').on('shown.bs.modal', function (event) {
        // keep track of the number of open modals
        if ( typeof( $('body').data( 'fv_open_modals' ) ) == 'undefined' ) {
            $('body').data( 'fv_open_modals', 0 );
        }

        // if the z-index of this modal has been set, ignore.
        if ($(this).hasClass('fv-modal-stack')) {
            return;
        }

        $(this).addClass('fv-modal-stack');
        $('body').data('fv_open_modals', $('body').data('fv_open_modals' ) + 1 );
        $(this).css('z-index', 1040 + (10 * $('body').data('fv_open_modals' )));
        $('.modal-backdrop').not('.fv-modal-stack').css('z-index', 1039 + (10 * $('body').data('fv_open_modals')));
        $('.modal-backdrop').not('fv-modal-stack').addClass('fv-modal-stack'); 

    });        
});

How can I select all options of multi-select select box on click?

Give selected attribute to all options like this

$('#countries option').attr('selected', 'selected');

Usage:

$('#select_all').click( function() {
    $('#countries option').attr('selected', 'selected');
});

Update

In case you are using 1.6+, better option would be to use .prop() instead of .attr()

$('#select_all').click( function() {
    $('#countries option').prop('selected', true);
});

How can I do a BEFORE UPDATED trigger with sql server?

It is true that there aren't "before triggers" in MSSQL. However, you could still track the changes that were made on the table, by using the "inserted" and "deleted" tables together. When an update causes the trigger to fire, the "inserted" table stores the new values and the "deleted" table stores the old values. Once having this info, you could relatively easy simulate the "before trigger" behaviour.

What is the { get; set; } syntax in C#?

So as I understand it { get; set; } is an "auto property" which just like @Klaus and @Brandon said is shorthand for writing a property with a "backing field." So in this case:

public class Genre
{
    private string name; // This is the backing field
    public string Name   // This is your property
    {
        get => name;
        set => name = value;
    }
}

However if you're like me - about an hour or so ago - you don't really understand what properties and accessors are, and you don't have the best understanding of some basic terminologies either. MSDN is a great tool for learning stuff like this but it's not always easy to understand for beginners. So I'm gonna try to explain this more in-depth here.

get and set are accessors, meaning they're able to access data and info in private fields (usually from a backing field) and usually do so from public properties (as you can see in the above example).

There's no denying that the above statement is pretty confusing, so let's go into some examples. Let's say this code is referring to genres of music. So within the class Genre, we're going to want different genres of music. Let's say we want to have 3 genres: Hip Hop, Rock, and Country. To do this we would use the name of the Class to create new instances of that class.

Genre g1 = new Genre(); //Here we're creating a new instance of the class "Genre"
                        //called g1. We'll create as many as we need (3)
Genre g2 = new Genre();
Genre g3 = new Genre();

//Note the () following new Genre. I believe that's essential since we're creating a
//new instance of a class (Like I said, I'm a beginner so I can't tell you exactly why
//it's there but I do know it's essential)

Now that we've created the instances of the Genre class we can set the genre names using the 'Name' property that was set way up above.

public string Name //Again, this is the 'Name' property
{ get; set; } //And this is the shorthand version the process we're doing right now 

We can set the name of 'g1' to Hip Hop by writing the following

g1.Name = "Hip Hop";

What's happening here is sort of complex. Like I said before, get and set access information from private fields that you otherwise wouldn't be able to access. get can only read information from that private field and return it. set can only write information in that private field. But by having a property with both get and set we're able do both of those functions. And by writing g1.Name = "Hip Hop"; we are specifically using the set function from our Name property

set uses an implicit variable called value. Basically what this means is any time you see "value" within set, it's referring to a variable; the "value" variable. When we write g1.Name = we're using the = to pass in the value variable which in this case is "Hip Hop". So you can essentially think of it like this:

public class g1 //We've created an instance of the Genre Class called "g1"
{
    private string name;
    public string Name
    {
        get => name;
        set => name = "Hip Hop"; //instead of 'value', "Hip Hop" is written because 
                              //'value' in 'g1' was set to "Hip Hop" by previously
                              //writing 'g1.Name = "Hip Hop"'
    }
}

It's Important to note that the above example isn't actually written in the code. It's more of a hypothetical code that represents what's going on in the background.

So now that we've set the Name of the g1 instance of Genre, I believe we can get the name by writing

console.WriteLine (g1.Name); //This uses the 'get' function from our 'Name' Property 
                             //and returns the field 'name' which we just set to
                             //"Hip Hop"

and if we ran this we would get "Hip Hop" in our console.

So for the purpose of this explanation I'll complete the example with outputs as well

using System;
public class Genre
{
    public string Name { get; set; }
}

public class MainClass
{
    public static void Main()
    {
        Genre g1 = new Genre();
        Genre g2 = new Genre();
        Genre g3 = new Genre();

        g1.Name = "Hip Hop";
        g2.Name = "Rock";
        g3.Name = "Country";

        Console.WriteLine ("Genres: {0}, {1}, {2}", g1.Name, g2.Name, g3.Name);
    }
}

Output:

"Genres: Hip Hop, Rock, Country"

Get the current first responder without using a private API

With a category on UIResponder, it is possible to legally ask the UIApplication object to tell you who the first responder is.

See this:

Is there any way of asking an iOS view which of its children has first responder status?

clk'event vs rising_edge()

The linked comment is incorrect : 'L' to '1' will produce a rising edge.

In addition, if your clock signal transitions from 'H' to '1', rising_edge(clk) will (correctly) not trigger while (clk'event and clk = '1') (incorrectly) will.

Granted, that may look like a contrived example, but I have seen clock waveforms do that in real hardware, due to failures elsewhere.

Programmatically retrieve SQL Server stored procedure source that is identical to the source returned by the SQL Server Management Studio gui?

I agree with Mark. I set the output to text mode and then sp_HelpText 'sproc'. I have this binded to Crtl-F1 to make it easy.

ORA-30926: unable to get a stable set of rows in the source tables

This is usually caused by duplicates in the query specified in USING clause. This probably means that TABLE_A is a parent table and the same ROWID is returned several times.

You could quickly solve the problem by using a DISTINCT in your query (in fact, if 'Y' is a constant value you don't even need to put it in the query).

Assuming your query is correct (don't know your tables) you could do something like this:

  MERGE INTO table_1 a
      USING 
      (SELECT distinct ta.ROWID row_id
              FROM table_1 a ,table_2 b ,table_3 c
              WHERE a.mbr = c.mbr
              AND b.head = c.head
              AND b.type_of_action <> '6') src
              ON ( a.ROWID = src.row_id )
  WHEN MATCHED THEN UPDATE SET in_correct = 'Y';

How to enable named/bind/DNS full logging?

Run command rndc querylog on or add querylog yes; to options{}; section in named.conf to activate that channel.

Also make sure you’re checking correct directory if your bind is chrooted.

How to use mod operator in bash?

You must put your mathematical expressions inside $(( )).

One-liner:

for i in {1..600}; do wget http://example.com/search/link$(($i % 5)); done;

Multiple lines:

for i in {1..600}; do
    wget http://example.com/search/link$(($i % 5))
done

How can I check if an array contains a specific value in php?

Following is how you can do this:

<?php
$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('kitchen', $rooms)){
    echo 'this array contains kitchen';
}

Make sure that you search for kitchen and not Kitchen. This function is case sensitive. So, the below function simply won't work:

$rooms = ['kitchen', 'bedroom', 'living_room', 'dining_room']; # this is your array
if(in_array('KITCHEN', $rooms)){
    echo 'this array contains kitchen';
}

If you rather want a quick way to make this search case insensitive, have a look at the proposed solution in this reply: https://stackoverflow.com/a/30555568/8661779

Source: http://dwellupper.io/post/50/understanding-php-in-array-function-with-examples

How to turn a String into a JavaScript function call?

While I like the first answer and I hate eval, I'd like to add that there's another way (similar to eval) so if you can go around it and not use it, you better do. But in some cases you may want to call some javascript code before or after some ajax call and if you have this code in a custom attribute instead of ajax you could use this:

    var executeBefore = $(el).attr("data-execute-before-ajax");
    if (executeBefore != "") {
        var fn = new Function(executeBefore);
        fn();
    }

Or eventually store this in a function cache if you may need to call it multiple times.

Again - don't use eval or this method if you have another way to do that.

How do I clone into a non-empty directory?

This worked for me:

cd existing_folder
git init
git remote add origin path_to_your_repo.git
git add .
git commit
git push -u origin master

How to read file binary in C#?

Quick and dirty version:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();

foreach(byte b in fileBytes)
{
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
}

File.WriteAllText(outputFilename, sb.ToString());

How can I count all the lines of code in a directory recursively?

Yet another variation :)

$ find . -name '*.php' | xargs cat | wc -l

This will give the total sum, instead of file-by-file.

Add . after find to make it work.

Entity Framework - Code First - Can't Store List<String>

I Know this is a old question, and Pawel has given the correct answer, I just wanted to show a code example of how to do some string processing, and avoid an extra class for the list of a primitive type.

public class Test
{
    public Test()
    {
        _strings = new List<string>
        {
            "test",
            "test2",
            "test3",
            "test4"
        };
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    private List<String> _strings { get; set; }

    public List<string> Strings
    {
        get { return _strings; }
        set { _strings = value; }
    }

    [Required]
    public string StringsAsString
    {
        get { return String.Join(',', _strings); }
        set { _strings = value.Split(',').ToList(); }
    }
}

If input value is blank, assign a value of "empty" with Javascript

You can set a callback function for the onSubmit event of the form and check the contents of each field. If it contains nothing you can then fill it with the string "empty":

<form name="my_form" action="validate.php" onsubmit="check()">
    <input type="text" name="text1" />
    <input type="submit" value="submit" />
</form>

and in your js:

function check() {
    if(document.forms["my_form"]["text1"].value == "")
        document.forms["my_form"]["text1"].value = "empty";
}

Bootstrap close responsive menu "on click"

This works, but does not animate.

$('.btn-navbar').addClass('collapsed');
$('.nav-collapse').removeClass('in').css('height', '0');

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

How can strings be concatenated?

The easiest way would be

Section = 'Sec_' + Section

But for efficiency, see: https://waymoot.org/home/python_string/

Format XML string to print friendly XML string

Customizable Pretty XML output with UTF-8 XML declaration

The following class definition gives a simple method to convert an input XML string into formatted output XML with the xml declaration as UTF-8. It supports all the configuration options that the XmlWriterSettings class offers.

using System;
using System.Text;
using System.Xml;
using System.IO;

namespace CJBS.Demo
{
    /// <summary>
    /// Supports formatting for XML in a format that is easily human-readable.
    /// </summary>
    public static class PrettyXmlFormatter
    {

        /// <summary>
        /// Generates formatted UTF-8 XML for the content in the <paramref name="doc"/>
        /// </summary>
        /// <param name="doc">XmlDocument for which content will be returned as a formatted string</param>
        /// <returns>Formatted (indented) XML string</returns>
        public static string GetPrettyXml(XmlDocument doc)
        {
            // Configure how XML is to be formatted
            XmlWriterSettings settings = new XmlWriterSettings 
            {
                Indent = true
                , IndentChars = "  "
                , NewLineChars = System.Environment.NewLine
                , NewLineHandling = NewLineHandling.Replace
                //,NewLineOnAttributes = true
                //,OmitXmlDeclaration = false
            };

            // Use wrapper class that supports UTF-8 encoding
            StringWriterWithEncoding sw = new StringWriterWithEncoding(Encoding.UTF8);

            // Output formatted XML to StringWriter
            using (XmlWriter writer = XmlWriter.Create(sw, settings))
            {
                doc.Save(writer);
            }

            // Get formatted text from writer
            return sw.ToString();
        }



        /// <summary>
        /// Wrapper class around <see cref="StringWriter"/> that supports encoding.
        /// Attribution: http://stackoverflow.com/a/427737/3063884
        /// </summary>
        private sealed class StringWriterWithEncoding : StringWriter
        {
            private readonly Encoding encoding;

            /// <summary>
            /// Creates a new <see cref="PrettyXmlFormatter"/> with the specified encoding
            /// </summary>
            /// <param name="encoding"></param>
            public StringWriterWithEncoding(Encoding encoding)
            {
                this.encoding = encoding;
            }

            /// <summary>
            /// Encoding to use when dealing with text
            /// </summary>
            public override Encoding Encoding
            {
                get { return encoding; }
            }
        }
    }
}

Possibilities for further improvement:-

  • An additional method GetPrettyXml(XmlDocument doc, XmlWriterSettings settings) could be created that allows the caller to customize the output.
  • An additional method GetPrettyXml(String rawXml) could be added that supports parsing raw text, rather than have the client use the XmlDocument. In my case, I needed to manipulate the XML using the XmlDocument, hence I didn't add this.

Usage:

String myFormattedXml = null;
XmlDocument doc = new XmlDocument();
try
{
    doc.LoadXml(myRawXmlString);
    myFormattedXml = PrettyXmlFormatter.GetPrettyXml(doc);
}
catch(XmlException ex)
{
    // Failed to parse XML -- use original XML as formatted XML
    myFormattedXml = myRawXmlString;
}

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

Application_Error having issue with Ajax requests. If error handled in Action which called by Ajax - it will display your Error View inside the resulting container.

Serializing a list to JSON

.NET already supports basic Json serialization through the System.Runtime.Serialization.Json namespace and the DataContractJsonSerializer class since version 3.5. As the name implies, DataContractJsonSerializer takes into account any data annotations you add to your objects to create the final Json output.

That can be handy if you already have annotated data classes that you want to serialize Json to a stream, as described in How To: Serialize and Deserialize JSON Data. There are limitations but it's good enough and fast enough if you have basic needs and don't want to add Yet Another Library to your project.

The following code serializea a list to the console output stream. As you see it is a bit more verbose than Json.NET and not type-safe (ie no generics)

        var list = new List<string> {"a", "b", "c", "d"};

        using(var output = Console.OpenStandardOutput())                
        {                
            var writer = new DataContractJsonSerializer(typeof (List<string>));
            writer.WriteObject(output,list);
        }

On the other hand, Json.NET provides much better control over how you generate Json. This will come in VERY handy when you have to map javascript-friendly names names to .NET classes, format dates to json etc.

Another option is ServiceStack.Text, part of the ServicStack ... stack, which provides a set of very fast serializers for Json, JSV and CSV.

Including an anchor tag in an ASP.NET MVC Html.ActionLink

I Did that and it works for redirecting to other view I think If you add the #sectionLink after It will work

<a class="btn yellow" href="/users/Create/@Model.Id" target="_blank">
                                        Add As User
                                    </a>

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I faced same problem but that was related proxy. it was resolved by setting proxy.

Set http_proxy=http://myuserid:mypassword@myproxyname:myproxyport
Set https_proxy=http://myuserid:mypassword@myproxyname:myproxyport

This might help someone.

Convert Difference between 2 times into Milliseconds?

To answer the title-question:

DateTime d1 = ...;
DateTime d2 = ...;
TimeSpan diff = d2 - d1;

int millisceonds = (int) diff.TotalMilliseconds;

You can use this to set a Timer:

timer1.interval = millisceonds;
timer1.Enabled = true;

Don't forget to disable the timer when handling the tick.

But if you want an event at 12:03, just substitute DateTime.Now for d1.

But it is not clear what the exact function of textBox1 and textBox2 are.

Create table using Javascript

I hope you find this helpful.

HTML :

<html>
<head>
    <link rel = "stylesheet" href = "test.css">
<body>

</body>
<script src = "test.js"></script>
</head>
</html>

JAVASCRIPT :

var tableString = "<table>",
    body = document.getElementsByTagName('body')[0],
    div = document.createElement('div');

for (row = 1; row < 101; row += 1) {

    tableString += "<tr>";

    for (col = 1; col < 11; col += 1) {

        tableString += "<td>" + "row [" + row + "]" + "col [" + col + "]" + "</td>";
    }
    tableString += "</tr>";
}

tableString += "</table>";
div.innerHTML = tableString;
body.appendChild(div);

Pythonic way to print list items

To print each element of a given list using a single line code

 for i in result: print(i)

How do you clear your Visual Studio cache on Windows Vista?

The accepted answer gave two locations:

here

C:\Documents and Settings\Administrator\Local Settings\Temp\VWDWebCache

and possibly here

C:\Documents and Settings\Administrator\Local Settings\Application Data\Microsoft\WebsiteCache

Did you try those?

Edited to add

On my Windows Vista machine, it's located in

%Temp%\VWDWebCache

and in

%LocalAppData%\Microsoft\WebsiteCache

From your additional information (regarding team edition) this comes from Clear Client TFS Cache:

Clear Client TFS Cache

Visual Studio and Team Explorer provide a caching mechanism which can get out of sync. If I have multiple instances of a single TFS which can be connected to from a single Visual Studio client, that client can become confused.

To solve it..

For Windows Vista delete contents of this folder

%LocalAppData%\Microsoft\Team Foundation\1.0\Cache

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

javascript: optional first argument in function

Or you also can differentiate by what type of content you got. Options used to be an object the content is used to be a string, so you could say:

if ( typeof content === "object" ) {
  options = content;
  content = null;
}

Or if you are confused with renaming, you can use the arguments array which can be more straightforward:

if ( arguments.length === 1 ) {
  options = arguments[0];
  content = null;
}

iterating over each character of a String in ruby 1.8.6 (each_char)

there is really a problem in 1.8.6. and it's ok after this edition

in 1.8.6,you can add this:

requre 'jcode'

Center a position:fixed element

This solution does not require of you to define a width and height to your popup div.

http://jsfiddle.net/4Ly4B/33/

And instead of calculating the size of the popup, and minus half to the top, javascript is resizeing the popupContainer to fill out the whole screen...

(100% height, does not work when useing display:table-cell; (wich is required to center something vertically))...

Anyway it works :)

How to change the value of attribute in appSettings section with Web.config transformation

Replacing all AppSettings

This is the overkill case where you just want to replace an entire section of the web.config. In this case I will replace all AppSettings in the web.config will new settings in web.release.config. This is my baseline web.config appSettings:

<appSettings>
  <add key="KeyA" value="ValA"/>
  <add key="KeyB" value="ValB"/>
</appSettings>

Now in my web.release.config file, I am going to create a appSettings section except I will include the attribute xdt:Transform=”Replace” since I want to just replace the entire element. I did not have to use xdt:Locator because there is nothing to locate – I just want to wipe the slate clean and replace everything.

<appSettings xdt:Transform="Replace">
  <add key="ProdKeyA" value="ProdValA"/>
  <add key="ProdKeyB" value="ProdValB"/>
  <add key="ProdKeyC" value="ProdValC"/>
</appSettings>

Note that in the web.release.config file my appSettings section has three keys instead of two, and the keys aren’t even the same. Now let’s look at the generated web.config file what happens when we publish:

<appSettings>
   <add key="ProdKeyA" value="ProdValA"/>
   <add key="ProdKeyB" value="ProdValB"/>
   <add key="ProdKeyC" value="ProdValC"/>
 </appSettings>

Just as we expected – the web.config appSettings were completely replaced by the values in web.release config. That was easy!

How do I pass data to Angular routed components?

Pass using JSON

  <a routerLink = "/link"
   [queryParams] = "{parameterName: objectToPass| json }">
         sample Link                   
  </a>

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

I had a similar problem and upon looking into it, it was simply a field in the actual table missing id (id was empty/null) - meaning when you try to make the id field the primary key it will result in error because the table contains a row with null value for the primary key.

This could be the fix if you see a temp table associated with the error. I was using SQL Server Management Studio.

Composer: how can I install another dependency without updating old ones?

Actually, the correct solution is:

composer require vendor/package

Taken from the CLI documentation for Composer:

The require command adds new packages to the composer.json file from the current directory.

php composer.phar require

After adding/changing the requirements, the modified requirements will be installed or updated.

If you do not want to choose requirements interactively, you can just pass them to the command.

php composer.phar require vendor/package:2.* vendor/package2:dev-master

While it is true that composer update installs new packages found in composer.json, it will also update the composer.lock file and any installed packages according to any fuzzy logic (> or * chars after the colons) found in composer.json! This can be avoided by using composer update vendor/package, but I wouldn't recommend making a habit of it, as you're one forgotten argument away from a potentially broken project…

Keep things sane and stick with composer require vendor/package for adding new dependencies!

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

The DateTime::ToString() method has a string formatter that can be used to output datetime in any required format. See DateTime.ToString Method (String) for more information.

Default keystore file does not exist?

go to ~/.android if there is no debug.keystore copy it from your project and paste it here then run command again.

What is a good practice to check if an environmental variable exists or not?

I'd recommend the following solution.

It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.

from os import environ

REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
    raise EnvironmentError(f'Failed because {diff} are not set')

How to search file text for a pattern and replace it with a given value

This works for me:

filename = "foo"
text = File.read(filename) 
content = text.gsub(/search_regexp/, "replacestring")
File.open(filename, "w") { |file| file << content }

AngularJs event to call after content is loaded

Angular < 1.6.X

angular.element(document).ready(function () {
    console.log('page loading completed');
});

Angular >= 1.6.X

angular.element(function () {
    console.log('page loading completed');
});

Node.js/Express.js App Only Works on Port 3000

The default way to change the listening port on The Express framework is to modify the file named www in the bin folder.

There, you will find a line such as the following

var port = normalizePort(process.env.PORT || '3000');

Change the value 3000 to any port you wish.

This is valid for Express version 4.13.1

Which equals operator (== vs ===) should be used in JavaScript comparisons?

In JavaScript it means of the same value and type.

For example,

4 == "4" // will return true

but

4 === "4" // will return false 

android: stretch image in imageview to fit screen

I Have used this android:scaleType="fitXY" code in Xml file.

How to import js-modules into TypeScript file?

I tested 3 methods to do that...

Method1:

      const FriendCard:any = require('./../pages/FriendCard')

Method2:

      import * as FriendCard from './../pages/FriendCard';

Method3:

if you can find something like this in tsconfig.json:

      { "compilerOptions": { ..., "allowJs": true }

then you can write: import FriendCard from './../pages/FriendCard';

Java compiler level does not match the version of the installed Java project facet

Right click the project and select properties Click the java compiler from the left and change to your required version Hope this helps

Bypass invalid SSL certificate errors when calling web services in .Net

I was having same error using DownloadString; and was able to make it works as below with suggestions on this page

System.Net.WebClient client = new System.Net.WebClient();            
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string sHttpResonse = client.DownloadString(sUrl);

How do I show multiple recaptchas on a single page?

_x000D_
_x000D_
var ReCaptchaCallback = function() {_x000D_
      $('.g-recaptcha').each(function(){_x000D_
      var el = $(this);_x000D_
      grecaptcha.render(el.get(0), {'sitekey' : el.data("sitekey")});_x000D_
      });  _x000D_
        };
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallback&render=explicit" async defer></script>_x000D_
_x000D_
_x000D_
ReCaptcha 1_x000D_
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>_x000D_
_x000D_
ReCaptcha 2_x000D_
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>_x000D_
_x000D_
ReCaptcha 3_x000D_
<div class="g-recaptcha" data-sitekey="6Lc8WQcUAAAAABQKSITdXbc6p9HISCQhZIJwm2Zw"></div>
_x000D_
_x000D_
_x000D_

Use StringFormat to add a string to a WPF XAML binding

Please note that using StringFormat in Bindings only seems to work for "text" properties. Using this for Label.Content will not work

How to support different screen size in android

You can figure out the dimensions of the screen dynamically

Display mDisplay= activity.getWindowManager().getDefaultDisplay();
int width= mDisplay.getWidth();
int Height= mDisplay.getHeight();

The layout can be set using the width and the height obtained using this method.

What exactly is Apache Camel?

My take to describe this in a more accessible way...

In order to understand what Apache Camel is, you need to understand what Enterprise Integration Patterns are.

Let's start with what we presumably already know: The Singleton pattern, the Factory pattern, etc; They are merely ways of organizing your solution to the problem, but they are not solutions themselves. These patterns were analyzed and extracted for the rest of us by the Gang of Four, when they published their book: Design Patterns. They saved some of us tremendous effort in thinking of how to best structure our code.

Much like the Gang of Four, Gregor Hohpe and Bobby Woolf authored the book Enterprise Integration Patterns (EIP) in which they propose and document a set of new patterns and blueprints for how we could best design large component-based systems, where components can be running on the same process or in a different machine.

They basically propose that we structure our system to be message oriented -- where components communicate with each others using messages as inputs and outputs and absolutely nothing else. They show us a complete set of patterns that we may choose from and implement in our different components that will together form the whole system.

So what is Apache Camel?

Apache Camel offers you the interfaces for the EIPs, the base objects, commonly needed implementations, debugging tools, a configuration system, and many other helpers which will save you a ton of time when you want to implement your solution to follow the EIPs.

Take MVC. MVC is pretty simple in theory and we could implement it without any framework help. But good MVC frameworks provide us with the structure ready-to-use and have gone the extra mile and thought out all the other "side" things you need when you create a large MVC project and that's why we use them most of the time.

That's exactly what Apache Camel is for EIPs. It's a complete production-ready framework for people who want to implement their solution to follow the EIPs.

How do I make a C++ console program exit?

if you are in the main you can do:

return 0;  

or

exit(exit_code);

The exit code depends of the semantic of your code. 1 is error 0 e a normal exit.

In some other function of your program:

exit(exit_code)  

will exit the program.

How do I convert from a string to an integer in Visual Basic?

Use

Convert.toInt32(txtPrice.Text)

This is assuming VB.NET.

Judging by the name "txtPrice", you really don't want an Integer but a Decimal. So instead use:

Convert.toDecimal(txtPrice.Text)

If this is the case, be sure whatever you assign this to is Decimal not an Integer.

Android Studio doesn't start, fails saying components not installed

I also had issues with OS X Yosemite on a fresh install of Android Studio.

My situation was that I was using a VPN. In the preferences, I ended up setting the HTTP Proxy setting to detect automatically after trying running it as sudo and setting a static proxy setting, but neither worked. I was able to download successfully after that. Hope this helps someone with a similar situation (VPN).

Android HTTP Proxy Settings

How to write text on a image in windows using python opencv2

I know this is a really old question but i think i have a solution In the newer versions of openCV fonts are repesented by a number like this

    FONT_HERSHEY_SIMPLEX = 0,
    FONT_HERSHEY_PLAIN = 1,
    FONT_HERSHEY_DUPLEX = 2,
    FONT_HERSHEY_COMPLEX = 3,
    FONT_HERSHEY_TRIPLEX = 4,
    FONT_HERSHEY_COMPLEX_SMALL = 5,
    FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
    FONT_HERSHEY_SCRIPT_COMPLEX = 7,
    FONT_ITALIC = 16

so all you have to do is replace the font name with the corresponding number

cv2.putText(image,"Hello World!!!", (x,y), 0, 2, 255)

again i know its an old question but it may help someone in the future

Write a file in UTF-8 using FileWriter (Java)?

OK it's 2019 now, and from Java 11 you have a constructor with Charset:

FileWriter?(String fileName, Charset charset)

Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)

Why does the 260 character path length limit exist in Windows?

The question is why does the limitation still exist. Surely modern Windows can increase the side of MAX_PATH to allow longer paths. Why has the limitation not been removed?

  • The reason it cannot be removed is that Windows promised it would never change.

Through API contract, Windows has guaranteed all applications that the standard file APIs will never return a path longer than 260 characters.

Consider the following correct code:

WIN32_FIND_DATA findData;

FindFirstFile("C:\Contoso\*", ref findData);

Windows guaranteed my program that it would populate my WIN32_FIND_DATA structure:

WIN32_FIND_DATA {
   DWORD    dwFileAttributes;
   FILETIME ftCreationTime;
   FILETIME ftLastAccessTime;
   FILETIME ftLastWriteTime;
   //...
   TCHAR    cFileName[MAX_PATH];
   //..
}

My application didn't declare the value of the constant MAX_PATH, the Windows API did. My application used that defined value.

My structure is correctly defined, and only allocates 592 bytes total. That means that i am only able to receive a filename that is less than 260 characters. Windows promised me that if i wrote my application correctly, my application would continue to work in the future.

If Windows were to allow filenames longer than 260 characters then my existing application (which used the correct API correctly) would fail.

For anyone calling for Microsoft to change the MAX_PATH constant, they first need to ensure that no existing application fails. For example, i still own and use a Windows application that was written to run on Windows 3.11. It still runs on 64-bit Windows 10. That is what backwards compatibility gets you.

Microsoft did create a way to use the full 32,768 path names; but they had to create a new API contract to do it. For one, you should use the Shell API to enumerate files (as not all files exist on a hard drive or network share).

But they also have to not break existing user applications. The vast majority of applications do not use the shell api for file work. Everyone just calls FindFirstFile/FindNextFile and calls it a day.

How can I get the count of milliseconds since midnight for the current?

Joda-Time

I think you can use Joda-Time to do this. Take a look at the DateTime class and its getMillisOfSecond method. Something like

int ms = new DateTime().getMillisOfSecond() ;

how to open popup window using jsp or jquery?

Try this:

SCRIPT:

function winOpen()
{
    window.open("yourpage.jsp");
}

HTML:

<a href="javascript:;" onclick="winOpen()">Pop Up</a>

Read https://developer.mozilla.org/en/docs/DOM/window.open for window.open

.jar error - could not find or load main class

Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.

Swift double to string

let double = 1.5 
let string = double.description

update Xcode 7.1 • Swift 2.1:

Now Double is also convertible to String so you can simply use it as you wish:

let double = 1.5
let doubleString = String(double)   // "1.5"

Swift 3 or later we can extend LosslessStringConvertible and make it generic

Xcode 11.3 • Swift 5.1 or later

extension LosslessStringConvertible { 
    var string: String { .init(self) } 
}

let double = 1.5 
let string = double.string  //  "1.5"

For a fixed number of fraction digits we can extend FloatingPoint protocol:

extension FloatingPoint where Self: CVarArg {
    func fixedFraction(digits: Int) -> String {
        .init(format: "%.*f", digits, self)
    }
}

If you need more control over your number format (minimum and maximum fraction digits and rounding mode) you can use NumberFormatter:

extension Formatter {
    static let number = NumberFormatter()
}

extension FloatingPoint {
    func fractionDigits(min: Int = 2, max: Int = 2, roundingMode: NumberFormatter.RoundingMode = .halfEven) -> String {
        Formatter.number.minimumFractionDigits = min
        Formatter.number.maximumFractionDigits = max
        Formatter.number.roundingMode = roundingMode
        Formatter.number.numberStyle = .decimal
        return Formatter.number.string(for: self) ?? ""
    }
}

2.12345.fractionDigits()                                    // "2.12"
2.12345.fractionDigits(min: 3, max: 3, roundingMode: .up)   // "2.124"

Can a local variable's memory be accessed outside its scope?

In typical compiler implementations, you can think of the code as "print out the value of the memory block with adress that used to be occupied by a". Also, if you add a new function invocation to a function that constains a local int it's a good chance that the value of a (or the memory address that a used to point to) changes. This happens because the stack will be overwritten with a new frame containing different data.

However, this is undefined behaviour and you should not rely on it to work!

Is it possible to get all arguments of a function as single object inside that function?

You can also convert it to an array if you prefer. If Array generics are available:

var args = Array.slice(arguments)

Otherwise:

var args = Array.prototype.slice.call(arguments);

from Mozilla MDN:

You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example).

Show MySQL host via SQL Command

Maybe

mysql> show processlist;

jQuery - setting the selected value of a select control via its text description

Try

[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )

_x000D_
_x000D_
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
_x000D_
<select id="mySelect">
  <option value="A">Text A</option>
  <option value="B">Text B</option>
  <option value="C">Text C</option>
</select>
_x000D_
_x000D_
_x000D_

Mime type for WOFF fonts?

Reference for adding font mime types to .NET/IIS

via web.config

<system.webServer>
  <staticContent>
     <!-- remove first in case they are defined in IIS already, which would cause a runtime error -->
     <remove fileExtension=".woff" />
     <remove fileExtension=".woff2" />
     <mimeMap fileExtension=".woff" mimeType="font/woff" />
     <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  </staticContent>
</system.webServer>

via IIS Manager

screenshot of adding woff mime types to IIS

Turning multi-line string into single comma-separated

cat data.txt | xargs | sed -e 's/ /, /g'

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

How do I embed PHP code in JavaScript?

We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.

However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.

How to display special characters in PHP

In PHP there is a pretty good function utf8_encode() to solve this issue.

echo utf8_encode("Résumé");

//will output Résumé instead of R?sum?

Check the official PHP page.

Remove category & tag base from WordPress url - without a plugin

updated answer:

other solution:
In wp-includes/rewrite.php file, you'll see the code:
$this->category_structure = $this->front . 'category/'; just copy whole function, put in your functions.php and hook it. just change the above line with:
$this->category_structure = $this->front . '/';

Display loading image while post with ajax

<div id="load" style="display:none"><img src="ajax-loader.gif"/></div>

function getData(p){
        var page=p;
        document.getElementById("load").style.display = "block";  // show the loading message.
        $.ajax({
            url: "loadData.php?id=<? echo $id; ?>",
            type: "POST",
            cache: false,
            data: "&page="+ page,
            success : function(html){
                $(".content").html(html);
        document.getElementById("load").style.display = "none";
            }
        });

CSS3 100vh not constant in mobile browser

I came up with a React component – check it out if you use React or browse the source code if you don't, so you can adapt it to your environment.

It sets the fullscreen div's height to window.innerHeight and then updates it on window resizes.

How can I maintain fragment state when added to the back stack?

Comparing to Apple's UINavigationController and UIViewController, Google does not do well in Android software architecture. And Android's document about Fragment does not help much.

When you enter FragmentB from FragmentA, the existing FragmentA instance is not destroyed. When you press Back in FragmentB and return to FragmentA, we don't create a new FragmentA instance. The existing FragmentA instance's onCreateView() will be called.

The key thing is we should not inflate view again in FragmentA's onCreateView(), because we are using the existing FragmentA's instance. We need to save and reuse the rootView.

The following code works well. It does not only keep fragment state, but also reduces the RAM and CPU load (because we only inflate layout if necessary). I can't believe Google's sample code and document never mention it but always inflate layout.

Version 1(Don't use version 1. Use version 2)

public class FragmentA extends Fragment {
    View _rootView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (_rootView == null) {
            // Inflate the layout for this fragment
            _rootView = inflater.inflate(R.layout.fragment_a, container, false);
            // Find and setup subviews
            _listView = (ListView)_rootView.findViewById(R.id.listView);
            ...
        } else {
            // Do not inflate the layout again.
            // The returned View of onCreateView will be added into the fragment.
            // However it is not allowed to be added twice even if the parent is same.
            // So we must remove _rootView from the existing parent view group
            // (it will be added back).
            ((ViewGroup)_rootView.getParent()).removeView(_rootView);
        }
        return _rootView;
    }
}

------Update on May 3 2005:-------

As the comments mentioned, sometimes _rootView.getParent() is null in onCreateView, which causes the crash. Version 2 removes _rootView in onDestroyView(), as dell116 suggested. Tested on Android 4.0.3, 4.4.4, 5.1.0.

Version 2

public class FragmentA extends Fragment {
    View _rootView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        if (_rootView == null) {
            // Inflate the layout for this fragment
            _rootView = inflater.inflate(R.layout.fragment_a, container, false);
            // Find and setup subviews
            _listView = (ListView)_rootView.findViewById(R.id.listView);
            ...
        } else {
            // Do not inflate the layout again.
            // The returned View of onCreateView will be added into the fragment.
            // However it is not allowed to be added twice even if the parent is same.
            // So we must remove _rootView from the existing parent view group
            // in onDestroyView() (it will be added back).
        }
        return _rootView;
    }

    @Override
    public void onDestroyView() {
        if (_rootView.getParent() != null) {
            ((ViewGroup)_rootView.getParent()).removeView(_rootView);
        }
        super.onDestroyView();
    }
}

WARNING!!!

This is a HACK! Though I am using it in my app, you need to test and read comments carefully.

How to sort a Ruby Hash by number value?

That's not the behavior I'm seeing:

irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
 10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]

Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?

Why do access tokens expire?

In addition to the other responses:

Once obtained, Access Tokens are typically sent along with every request from Clients to protected Resource Servers. This induce a risk for access token stealing and replay (assuming of course that access tokens are of type "Bearer" (as defined in the initial RFC6750).

Examples of those risks, in real life:

  • Resource Servers generally are distributed application servers and typically have lower security levels compared to Authorization Servers (lower SSL/TLS config, less hardening, etc.). Authorization Servers on the other hand are usually considered as critical Security infrastructure and are subject to more severe hardening.

  • Access Tokens may show up in HTTP traces, logs, etc. that are collected legitimately for diagnostic purposes on the Resource Servers or clients. Those traces can be exchanged over public or semi-public places (bug tracers, service-desk, etc.).

  • Backend RS applications can be outsourced to more or less trustworthy third-parties.

The Refresh Token, on the other hand, is typically transmitted only twice over the wires, and always between the client and the Authorization Server: once when obtained by client, and once when used by client during refresh (effectively "expiring" the previous refresh token). This is a drastically limited opportunity for interception and replay.

Last thought, Refresh Tokens offer very little protection, if any, against compromised clients.

Using CSS in Laravel views?

put your css in public folder, then

add this in you blade file

<link rel="stylesheet" type="text/css" href="{{ asset('mystyle.css') }}">

Http 415 Unsupported Media type error with JSON

The reason can be not adding "annotation-driven" in your dispatcher servlet xml file. and also it may be due to not adding as application/json in the headers

Is there a "null coalescing" operator in JavaScript?

Logical nullish assignment, 2020+ solution

A new operator is currently being added to the browsers, ??=. This combines the null coalescing operator ?? with the assignment operator =.

NOTE: This is not common in public browser versions yet. Will update as availability changes.

??= checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Browser Support Sept 2020 - 3.7%

Mozilla Documentation

momentJS date string add 5 days

You can reduce what they said in a few lines of code:

var nowPlusOneDay = moment().add('days', 1);
var nowPlusOneDayStr = nowPlusOneDay.format('YYYY-MM-DD');

alert('nowPlusOneDay Without Format(Unix Date):'+nowPlusOneDay);
alert('nowPlusOneDay Formatted(String):'+nowPlusOneDayStr);

XSLT - How to select XML Attribute by Attribute?

Try this

xsl:variable name="myVarA" select="//DataSet/Data[@Value1='2']/@Value2" />

The '//' will search for DataSet at any depth

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

I suggest that newbies connect a PL2303 to Ubuntu, chmod 777 /dev/ttyUSB0 (file-permissions) and connect to a CuteCom serial terminal. The CuteCom UI is simple \ intuitive. If the PL2303 is continuously broadcasting data, then Cutecom will display data in hex format

Delete all rows in an HTML table

How about this:

When the page first loads, do this:

var myTable = document.getElementById("myTable");
myTable.oldHTML=myTable.innerHTML;

Then when you want to clear the table:

myTable.innerHTML=myTable.oldHTML;

The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

For me it was a missing static keyword in one of the JUnit annotated methods, e.g.:

@AfterClass
public static void cleanUp() {
    // ...
}

Accessing certain pixel RGB value in openCV

uchar * value = img2.data; //Pointer to the first pixel data ,it's return array in all values 
int r = 2;
for (size_t i = 0; i < img2.cols* (img2.rows * img2.channels()); i++)
{

        if (r > 2) r = 0;

        if (r == 0) value[i] = 0;
        if (r == 1)value[i] =  0;
        if (r == 2)value[i] = 255;

        r++;
}

Programmatically add custom event in the iPhone Calendar

Remember to set the endDate to the created event, it is mandatory.

Otherwise it will fail (almost silently) with this error:

"Error Domain=EKErrorDomain Code=3 "No end date has been set." UserInfo={NSLocalizedDescription=No end date has been set.}"

The complete working code for me is:

EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
    if (!granted) { return; }
    EKEvent *calendarEvent = [EKEvent eventWithEventStore:store];
    calendarEvent.title = [NSString stringWithFormat:@"CEmprendedor: %@", _event.name];
    calendarEvent.startDate = _event.date;
    // 5 hours of duration, we must add the duration of the event to the API
    NSDate *endDate = [_event.date dateByAddingTimeInterval:60*60*5];
    calendarEvent.endDate = endDate;
    calendarEvent.calendar = [store defaultCalendarForNewEvents];
    NSError *err = nil;
    [store saveEvent:calendarEvent span:EKSpanThisEvent commit:YES error:&err];
    self.savedEventId = calendarEvent.eventIdentifier;  //saving the calendar event id to possibly deleted them
}];