Programs & Examples On #Mobile application

Refers to a software application that is designed to run on a hand-held device, such as a smartphone, pda, or tablet.

Convert HTML5 into standalone Android App

You could use PhoneGap.

http://phonegap.com/

http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

How can I generate an apk that can run without server with react-native?

You should just use android studio for this process. It is just simpler. But first run this command in your react native app directory:

For Newer version of react-native(e.g. react native 0.49.0 & so on...)

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

For Older Version of react-native (0.49.0 & below)

react-native bundle --platform android --dev false --entry-file index.android.js   --bundle-output android/app/src/main/assets/index.android.bundle   --assets-dest android/app/src/main/res/

Then Use android studio to open the 'android' folder in you react native app directory, it will ask to upgrade gradle and some other stuff. go to build-> Generate signed APK and follow the instructions from there. It's really straight forward.

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Get startup type of Windows service using PowerShell

WMI is the way to do this.

Get-WmiObject -Query "Select StartMode From Win32_Service Where Name='winmgmt'"

Or

Get-WmiObject -Class Win32_Service -Property StartMode -Filter "Name='Winmgmt'"

jQuery How do you get an image to fade in on load?

You have a syntax error on line 5:

$('#logo').hide();.fadeIn(3000);

Should be:

$('#logo').hide().fadeIn(3000);

How do you remove an array element in a foreach loop?

foreach($display_related_tags as $key => $tag_name)
{
    if($tag_name == $found_tag['name'])
        unset($display_related_tags[$key];
}

Make copy of an array

All solution that call length from array, add your code redundant null checkersconsider example:

int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();

//What if array a comes as local parameter? You need to use null check:

public void someMethod(int[] a) {
    if (a!=null) {
        int[] b = Arrays.copyOf(a, a.length);
        int[] c = a.clone();
    }
}

I recommend you not inventing the wheel and use utility class where all necessary checks have already performed. Consider ArrayUtils from apache commons. You code become shorter:

public void someMethod(int[] a) {
    int[] b = ArrayUtils.clone(a);
}

Apache commons you can find there

How to use a variable inside a regular expression?

more example

I have configus.yml with flows files

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

in python code I use

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

Django - after login, redirect user to his custom page --> mysite.com/username

You can authenticate and log the user in as stated here: https://docs.djangoproject.com/en/dev/topics/auth/default/#how-to-log-a-user-in

This will give you access to the User object from which you can get the username and then do a HttpResponseRedirect to the custom URL.

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

How do I correctly clone a JavaScript object?

let clone = Object.assign( Object.create( Object.getPrototypeOf(obj)), obj)

ES6 solution if you want to (shallow) clone a class instance and not just a property object.

Equal height rows in a flex container

You can accomplish that now with display: grid:

_x000D_
_x000D_
.list {_x000D_
  display: grid;_x000D_
  overflow: hidden;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-auto-rows: 1fr;_x000D_
  grid-column-gap: 5px;_x000D_
  grid-row-gap: 5px;_x000D_
  max-width: 500px;_x000D_
}_x000D_
.list-item {_x000D_
  background-color: #ccc;_x000D_
  display: flex;_x000D_
  padding: 0.5em;_x000D_
  margin-bottom: 20px;_x000D_
}_x000D_
.list-content {_x000D_
  width: 100%;_x000D_
}
_x000D_
<ul class="list">_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h2>box 1</h2>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
    </div>_x000D_
  </li>_x000D_
_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h3>box 2</h3>_x000D_
      <p>Lorem ipsum dolor</p>_x000D_
    </div>_x000D_
  </li>_x000D_
  <li class="list-item">_x000D_
    <div class="list-content">_x000D_
      <h1>h1</h1>_x000D_
    </div>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Although the grid itself is not flexbox, it behaves very similar to a flexbox container, and the items inside the grid can be flex.

The grid layout is also very handy in the case you want responsive grids. That is, if you want the grid to have a different number of columns per row you can then just change grid-template-columns:

grid-template-columns: repeat(1, 1fr); // 1 column
grid-template-columns: repeat(2, 1fr); // 2 columns
grid-template-columns: repeat(3, 1fr); // 3 columns

and so on...

You can mix it with media queries and change according to the size of the page.

Sadly there is still no support for container queries / element queries in the browsers (out of the box) to make it work well with changing the number of columns according to the container size, not to the page size (this would be great to use with reusable webcomponents).

More information about the grid layout:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

Support of the Grid Layout accross browsers:

https://caniuse.com/#feat=css-grid

How to set background color of a button in Java GUI?

Use the setBackground method to set the background and setForeground to change the colour of your text. Note however, that putting grey text over a black background might make your text a bit tough to read.

How to convert a byte array to its numeric value (Java)?

public static long byteArrayToLong(byte[] bytes) {
    return ((long) (bytes[0]) << 56)
            + (((long) bytes[1] & 0xFF) << 48)
            + ((long) (bytes[2] & 0xFF) << 40)
            + ((long) (bytes[3] & 0xFF) << 32)
            + ((long) (bytes[4] & 0xFF) << 24)
            + ((bytes[5] & 0xFF) << 16)
            + ((bytes[6] & 0xFF) << 8)
            + (bytes[7] & 0xFF);
}

convert bytes array (long is 8 bytes) to long

What is the C# equivalent of friend?

The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:

class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}

or if you prefer to put the Inner class in another file:

Outer.cs
partial class Outer
{
}


Inner.cs
partial class Outer
{
    class Inner
    {
       // This class can access Outer's private members
    }
}

test if display = none

Use like this:

if( $('#foo').is(':visible') ) {
    // it's visible, do something
}
else {
    // it's not visible so do something else
}

Hope it helps!

Cannot read property 'push' of undefined when combining arrays

answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.

How do I POST urlencoded form data with $http without jQuery?

you need to post plain javascript object, nothing else

           var request = $http({
                method: "post",
                url: "process.cfm",
                transformRequest: transformRequestAsFormPost,
                data: { id: 4, name: "Kim" }
            });

            request.success(
                function( data ) {
                    $scope.localData = data;
                }
            );

if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side

header('HTTP/1.0 404 Not Found'); not doing anything

Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.

How to dismiss ViewController in Swift?

  1. embed the View you want to dismiss in a NavigationController
  2. add a BarButton with "Done" as Identifier
  3. invoke the Assistant Editor with the Done button selected
  4. create an IBAction for this button
  5. add this line into the brackets:

    self.dismissViewControllerAnimated(true, completion: nil)
    

How can I use custom fonts on a website?

CSS lets you use custom fonts, downloadable fonts on your website. You can download the font of your preference, let’s say myfont.ttf, and upload it to your remote server where your blog or website is hosted.

@font-face {
    font-family: myfont;
    src: url('myfont.ttf');
}

Get all dates between two dates in SQL Server

My first suggestion would be use your calendar table, if you don't have one, then create one. They are very useful. Your query is then as simple as:

DECLARE @MinDate DATE = '20140101',
        @MaxDate DATE = '20140106';

SELECT  Date
FROM    dbo.Calendar
WHERE   Date >= @MinDate
AND     Date < @MaxDate;

If you don't want to, or can't create a calendar table you can still do this on the fly without a recursive CTE:

DECLARE @MinDate DATE = '20140101',
        @MaxDate DATE = '20140106';

SELECT  TOP (DATEDIFF(DAY, @MinDate, @MaxDate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @MinDate)
FROM    sys.all_objects a
        CROSS JOIN sys.all_objects b;

For further reading on this see:

With regard to then using this sequence of dates in a cursor, I would really recommend you find another way. There is usually a set based alternative that will perform much better.

So with your data:

  date   | it_cd | qty 
24-04-14 |  i-1  | 10 
26-04-14 |  i-1  | 20

To get the quantity on 28-04-2014 (which I gather is your requirement), you don't actually need any of the above, you can simply use:

SELECT  TOP 1 date, it_cd, qty 
FROM    T
WHERE   it_cd = 'i-1'
AND     Date <= '20140428'
ORDER BY Date DESC;

If you don't want it for a particular item:

SELECT  date, it_cd, qty 
FROM    (   SELECT  date, 
                    it_cd, 
                    qty, 
                    RowNumber = ROW_NUMBER() OVER(PARTITION BY ic_id 
                                                    ORDER BY date DESC)
            FROM    T
            WHERE   Date  <= '20140428'
        ) T
WHERE   RowNumber = 1;

jquery simple image slideshow tutorial

This is by far the easiest example I have found on the net. http://jonraasch.com/blog/a-simple-jquery-slideshow

Summaring the example, this is what you need to do a slideshow:

HTML:

<div id="slideshow">
    <img src="img1.jpg" style="position:absolute;" class="active" />
    <img src="img2.jpg" style="position:absolute;" />
    <img src="img3.jpg" style="position:absolute;" />
</div>

Position absolute is used to put an each image over the other.

CSS

<style type="text/css">
    .active{
        z-index:99;
    }
</style>

The image that has the class="active" will appear over the others, the class=active property will change with the following Jquery code.

<script>
    function slideSwitch() {
        var $active = $('div#slideshow IMG.active');
        var $next = $active.next();    

        $next.addClass('active');

        $active.removeClass('active');
    }

    $(function() {
        setInterval( "slideSwitch()", 5000 );
    });
</script>

If you want to go further with slideshows I suggest you to have a look at the link above (to see animated oppacity changes - 2n example) or at other more complex slideshows tutorials.

How to determine the version of android SDK installed in computer?

I develope cross-plateform mobile applications Using Xamarin integrated in Visual Studio 2017.

I prefer to install and check all details of Android SDK from within the Visual Studio 2017. This can be found under the menu TOOLS -> Android -> Android SDK Manager.

Bellow is the Visual representation of the Adroid SDK Manager.enter image description here

Python - difference between two strings

I like the ndiff answer, but if you want to spit it all into a list of only the changes, you could do something like:

import difflib

case_a = 'afrykbnerskojezyczny'
case_b = 'afrykanerskojezycznym'

output_list = [li for li in difflib.ndiff(case_a, case_b) if li[0] != ' ']

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

put this in your "head" of your index.html

 <style>
  html body{
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    margin: 0;
  }
  </style>

Bootstrap 4 responsive tables won't take up 100% width

Create responsive tables by wrapping any .table with .table-responsive{-sm|-md|-lg|-xl}, making the table scroll horizontally at each max-width breakpoint of up to (but not including) 576px, 768px, 992px, and 1120px, respectively.

just wrap table with .table-responsive{-sm|-md|-lg|-xl}

for example

<div class="table-responsive-md">
    <table class="table">
    </table>
</div>

bootstrap 4 tables

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How do I include inline JavaScript in Haml?

I'm using fileupload-jquery in haml. The original js is below:

_x000D_
_x000D_
<!-- The template to display files available for download -->_x000D_
<script id="template-download" type="text/x-tmpl">_x000D_
  {% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
    <tr class="template-download fade">_x000D_
      {% if (file.error) { %}_x000D_
        <td></td>_x000D_
        <td class="name"><span>{%=file.name%}</span></td>_x000D_
        <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
        <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
        {% } else { %}_x000D_
        <td class="preview">{% if (file.thumbnail_url) { %}_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
          {% } %}</td>_x000D_
        <td class="name">_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
        </td>_x000D_
        <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
        <td colspan="2"></td>_x000D_
        {% } %}_x000D_
      <td class="delete">_x000D_
        <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
          <i class="icon-trash icon-white"></i>_x000D_
          <span>{%=locale.fileupload.destroy%}</span>_x000D_
        </button>_x000D_
        <input type="checkbox" name="delete" value="1">_x000D_
      </td>_x000D_
    </tr>_x000D_
    {% } %}_x000D_
</script>
_x000D_
_x000D_
_x000D_

At first I used the :cdata to convert (from html2haml), it doesn't work properly (Delete button can't remove relevant component in callback).

_x000D_
_x000D_
<script id='template-download' type='text/x-tmpl'>_x000D_
      <![CDATA[_x000D_
          {% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
          <tr class="template-download fade">_x000D_
          {% if (file.error) { %}_x000D_
          <td></td>_x000D_
          <td class="name"><span>{%=file.name%}</span></td>_x000D_
          <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
          <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
          {% } else { %}_x000D_
          <td class="preview">{% if (file.thumbnail_url) { %}_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
          {% } %}</td>_x000D_
          <td class="name">_x000D_
          <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
          </td>_x000D_
          <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
          <td colspan="2"></td>_x000D_
          {% } %}_x000D_
          <td class="delete">_x000D_
          <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
          <i class="icon-trash icon-white"></i>_x000D_
          <span>{%=locale.fileupload.destroy%}</span>_x000D_
          </button>_x000D_
          <input type="checkbox" name="delete" value="1">_x000D_
          </td>_x000D_
          </tr>_x000D_
          {% } %}_x000D_
      ]]>_x000D_
    </script>
_x000D_
_x000D_
_x000D_

So I use :plain filter:

_x000D_
_x000D_
%script#template-download{:type => "text/x-tmpl"}_x000D_
  :plain_x000D_
    {% for (var i=0, file; file=o.files[i]; i++) { %}_x000D_
    <tr class="template-download fade">_x000D_
    {% if (file.error) { %}_x000D_
    <td></td>_x000D_
    <td class="name"><span>{%=file.name%}</span></td>_x000D_
    <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
    <td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>_x000D_
    {% } else { %}_x000D_
    <td class="preview">{% if (file.thumbnail_url) { %}_x000D_
    <a href="{%=file.url%}" title="{%=file.name%}" rel="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>_x000D_
    {% } %}</td>_x000D_
    <td class="name">_x000D_
    <a href="{%=file.url%}" title="{%=file.name%}" rel="{%=file.thumbnail_url&&'gallery'%}" download="{%=file.name%}">{%=file.name%}</a>_x000D_
    </td>_x000D_
    <td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>_x000D_
    <td colspan="2"></td>_x000D_
    {% } %}_x000D_
    <td class="delete">_x000D_
    <button class="btn btn-danger" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}">_x000D_
    <i class="icon-trash icon-white"></i>_x000D_
    <span>{%=locale.fileupload.destroy%}</span>_x000D_
    </button>_x000D_
    <input type="checkbox" name="delete" value="1">_x000D_
    </td>_x000D_
    </tr>_x000D_
    {% } %}
_x000D_
_x000D_
_x000D_

The converted result is exactly the same as the original.

So :plain filter in this senario fits my need.

:plain Does not parse the filtered text. This is useful for large blocks of text without HTML tags, when you don’t want lines starting with . or - to be parsed.

For more detail, please refer to haml.info

How do you list all triggers in a MySQL database?

I hope following code will give you more information.

select * from information_schema.triggers where 
information_schema.triggers.trigger_schema like '%your_db_name%'

This will give you total 22 Columns in MySQL version: 5.5.27 and Above

TRIGGER_CATALOG 
TRIGGER_SCHEMA
TRIGGER_NAME
EVENT_MANIPULATION
EVENT_OBJECT_CATALOG
EVENT_OBJECT_SCHEMA 
EVENT_OBJECT_TABLE
ACTION_ORDER
ACTION_CONDITION
ACTION_STATEMENT
ACTION_ORIENTATION
ACTION_TIMING
ACTION_REFERENCE_OLD_TABLE
ACTION_REFERENCE_NEW_TABLE
ACTION_REFERENCE_OLD_ROW
ACTION_REFERENCE_NEW_ROW
CREATED 
SQL_MODE
DEFINER 
CHARACTER_SET_CLIENT
COLLATION_CONNECTION
DATABASE_COLLATION

Can I nest a <button> element inside an <a> using HTML5?

It is illegal in HTML5 to embed a button element inside a link.

Better to use CSS on the default and :active (pressed) states:

_x000D_
_x000D_
body{background-color:#F0F0F0} /* JUST TO MAKE THE BORDER STAND OUT */_x000D_
a.Button{padding:.1em .4em;color:#0000D0;background-color:#E0E0E0;font:normal 80% sans-serif;font-weight:700;border:2px #606060 solid;text-decoration:none}_x000D_
a.Button:not(:active){border-left-color:#FFFFFF;border-top-color:#FFFFFF}_x000D_
a.Button:active{border-right-color:#FFFFFF;border-bottom-color:#FFFFFF}
_x000D_
<p><a class="Button" href="www.stackoverflow.com">Click me<a>
_x000D_
_x000D_
_x000D_

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

Conversion from 12 hours time to 24 hours time in java

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); 

provided by Bart Kiers answer should be replaced with somethig like

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I get the error in another situation, and here are the problem and the solution:

I have 2 classes derived from a same base class named LevledItem:

public partial class Team : LeveledItem
{
   //Everything is ok here!
}
public partial class Story : LeveledItem
{
   //Everything is ok here!
}

But in their DbContext, I copied some code but forget to change one of the class name:

public class MFCTeamDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Other codes here
        modelBuilder.Entity<LeveledItem>()
            .Map<Team>(m => m.Requires("Type").HasValue(ItemType.Team));
    }

public class ProductBacklogDbContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Other codes here
        modelBuilder.Entity<LeveledItem>()
            .Map<Team>(m => m.Requires("Type").HasValue(ItemType.Story));
    }

Yes, the second Map< Team> should be Map< Story>. And it cost me half a day to figure it out!

How to retrieve unique count of a field using Kibana + Elastic Search

Using Aggs u can easily do that. Writing down query for now.

GET index/_search
{
  "size":0,
  "aggs": {
    "source": {
      "terms": {
        "field": "field",
        "size": 100000
      }
    }
  }
 }

This would return the different values of field with there doc counts.

Paging UICollectionView by cells, not screen

This is a straight way to do this.

The case is simple, but finally quite common ( typical thumbnails scroller with fixed cell size and fixed gap between cells )

var itemCellSize: CGSize = <your cell size>
var itemCellsGap: CGFloat = <gap in between>

override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    let pageWidth = (itemCellSize.width + itemCellsGap)
    let itemIndex = (targetContentOffset.pointee.x) / pageWidth
    targetContentOffset.pointee.x = round(itemIndex) * pageWidth - (itemCellsGap / 2)
}

// CollectionViewFlowLayoutDelegate

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return itemCellSize
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return itemCellsGap
}

Note that there is no reason to call a scrollToOffset or dive into layouts. The native scrolling behaviour already does everything.

Cheers All :)

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

Easy! The default should be the first option. Done! That would lead you to unobtrusive JavaScript, because JavaScript isn't needed :)

Unobtrusive JavaScript

How to turn a String into a JavaScript function call?

Here is a more generic way to do the same, while supporting scopes :

// Get function from string, with or without scopes (by Nicolas Gauthier)
window.getFunctionFromString = function(string)
{
    var scope = window;
    var scopeSplit = string.split('.');
    for (i = 0; i < scopeSplit.length - 1; i++)
    {
        scope = scope[scopeSplit[i]];

        if (scope == undefined) return;
    }

    return scope[scopeSplit[scopeSplit.length - 1]];
}

Hope it can help some people out.

border-radius not working

Your problem is unrelated to how you have set border-radius. Fire up Chrome and hit Ctrl+Shift+j and inspect the element. Uncheck width and the border will have curved corners.

How to retrieve Jenkins build parameters using the Groovy API?

I've just got this working, so specifically, using the Groovy Postbuild plugin, you can do the following:

def paramText
def actionList = manager.build.getActions(hudson.model.ParametersAction)
if (actionList.size() != 0)
{
  def pA = actionList.get(0)
  paramText = pA.createVariableResolver(manager.build).resolve("MY_PARAM_NAME")
}

Pythonic way to find maximum value and its index in a list?

There are many options, for example:

import operator
index, value = max(enumerate(my_list), key=operator.itemgetter(1))

split string only on first instance of specified character

Use capturing parentheses:

"good_luck_buddy".split(/_(.+)/)[1]
"luck_buddy"

They are defined as

If separator contains capturing parentheses, matched results are returned in the array.

So in this case we want to split at _.+ (i.e. split separator being a sub string starting with _) but also let the result contain some part of our separator (i.e. everything after _).

In this example our separator (matching _(.+)) is _luck_buddy and the captured group (within the separator) is lucky_buddy. Without the capturing parenthesis the luck_buddy (matching .+) would've not been included in the result array as it is the case with simple split that separators are not included in the result.

Check empty string in Swift?

public extension Swift.Optional {
    
    func nonEmptyValue<T>(fallback: T) -> T {
        
        if let stringValue = self as? String, stringValue.isEmpty {
            return fallback
        }
        
        if let value = self as? T {
            return value
        } else {
            return fallback
        }
    }
}

downloading all the files in a directory with cURL

If you're not bound to curl, you might want to use wget in recursive mode but restricting it to one level of recursion, try the following;

wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
  • --no-parent : Do not ever ascend to the parent directory when retrieving recursively.
  • --level=depth : Specify recursion maximum depth level depth. The default maximum depth is five layers.
  • --no-directories : Do not create a hierarchy of directories when retrieving recursively.

Convert HH:MM:SS string to seconds only in javascript

You can do this dynamically - in case you encounter not only: HH:mm:ss, but also, mm:ss, or even ss alone.

var str = '12:99:07';
var times = str.split(":");
times.reverse();
var x = times.length, y = 0, z;
for (var i = 0; i < x; i++) {
    z = times[i] * Math.pow(60, i);
    y += z;
}
console.log(y);

postgres: upgrade a user to be a superuser?

Run this Command

alter user myuser with superuser;

If you want to see the permission to a user run following command

\du

Changing the space between each item in Bootstrap navbar

Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.

If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.

In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.

@media (min-width: 992px){
    .navbar li {
        margin-left : 1em;
        margin-right : 1em;
    }
}

How can I sort an ArrayList of Strings in Java?

Collections.sort(teamsName.subList(1, teamsName.size()));

The code above will reflect the actual sublist of your original list sorted.

Java Security: Illegal key size or default parameters?

With Java 9, Java 8u161, Java 7u171 and Java 6u181 the limitation is now disabled by default. See issue in Java Bug Database.


Beginning with Java 8u151 you can disable the limitation programmatically.

In older releases, JCE jurisdiction files had to be downloaded and installed separately to allow unlimited cryptography to be used by the JDK. The download and install steps are no longer necessary.

Instead you can now invoke the following line before first use of JCE classes (i.e. preferably right after application start):

Security.setProperty("crypto.policy", "unlimited");

What is the difference between onBlur and onChange attribute in HTML?

The onBlur event is fired when you have moved away from an object without necessarily having changed its value.

The onChange event is only called when you have changed the value of the field and it loses focus.

You might want to take a look at quirksmode's intro to events. This is a great place to get info on what's going on in your browser when you interact with it. His book is good too.

jQuery: How to capture the TAB keypress within a Textbox

Working example in jQuery 1.9:

$('body').on('keydown', '#textbox', function(e) {
    if (e.which == 9) {
        e.preventDefault();
        // do your code
    }
});

How do I concatenate two lists in Python?

You can use sets to obtain merged list of unique values

mergedlist = list(set(listone + listtwo))

assignment operator overloading in c++

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

Picking a random element from a set

In C#

        Random random = new Random((int)DateTime.Now.Ticks);

        OrderedDictionary od = new OrderedDictionary();

        od.Add("abc", 1);
        od.Add("def", 2);
        od.Add("ghi", 3);
        od.Add("jkl", 4);


        int randomIndex = random.Next(od.Count);

        Console.WriteLine(od[randomIndex]);

        // Can access via index or key value:
        Console.WriteLine(od[1]);
        Console.WriteLine(od["def"]);

How to install mcrypt extension in xampp

First, you should download the suitable version for your system from here: https://pecl.php.net/package/mcrypt/1.0.3/windows

Then, you should copy php_mcrypt.dll to ../xampp/php/ext/ and enable the extension by adding extension=mcrypt to your xampp/php/php.ini file.

Multiple conditions in a C 'for' loop

Of course it is right what you say at the beginning, and C logical operator && and || are what you usually use to "connect" conditions (expressions that can be evaluated as true or false); the comma operator is not a logical operator and its use in that example makes no sense, as explained by other users. You can use it e.g. to "concatenate" statements in the for itself: you can initialize and update j altogether with i; or use the comma operator in other ways

#include <stdio.h>

int main(void)  // as std wants
{
  int i, j;

  // init both i and j; condition, we suppose && is the "original"
  // intention; update i and j
  for(i=0, j=2; j>=0 && i<=5; i++, j--)
  {
       printf("%d ", i+j);
  }
  return 0;        
}

JavaScript click event listener on class

You can use the code below:

document.body.addEventListener('click', function (evt) {
    if (evt.target.className === 'databox') {
        alert(this)
    }
}, false);

How can I query for null values in entity framework?

If it is a nullable type, maybe try use the HasValue property?

var result = from entry in table
                 where !entry.something.HasValue
                 select entry;

Don't have any EF to test on here though... just a suggestion =)

Why does make think the target is up to date?

EDIT: This only applies to some versions of make - you should check your man page.

You can also pass the -B flag to make. As per the man page, this does:

-B, --always-make Unconditionally make all targets.

So make -B test would solve your problem if you were in a situation where you don't want to edit the Makefile or change the name of your test folder.

How to pass values across the pages in ASP.net without using Session

You can pass values from one page to another by followings..

Response.Redirect
Cookies
Application Variables
HttpContext

Response.Redirect

SET :

Response.Redirect("Defaultaspx?Name=Pandian");

GET :

string Name = Request.QueryString["Name"];

Cookies

SET :

HttpCookie cookName = new HttpCookie("Name");
cookName.Value = "Pandian"; 

GET :

string name = Request.Cookies["Name"].Value;

Application Variables

SET :

Application["Name"] = "pandian";

GET :

string Name = Application["Name"].ToString();

Refer the full content here : Pass values from one to another

How to configure the web.config to allow requests of any length

If you run into this issue when running an IIS 8.5 web server you can use the following method.

First, find the "Request Filtering" module in the IIS site you are working on, then double click it...

enter image description here

Next, you need to right click in the white area shown below then click the context menu option called "Edit Feature Settings".

enter image description here

Then the last thing to do is change the "Maximum query string (Bytes)" value from 2048 to something more appropriate such as 5000 for your needs.

enter image description here

CSS endless rotation animation

_x000D_
_x000D_
@-webkit-keyframes rotating /* Safari and Chrome */ {_x000D_
  from {_x000D_
    -webkit-transform: rotate(0deg);_x000D_
    -o-transform: rotate(0deg);_x000D_
    transform: rotate(0deg);_x000D_
  }_x000D_
  to {_x000D_
    -webkit-transform: rotate(360deg);_x000D_
    -o-transform: rotate(360deg);_x000D_
    transform: rotate(360deg);_x000D_
  }_x000D_
}_x000D_
@keyframes rotating {_x000D_
  from {_x000D_
    -ms-transform: rotate(0deg);_x000D_
    -moz-transform: rotate(0deg);_x000D_
    -webkit-transform: rotate(0deg);_x000D_
    -o-transform: rotate(0deg);_x000D_
    transform: rotate(0deg);_x000D_
  }_x000D_
  to {_x000D_
    -ms-transform: rotate(360deg);_x000D_
    -moz-transform: rotate(360deg);_x000D_
    -webkit-transform: rotate(360deg);_x000D_
    -o-transform: rotate(360deg);_x000D_
    transform: rotate(360deg);_x000D_
  }_x000D_
}_x000D_
.rotating {_x000D_
  -webkit-animation: rotating 2s linear infinite;_x000D_
  -moz-animation: rotating 2s linear infinite;_x000D_
  -ms-animation: rotating 2s linear infinite;_x000D_
  -o-animation: rotating 2s linear infinite;_x000D_
  animation: rotating 2s linear infinite;_x000D_
}
_x000D_
<div _x000D_
  class="rotating"_x000D_
  style="width: 100px; height: 100px; line-height: 100px; text-align: center;" _x000D_
 >Rotate</div>
_x000D_
_x000D_
_x000D_

How to check if the request is an AJAX request with PHP

There is no sure-fire way of knowing that a request was made via Ajax. You can never trust data coming from the client. You could use a couple of different methods but they can be easily overcome by spoofing.

How to save a Seaborn plot into a file

The suggested solutions are incompatible with Seaborn 0.8.1

giving the following errors because the Seaborn interface has changed:

AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure

AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function

The following calls allow you to access the figure (Seaborn 0.8.1 compatible):

swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...) 

as seen previously in this answer.

UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by

fig = myGridPlotObject.fig

Like previously suggested in other posts in this thread.

Is log(n!) = T(n·log(n))?

For lower bound,

lg(n!) = lg(n)+lg(n-1)+...+lg(n/2)+...+lg2+lg1
       >= lg(n/2)+lg(n/2)+...+lg(n/2)+ ((n-1)/2) lg 2 (leave last term lg1(=0); replace first n/2 terms as lg(n/2); replace last (n-1)/2 terms as lg2 which will make cancellation easier later)
       = n/2 lg(n/2) + (n/2) lg 2 - 1/2 lg 2
       = n/2 lg n - (n/2)(lg 2) + n/2 - 1/2
       = n/2 lg n - 1/2

lg(n!) >= (1/2) (n lg n - 1)

Combining both bounds :

1/2 (n lg n - 1) <= lg(n!) <= n lg n

By choosing lower bound constant greater than (1/2) we can compensate for -1 inside the bracket.

Thus lg(n!) = Theta(n lg n)

'git status' shows changed files, but 'git diff' doesn't

I stumbled upon this problem again. But this time it occurred for a different reason. I had copied files into the repo to overwrite the previous versions. Now I can see the files are modified but diff doesn't return the diffs.

For example, I have a mainpage.xaml file. In File Explorer I pasted a new mainpage.xaml file over the one in my current repo. I did the work on another machine and just pasted the file here.
git shows modified

The file shows modified, but when I run git diff, it will not show the changes. It's probably because the fileinfo on the file has changed and git knows that it isn't really the same file. Interesting.

git diff shows nothing

You can see that when I run diff on the file it shows nothing, just returns the prompt.

ORDER BY the IN value list

To do this, I think you should probably have an additional "ORDER" table which defines the mapping of IDs to order (effectively doing what your response to your own question said), which you can then use as an additional column on your select which you can then sort on.

In that way, you explicitly describe the ordering you desire in the database, where it should be.

How to draw border on just one side of a linear layout?

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" >
        <shape>
            <solid
                android:color="#f28b24" />
            <stroke
                android:width="1dp"
                android:color="#f28b24" />
            <corners
                android:radius="0dp"/>
            <padding
                android:left="0dp"
                android:top="0dp"
                android:right="0dp"
                android:bottom="0dp" />
        </shape>
    </item>
    <item>
        <shape>
            <gradient
                android:startColor="#f28b24"
                android:endColor="#f28b24"
                android:angle="270" />
            <stroke
                android:width="0dp"
                android:color="#f28b24" />
            <corners
                android:bottomLeftRadius="8dp"
                android:bottomRightRadius="0dp"
                android:topLeftRadius="0dp"
                android:topRightRadius="0dp"/>
            <padding
                android:left="10dp"
                android:top="10dp"
                android:right="10dp"
                android:bottom="10dp" />
        </shape>
    </item>
</selector>

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

Exception.Message vs Exception.ToString()

Exception.Message contains only the message (doh) associated with the exception. Example:

Object reference not set to an instance of an object

The Exception.ToString() method will give a much more verbose output, containing the exception type, the message (from before), a stack trace, and all of these things again for nested/inner exceptions. More precisely, the method returns the following:

ToString returns a representation of the current exception that is intended to be understood by humans. Where the exception contains culture-sensitive data, the string representation returned by ToString is required to take into account the current system culture. Although there are no exact requirements for the format of the returned string, it should attempt to reflect the value of the object as perceived by the user.

The default implementation of ToString obtains the name of the class that threw the current exception, the message, the result of calling ToString on the inner exception, and the result of calling Environment.StackTrace. If any of these members is a null reference (Nothing in Visual Basic), its value is not included in the returned string.

If there is no error message or if it is an empty string (""), then no error message is returned. The name of the inner exception and the stack trace are returned only if they are not a null reference (Nothing in Visual Basic).

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

How do I show multiple recaptchas on a single page?

I have contact form in footer that always displays and also some pages, like Create Account, can have captcha too, so it's dynamically and I'm using next way with jQuery:

html:

<div class="g-recaptcha" id="g-recaptcha"></div>

<div class="g-recaptcha" id="g-recaptcha-footer"></div>

javascript

<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit&hl=en"></script>
<script type="text/javascript">
  var CaptchaCallback = function(){        
      $('.g-recaptcha').each(function(){
        grecaptcha.render(this,{'sitekey' : 'your_site_key'});
      })
  };
</script>

offsetting an html anchor to adjust for fixed header

FWIW this worked for me:

[id]::before {
  content: '';
  display: block;
  height:      75px;
  margin-top: -75px;
  visibility: hidden;
}

Spring profiles and testing

public class LoginTest extends BaseTest {
    @Test
    public void exampleTest( ){ 
        // Test
    }
}

Inherits from a base test class (this example is testng rather than jUnit, but the ActiveProfiles is the same):

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }

MyActiveProfileResolver can contain any logic required to determine which profile to use:

public class MyActiveProfileResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        // This can contain any custom logic to determine which profiles to use
        return new String[] { "exampleProfile" };
    }
}

This sets the profile which is then used to resolve dependencies required by the test.

How to construct a set out of list items in python?

You can also use list comprehension to create set.

s = {i for i in range(5)}

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

Django optional url parameters

Thought I'd add a bit to the answer.

If you have multiple URL definitions then you'll have to name each of them separately. So you lose the flexibility when calling reverse since one reverse will expect a parameter while the other won't.

Another way to use regex to accommodate the optional parameter:

r'^project_config/(?P<product>\w+)/((?P<project_id>\w+)/)?$'

How to preserve insertion order in HashMap?

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

How to get function parameter names/values dynamically?

I've tried doing this before, but never found a praticial way to get it done. I ended up passing in an object instead and then looping through it.

//define like
function test(args) {
    for(var item in args) {
        alert(item);
        alert(args[item]);
    }
}

//then used like
test({
    name:"Joe",
    age:40,
    admin:bool
});

C# JSON Serialization of Dictionary into {key:value, ...} instead of {key:key, value:value, ...}

I'm using out of the box MVC4 with this code (note the two parameters inside ToDictionary)

 var result = new JsonResult()
 {
     Data = new
     {
         partials = GetPartials(data.Partials).ToDictionary(x => x.Key, y=> y.Value)
     }
 };

I get what's expected:

{"partials":{"cartSummary":"\u003cb\u003eCART SUMMARY\u003c/b\u003e"}}

Important: WebAPI in MVC4 uses JSON.NET serialization out of the box, but the standard web JsonResult action result doesn't. Therefore I recommend using a custom ActionResult to force JSON.NET serialization. You can also get nice formatting

Here's a simple actionresult JsonNetResult

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

You'll see the difference (and can make sure you're using the right one) when serializing a date:

Microsoft way:

 {"wireTime":"\/Date(1355627201572)\/"}

JSON.NET way:

 {"wireTime":"2012-12-15T19:07:03.5247384-08:00"}

Java 8 Lambda Stream forEach with multiple statements

You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()):

entryList.forEach(e->e.setTempId(tempId));

List<Entry> updatedEntries = entryList.stream()
  .map(e->entityManager.update(entry, entry.getId()))
  .collect(toList());

Convert ASCII number to ASCII Character in C

If i is the int, then

char c = i;

makes it a char. You might want to add a check that the value is <128 if it comes from an untrusted source. This is best done with isascii from <ctype.h>, if available on your system (see @Steve Jessop's comment to this answer).

UnsatisfiedDependencyException: Error creating bean with name

Just add @Service annotation to top of the service class

ArrayList of String Arrays

List<String[]> addresses = new ArrayList<String[]>();
String[] addressesArr  = new String[3];

addressesArr[0] = "zero";
addressesArr[1] = "one";
addressesArr[2] = "two";

addresses.add(addressesArr);

Alternating Row Colors in Bootstrap 3 - No Table

I was having trouble coloring rows in table using bootstrap table-striped class then realized delete table-striped class and do this in css file

tr:nth-of-type(odd)
{  
background-color: red;
}
tr:nth-of-type(even)
{  
background-color: blue;
}

The bootstrap table-striped class will over ride your selectors.

iloc giving 'IndexError: single positional indexer is out-of-bounds'

This happens when you index a row/column with a number that is larger than the dimensions of your dataframe. For instance, getting the eleventh column when you have only three.

import pandas as pd

df = pd.DataFrame({'Name': ['Mark', 'Laura', 'Adam', 'Roger', 'Anna'],
                   'City': ['Lisbon', 'Montreal', 'Lisbon', 'Berlin', 'Glasgow'],
                   'Car': ['Tesla', 'Audi', 'Porsche', 'Ford', 'Honda']})

You have 5 rows and three columns:

    Name      City      Car
0   Mark    Lisbon    Tesla
1  Laura  Montreal     Audi
2   Adam    Lisbon  Porsche
3  Roger    Berlin     Ford
4   Anna   Glasgow    Honda

Let's try to index the eleventh column (it doesn't exist):

df.iloc[:, 10] # there is obviously no 11th column

IndexError: single positional indexer is out-of-bounds

If you are a beginner with Python, remember that df.iloc[:, 10] would refer to the eleventh column.

JSP tricks to make templating easier?

Use tiles. It saved my life.

But if you can't, there's the include tag, making it similar to php.

The body tag might not actually do what you need it to, unless you have super simple content. The body tag is used to define the body of a specified element. Take a look at this example:

<jsp:element name="${content.headerName}"   
   xmlns:jsp="http://java.sun.com/JSP/Page">    
   <jsp:attribute name="lang">${content.lang}</jsp:attribute>   
   <jsp:body>${content.body}</jsp:body> 
</jsp:element>

You specify the element name, any attributes that element might have ("lang" in this case), and then the text that goes in it--the body. So if

  • content.headerName = h1,
  • content.lang = fr, and
  • content.body = Heading in French

Then the output would be

<h1 lang="fr">Heading in French</h1>

Iterating through a list to render multiple widgets in Flutter?

The Dart language has aspects of functional programming, so what you want can be written concisely as:

List<String> list = ['one', 'two', 'three', 'four'];
List<Widget> widgets = list.map((name) => new Text(name)).toList();

Read this as "take each name in list and map it to a Text and form them back into a List".

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".

This could be due to a few things:

  • If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.

  • If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.

  • If there are too many open connections to the database service, it could refuse new connections.

Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.

Display string as html in asp.net mvc view

I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.

I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.

So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.

I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.

How to embed a Google Drive folder in a website

Embedding a Google Drive directory in an IFRAME

Google Drive folders can be embedded and displayed in list and grid views (in which all you can do is click a file or folder to open it on a new tab). To do so, simply replace FOLDER-ID with your own in:

List view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>

or without specifying a mode, since list mode is the default:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID" style="width:100%; height:600px; border:0;"></iframe>

Grid view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Obtaining your folder id

The id is the hash (alphanumeric gibberish) after folders/ in the URL of the folder. You can see the URL in the address bar of your browser when you open the Drive folder. For example, in:

https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2 

The Folder ID is 0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2.

Folder with G Suite/Google Apps domain

If your folder is part of a Google Apps domain, you can add the domain to the URL to alleviate the permission problems (detailed further ahead):

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Just replace MY.DOMAIN.COM and FOLDER-ID with your own.

Caveat with folders requiring permission

This technique works best for folders with public access. Folders that are shared only with certain Google accounts can cause trouble when you embed them this way, depending on which Google accounts are active on the user's browser:

  1. If the user has not logged in to any Google account, then nothing appears in the frame.
  2. If the user is logged onto an account without authorisation to access the folder, the frame will contain the message You need permission, with some buttons to Request access or Switch accounts, but if you click on this last, the frame blanks out.
  3. If the user logs into an account without proper permissions, and later adds the authorised account, on loading the embedded Drive Google will resort to the first active account, and the user will see You need permission, unless...
  4. If the URL contains a Google Suite domain, and the user is logged into that domain's account, the embedded view will work, even if the user logged to another account first.

The blank frames are because Google forbids embedding its login page in an IFRAME (presumably to prevent account stealing), via the X-Frame-Options header, which if set to SAMEORIGIN will cause any well-behaved browser to refuse to load the page if it's not in the same domain (v.g. drive.google.com). You can see this in the developer console of your browser.

TL;DR

To get a list or grid view of a Drive folder (in which all you can do is click a file or folder to open it on a new tab), use:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

or alternatively, for a Google Suite/Apps Drive:

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Replace MY.DOMAIN.COM and FOLDER-ID with your own; remove #grid to get a detailed file list.

For private folders, have your users log to the correct account before loading the page with the embedded folder; if the folder is in a Google Apps domain, you can add the domain to the URL. Else, they must log into the authorised account before any other.

(this answer is an edit of Mori's, but it was rejected as it changed his intent, somehow)

PHP Fatal error when trying to access phpmyadmin mb_detect_encoding

What helped me (using XAMPP on Windows) was to:

  • make sure that my path included the correct path for PHP (I had two PHP installations, one under c:\php and the XAMPP installation in c:\xampp\php which was the one I wanted to use)
  • check that the lines
    extension_dir="C:\xampp\php\ext"
    extension=php_mbstring.dll
    extension=php_exif.dll ; Must be after mbstring as it depends on it
    were uncommented in the php.ini file (i.e. no ; at the beginning)
  • restart the Apache server
  • last but not least, clear the cache when reloading the page http://localhost/phpmyadmin/ (for instance with Ctrl-F5 in Chrome)

Initializing an Array of Structs in C#

You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;

    readonly MyStruct[] MyArray = new MyStruct[]{
      new MyStruct{ label = "a", id = 1},
      new MyStruct{ label = "b", id = 5},
      new MyStruct{ label = "c", id = 1}
    };

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I had same error. It occurred when s3 client was created with different endpoint than the one which was set up while creating bucket.

  • ERROR CODE - The bucket was set up with EAST Region.

s3Client = New AmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY, RegionEndpoint.USWest2)

  • FIX

s3Client = New AmazonS3Client(AWS_ACCESS_KEY, AWS_SECRET_KEY, RegionEndpoint.USEast1)

How to import multiple .csv files at once?

Using plyr::ldply there is roughly a 50% speed increase by enabling the .parallel option while reading 400 csv files roughly 30-40 MB each. Example includes a text progress bar.

library(plyr)
library(data.table)
library(doSNOW)

csv.list <- list.files(path="t:/data", pattern=".csv$", full.names=TRUE)

cl <- makeCluster(4)
registerDoSNOW(cl)

pb <- txtProgressBar(max=length(csv.list), style=3)
pbu <- function(i) setTxtProgressBar(pb, i)
dt <- setDT(ldply(csv.list, fread, .parallel=TRUE, .paropts=list(.options.snow=list(progress=pbu))))

stopCluster(cl)

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

log4j: Log output of a specific class to a specific appender

Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
        <param name="append" value="false"/>
        <param name="maxFileSize" value="1GB"/>
        <param name="maxBackupIndex" value="2"/>
        <param name="file" value="/tmp/bd.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <logger name="com.example.mypackage" additivity="false">
        <level value="debug"/>
        <appender-ref ref="bdfile"/>
    </logger>

    <root>
        <priority value="info"/>
        <appender-ref ref="bdfile"/>
        <appender-ref ref="console"/>
    </root>

</log4j:configuration>

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>   

int main()   
{   
    clock_t t1, t2;  
    t1 = clock();   
    int i;
    for(i = 0; i < 1000000; i++)   
    {   
        int x = 90;  
    }   

    t2 = clock();   

    float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;   
    printf("%f",diff);   

    return 0;   
}

How to send FormData objects with Ajax-requests in jQuery?

If you want to submit files using ajax use "jquery.form.js" This submits all form elements easily.

Samples http://jquery.malsup.com/form/#ajaxSubmit

rough view :

<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>


<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{ 
    information= responseText;
    callAjaxtolist();
    $("#AddPhotoForm").resetForm();
    $("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');        
};

$(document).ready(function(){
    $('.add_new_photo_div').live('click',function(){
            var options = {success:showResponseAfterAddPhoto};  
            $("#AddPhotoForm").ajaxSubmit(options);
        });
});
</script>

How to redirect output to a file and stdout

You can do that for your entire script by using something like that at the beginning of your script :

#!/usr/bin/env bash

test x$1 = x$'\x00' && shift || { set -o pipefail ; ( exec 2>&1 ; $0 $'\x00' "$@" ) | tee mylogfile ; exit $? ; }

# do whaetever you want

This redirect both stderr and stdout outputs to the file called mylogfile and let everything goes to stdout at the same time.

It is used some stupid tricks :

  • use exec without command to setup redirections,
  • use tee to duplicates outputs,
  • restart the script with the wanted redirections,
  • use a special first parameter (a simple NUL character specified by the $'string' special bash notation) to specify that the script is restarted (no equivalent parameter may be used by your original work),
  • try to preserve the original exit status when restarting the script using the pipefail option.

Ugly but useful for me in certain situations.

Angular: How to update queryParams without changing route

The answer with most vote partially worked for me. The browser url stayed the same but my routerLinkActive was not longer working after navigation.

My solution was to use lotation.go:

import { Component } from "@angular/core";
import { Location } from "@angular/common";
import { HttpParams } from "@angular/common/http";

export class whateverComponent {
  constructor(private readonly location: Location, private readonly router: Router) {}

  addQueryString() {
    const params = new HttpParams();
    params.append("param1", "value1");
    params.append("param2", "value2");
    this.location.go(this.router.url.split("?")[0], params.toString());
  }
}

I used HttpParams to build the query string since I was already using it to send information with httpClient. but you can just build it yourself.

and the this._router.url.split("?")[0], is to remove all previous query string from current url.

Stretch and scale a CSS image in the background - with CSS only

Use the Backstretch plugin. One could even have several images slide. It also works within containers. This way for example one could have only a portion of the background been covered with an background image.

Since even I could get it to work proves it to be an easy to use plugin :).

How to check a channel is closed or not without reading it?

it's easier to check first if the channel has elements, that would ensure the channel is alive.

func isChanClosed(ch chan interface{}) bool {
    if len(ch) == 0 {
        select {
        case _, ok := <-ch:
            return !ok
        }
    }
    return false 
}

Jupyter/IPython Notebooks: Shortcut for "run all"?

Easiest solution:

Esc, Ctrl-A, Shift-Enter.

How do I left align these Bootstrap form items?

I was having the exact same problem. I found the issue within bootstrap.min.css. You need to change the label: label {display:inline-block;} to label {display:block;}

Bootstrap 4 navbar color

To change navbar background color:

.navbar-custom {

    background-color: yourcolor !important;
}

Smooth scroll to div id jQuery

Plain JS:

Can be done in plain JS if you use modern browsers.

document
    .getElementById("range-calculator")
    .scrollIntoView({ behavior: "smooth" });

Browser support is a bit issue, but modern browsers support it.

H.264 file size for 1 hr of HD video

If you know the bitrate, it's simply bitrate (bits per second) multiplied by number of seconds. Given that HDV is 25 Mbit/s and one hour has 3,600 seconds, non-transcoded it would be:

25 Mbit/s * 3,600 s/hr  =  3.125 MB/s * 3,600 s/hr  =  11,250 MB/hr  ˜  11 GB/hr

Google's calculator can confirm

The same applies with H.264 footage, although the above might not be as accurate (being variable bitrate and such).

I want to archive approximately 100 hours of such content and want to figure out whether I'm looking at a big hard drive, a multi-drive unit like a Drobo, or an enterprise-level storage system.

First, do not buy an "enterprise-level" storage system (you almost certainly don't need things like hot-swap drives and the same level of support - given the costs)..

I would suggest buying two big drives: One would be your main drive, another in a USB enclosure, and would be connected daily and mirror the primary system (as a backup).

Drives are incredibly cheap, using the above calculation of ~11 GB/hour, that's only 1.1 TB of data (for 100 hours, uncompressed). and you can buy 2 TB drives now.

Drobo, or a machine with a few drives and software RAID is an option, but a single large drive plus backups would be simpler.

Storage is almost a non-issue now, but encode time can still be an issue. Encoding H.264 is very resource-intensive. On a quad-core ~2.5 GHz Xeon, I think I got around 60 fps encoding standard-def (DVD) to H.264 (compared to around 300 fps with MPEG 4). I suppose that's only about 50 hours, but it's something worth considering. Also, assuming the HDV is on tapes, it's a 1:1 capture time, so that's 150 hours of straight processing, never mind things like changing tapes, entering metadata, and general delays (sleep) and errors ("opps, wrong tape").

How to catch segmentation fault in Linux?

Here's an example of how to do it in C.

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void segfault_sigaction(int signal, siginfo_t *si, void *arg)
{
    printf("Caught segfault at address %p\n", si->si_addr);
    exit(0);
}

int main(void)
{
    int *foo = NULL;
    struct sigaction sa;

    memset(&sa, 0, sizeof(struct sigaction));
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = segfault_sigaction;
    sa.sa_flags   = SA_SIGINFO;

    sigaction(SIGSEGV, &sa, NULL);

    /* Cause a seg fault */
    *foo = 1;

    return 0;
}

Nested classes' scope?

I think you can simply do:

class OuterClass:
    outer_var = 1

    class InnerClass:
        pass
    InnerClass.inner_var = outer_var

The problem you encountered is due to this:

A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.
(...)
A scope defines the visibility of a name within a block.
(...)
The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes generator expressions since they are implemented using a function scope. This means that the following will fail:

   class A:  

       a = 42  

       b = list(a + i for i in range(10))

http://docs.python.org/reference/executionmodel.html#naming-and-binding

The above means:
a function body is a code block and a method is a function, then names defined out of the function body present in a class definition do not extend to the function body.

Paraphrasing this for your case:
a class definition is a code block, then names defined out of the inner class definition present in an outer class definition do not extend to the inner class definition.

What is the purpose of Android's <merge> tag in XML layouts?

The include tag

The <include> tag lets you to divide your layout into multiple files: it helps dealing with complex or overlong user interface.

Let's suppose you split your complex layout using two include files as follows:

top_level_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <include layout="@layout/include1.xml" />

    <!-- Second include file -->
    <include layout="@layout/include2.xml" />

</LinearLayout>

Then you need to write include1.xml and include2.xml.

Keep in mind that the xml from the include files is simply dumped in your top_level_activity layout at rendering time (pretty much like the #INCLUDE macro for C).

The include files are plain jane layout xml.

include1.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView1"
    android:text="First include"
    android:textAppearance="?android:attr/textAppearanceMedium"/>

... and include2.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button1"
    android:text="Button" />

See? Nothing fancy. Note that you still have to declare the android namespace with xmlns:android="http://schemas.android.com/apk/res/android.

So the rendered version of top_level_activity.xml is:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <TextView
        android:id="@+id/textView1"
        android:text="First include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />


</LinearLayout>

In your java code, all this is transparent: findViewById(R.id.textView1) in your activity class returns the correct widget ( even if that widget was declared in a xml file different from the activity layout).

And the cherry on top: the visual editor handles the thing swimmingly. The top level layout is rendered with the xml included.

The plot thickens

As an include file is a classic layout xml file, it means that it must have one top element. So in case your file needs to include more than one widget, you would have to use a layout.

Let's say that include1.xml has now two TextView: a layout has to be declared. Let's choose a LinearLayout.

include1.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout2" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</LinearLayout>

The top_level_activity.xml will be rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <LinearLayout 
        android:id="@+id/layout2" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

       <TextView
            android:id="@+id/textView1"
            android:text="Second include"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

       <TextView
            android:id="@+id/textView2"
            android:text="More text"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

   </LinearLayout>

     <!-- Second include file -->
   <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

But wait the two levels of LinearLayout are redundant!

Indeed, the two nested LinearLayout serve no purpose as the two TextView could be included under layout1for exactly the same rendering.

So what can we do?

Enter the merge tag

The <merge> tag is just a dummy tag that provides a top level element to deal with this kind of redundancy issues.

Now include1.xml becomes:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</merge>

and now top_level_activity.xml is rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file --> 
    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

You saved one hierarchy level, avoid one useless view: Romain Guy sleeps better already.

Aren't you happier now?

what's the easiest way to put space between 2 side-by-side buttons in asp.net

Old post, but I'd say the cleanest approach would be to add a class to the surrounding div and a button class on each button so your CSS rule becomes useful for more use cases:

_x000D_
_x000D_
/* Added to highlight spacing */_x000D_
.is-grouped {   _x000D_
    display: inline-block;_x000D_
    background-color: yellow;_x000D_
}_x000D_
_x000D_
.is-grouped > .button:not(:last-child) {_x000D_
    margin-right: 10px;_x000D_
}
_x000D_
Spacing shown in yellow<br><br>_x000D_
_x000D_
<div class='is-grouped'>_x000D_
    <button class='button'>Save</button>_x000D_
    <button class='button'>Save As...</button>_x000D_
    <button class='button'>Delete</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Default value for field in Django model

You can also use a callable in the default field, such as:

b = models.CharField(max_length=7, default=foo)

And then define the callable:

def foo():
    return 'bar'

How to restart a node.js server

In this case you are restarting your node.js server often because it's in active development and you are making changes all the time. There is a great hot reload script that will handle this for you by watching all your .js files and restarting your node.js server if any of those files have changed. Just the ticket for rapid development and test.

The script and explanation on how to use it are at here at Draco Blue.

The difference between fork(), vfork(), exec() and clone()

  • vfork() is an obsolete optimization. Before good memory management, fork() made a full copy of the parent's memory, so it was pretty expensive. since in many cases a fork() was followed by exec(), which discards the current memory map and creates a new one, it was a needless expense. Nowadays, fork() doesn't copy the memory; it's simply set as "copy on write", so fork()+exec() is just as efficient as vfork()+exec().

  • clone() is the syscall used by fork(). with some parameters, it creates a new process, with others, it creates a thread. the difference between them is just which data structures (memory space, processor state, stack, PID, open files, etc) are shared or not.

Creating an instance of class

   /* 1 */ Foo* foo1 = new Foo ();

Creates an object of type Foo in dynamic memory. foo1 points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo was a POD-type, this would perform value-initialization (it doesn't apply here).

   /* 2 */ Foo* foo2 = new Foo;

Identical to before, because Foo is not a POD type.

   /* 3 */ Foo foo3;

Creates a Foo object called foo3 in automatic storage.

   /* 4 */ Foo foo4 = Foo::Foo();

Uses copy-initialization to create a Foo object called foo4 in automatic storage.

   /* 5 */ Bar* bar1 = new Bar ( *new Foo() );

Uses Bar's conversion constructor to create an object of type Bar in dynamic storage. bar1 is a pointer to it.

   /* 6 */ Bar* bar2 = new Bar ( *new Foo );

Same as before.

   /* 7 */ Bar* bar3 = new Bar ( Foo foo5 );

This is just invalid syntax. You can't declare a variable there.

   /* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );

Would work and work by the same principle to 5 and 6 if bar3 wasn't declared on in 7.

5 & 6 contain memory leaks.

Syntax like new Bar ( Foo::Foo() ); is not usual. It's usually new Bar ( (Foo()) ); - extra parenthesis account for most-vexing parse. (corrected)

Convert string to Time

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

How do you read CSS rule values with JavaScript?

//works in IE, not sure about other browsers...

alert(classes[x].style.cssText);

How to draw a graph in PHP?

By far the easiest solution is to just use the Google Chart API http://code.google.com/apis/chart/

You can make bar graphs, pie charts, use 3D, and it's as easy as building a url with some parameters. See the simple example below.

This Pie Chart is really easy to make

Xcode couldn't find any provisioning profiles matching

Try to check Signing settings in Build settings for your project and target. Be sure that code signing identity section has correct identities for Debug and Release.

image description here

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Propagate all arguments in a bash shell script

For bash and other Bourne-like shells:

java com.myserver.Program "$@"

How to pass a value from one jsp to another jsp page?

Using Query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using Hidden variable .

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

you can send Using Session object.

   session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.

   int userid = session.getAttribute("userId"); 

Javascript : Send JSON Object with Ajax?

I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.

Wrap up content like below,

var params = {
            "IDs": IDs,
            "ID2s": IDs2,
            "id": 1
        };

In my case I had already json'd the arrays and passed the result to the function

var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());

Then call the XMLHttpRequest POST and stringify the object

var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");           
ajax.onreadystatechange = function () {
    if (this.readyState == 4) {
       var blob = new Blob([this.response], { type: "application/octet-stream" });
       saveAs(blob, "filename.zip");
    }
};

ajax.send(JSON.stringify(params));

Then have a model like this

public class MyModel
{
    public int[] IDs { get; set; }
    public int[] ID2s { get; set; }
    public int id { get; set; }
}

Then pass in Action like

public async Task<IActionResult> MyAction([FromBody] MyModel model)

Use this add-on if your returning a file

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>

Entity Framework: There is already an open DataReader associated with this Command

This problem can be solved simply by converting the data to a list

 var details = _webcontext.products.ToList();


            if (details != null)
            {
                Parallel.ForEach(details, x =>
                {
                    Products obj = new Products();
                    obj.slno = x.slno;
                    obj.ProductName = x.ProductName;
                    obj.Price = Convert.ToInt32(x.Price);
                    li.Add(obj);

                });
                return li;
            }

how to remove the bold from a headline?

The heading looks bold because of its large size, if you have applied bold or want to change behaviour, you can do:

h1 { font-weight:normal; }

More: http://www.w3.org/TR/css3-fonts/#font-weight-prop

How do I prevent a form from being resized by the user?

There is an option in vb.net that lets you do all this.

Set <code>lock = false</code> to <code>locked = true</code>

The user wont be able to re-size the form or move it around, although there are other ways, this I think is the best.

SELECT query with CASE condition and SUM()

To get each sum in a separate column:

Select SUM(IF(CPaymentType='Check', CAmount, 0)) as PaymentAmountCheck,
       SUM(IF(CPaymentType='Cash', CAmount, 0)) as PaymentAmountCash
from TableOrderPayment
where CPaymentType IN ('Check','Cash') 
and CDate<=SYSDATETIME() 
and CStatus='Active';

Installing ADB on macOS

Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk by default, not ~/.android-sdk-macosx.

I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.

How to check if a file is a valid image file?

Update

I also implemented the following solution in my Python script here on GitHub.

I also verified that damaged files (jpg) frequently are not 'broken' images i.e, a damaged picture file sometimes remains a legit picture file, the original image is lost or altered but you are still able to load it with no errors. But, file truncation cause always errors.

End Update

You can use Python Pillow(PIL) module, with most image formats, to check if a file is a valid and intact image file.

In the case you aim at detecting also broken images, @Nadia Alramli correctly suggests the im.verify() method, but this does not detect all the possible image defects, e.g., im.verify does not detect truncated images (that most viewers often load with a greyed area).

Pillow is able to detect these type of defects too, but you have to apply image manipulation or image decode/recode in or to trigger the check. Finally I suggest to use this code:

try:
  im = Image.load(filename)
  im.verify() #I perform also verify, don't know if he sees other types o defects
  im.close() #reload is necessary in my case
  im = Image.load(filename) 
  im.transpose(PIL.Image.FLIP_LEFT_RIGHT)
  im.close()
except: 
  #manage excetions here

In case of image defects this code will raise an exception. Please consider that im.verify is about 100 times faster than performing the image manipulation (and I think that flip is one of the cheaper transformations). With this code you are going to verify a set of images at about 10 MBytes/sec with standard Pillow or 40 MBytes/sec with Pillow-SIMD module (modern 2.5Ghz x86_64 CPU).

For the other formats psd,xcf,.. you can use Imagemagick wrapper Wand, the code is as follows:

im = wand.image.Image(filename=filename)
temp = im.flip;
im.close()

But, from my experiments Wand does not detect truncated images, I think it loads lacking parts as greyed area without prompting.

I red that Imagemagick has an external command identify that could make the job, but I have not found a way to invoke that function programmatically and I have not tested this route.

I suggest to always perform a preliminary check, check the filesize to not be zero (or very small), is a very cheap idea:

statfile = os.stat(filename)
filesize = statfile.st_size
if filesize == 0:
  #manage here the 'faulty image' case

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

I'm posting my solution for the other sleep-deprived souls out there:

If you're using RVM, double-check that you're in the correct folder, using the correct ruby version and gemset. I had an array of terminal tabs open, and one of them was in a different directory. typing "rails console" produced the error because my default rails distro is 2.3.x.

I noticed the error on my part, cd'd to the correct directory, and my .rvmrc file did the rest.

RVM is not like Git. In git, changing branches in one shell changes it everywhere. It's literally rewriting the files in question. RVM, on the other hand, is just setting shell variables, and must be set for each new shell you open.

In case you're not familiar with .rvmrc, you can put a file with that name in any directory, and rvm will pick it up and use the version/gemset specified therein, whenever you change to that directory. Here's a sample .rvmrc file:

rvm use 1.9.2@turtles

This will switch to the latest version of ruby 1.9.2 in your RVM collection, using the gemset "turtles". Now you can open up a hundred tabs in Terminal (as I end up doing) and never worry about the ruby version it's pointing to.

Difference between dict.clear() and assigning {} in Python

In addition to the differences mentioned in other answers, there also is a speed difference. d = {} is over twice as fast:

python -m timeit -s "d = {}" "for i in xrange(500000): d.clear()"
10 loops, best of 3: 127 msec per loop

python -m timeit -s "d = {}" "for i in xrange(500000): d = {}"
10 loops, best of 3: 53.6 msec per loop

Add new row to dataframe, at specific row-index, not appended?

The .before argument in dplyr::add_row can be used to specify the row.

dplyr::add_row(
  cars,
  speed = 0,
  dist = 0,
  .before = 3
)
#>    speed dist
#> 1      4    2
#> 2      4   10
#> 3      0    0
#> 4      7    4
#> 5      7   22
#> 6      8   16
#> ...

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

if you want to change menu item icons, arrow icon (back/up), and 3 dots icon you can use android:tint

  <style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:tint">@color/your_color</item>
  </style>

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

I you only want to apply the change only for one field, you could try serializing the field

class MyModel < ActiveRecord::Base
  serialize :content

  attr_accessible :content, :title
end

Determine the line of code that causes a segmentation fault?

Also, you can give valgrind a try: if you install valgrind and run

valgrind --leak-check=full <program>

then it will run your program and display stack traces for any segfaults, as well as any invalid memory reads or writes and memory leaks. It's really quite useful.

What does the "@" symbol do in SQL?

publish data where stoloc = 'AB143' 
|
[select prtnum where stoloc = @stoloc]

This is how the @ works.

Changing ImageView source

Or try this one. For me it's working fine:

imageView.setImageDrawable(ContextCompat.getDrawable(this, image));

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

Your error is quite literally saying "you're trying to use Windows Authentication, but your login isn't from a trusted domain". Which is odd, because you're connecting to the local machine.

Perhaps you're logged into Windows using a local account rather than a domain account? Ensure that you're logging in with a domain account that is also a SQL Server principal on your SQL2008 instance.

How does autowiring work in Spring?

Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:

UserService userService = new UserServiceImpl();

You will be using this after introducing DI:

@Autowired
private UserService userService;

For achieving this you need to create a bean of your service in your ServiceConfiguration file. After that you need to import that ServiceConfiguration class to your WebApplicationConfiguration class so that you can autowire that bean into your Controller like this:

public class AccController {

    @Autowired
    private UserService userService;
} 

You can find a java configuration based POC here example.

Matplotlib discrete colorbar

I think you'd want to look at colors.ListedColormap to generate your colormap, or if you just need a static colormap I've been working on an app that might help.

Git Pull vs Git Rebase

git pull and git rebase are not interchangeable, but they are closely connected.

git pull fetches the latest changes of the current branch from a remote and applies those changes to your local copy of the branch. Generally this is done by merging, i.e. the local changes are merged into the remote changes. So git pull is similar to git fetch & git merge.

Rebasing is an alternative to merging. Instead of creating a new commit that combines the two branches, it moves the commits of one of the branches on top of the other.

You can pull using rebase instead of merge (git pull --rebase). The local changes you made will be rebased on top of the remote changes, instead of being merged with the remote changes.

Atlassian has some excellent documentation on merging vs. rebasing.

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

In may case, I nedded to copy the gacutil.exe, gacutil.exe.config AND ALSO the gacutlrc.dll (from the 1033 directory)

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

This worked fine for me:

        $('#myelement').datetimepicker({
            dateFormat: "yy-mm-dd",
            timeFormat:  "hh:mm:ss"
        });

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

I have already update my node to Version 5.0.0 And I work work with this:

function toArrayBuffer(buffer){
    var array = [];
    var json = buffer.toJSON();
    var list = json.data

    for(var key in list){
        array.push(fixcode(list[key].toString(16)))
    }

    function fixcode(key){
        if(key.length==1){
            return '0'+key.toUpperCase()
        }else{
            return key.toUpperCase()
        }
    }

    return array
}

I use it to check my vhd disk image.

Format LocalDateTime with Timezone in Java8

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));

Count the occurrences of DISTINCT values

Just changed Amber's COUNT(*) to COUNT(1) for the better performance.

SELECT name, COUNT(1) as count 
FROM tablename 
GROUP BY name 
ORDER BY count DESC;

SQL set values of one column equal to values of another column in the same table

UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL 
AND ColumnA IS NOT NULL

Delete with Join in MySQL

Try this,

DELETE posts.*
FROM posts
INNER JOIN projects ON projects.project_id = posts.project_id
WHERE projects.client_id = :client_id

Putty: Getting Server refused our key Error

I have this issue where sshd only reads from authorized_keys2.

Copying or renaming the file fixed the problem for me.

cd  ~/.ssh
sudo cat authorized_keys >> authorized_keys2

P.S. I'm using Putty from Windows and used PuTTyKeygen for key pair generation.

How to upload image in CodeIgniter?

Change the code like this. It works perfectly:

public function uploadImageFile() //gallery insert
{ 
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_image_name = time() . str_replace(str_split(' ()\\/,:*?"<>|'), '', 
    $_FILES['image_file']['name']);
    $config['upload_path'] = 'uploads/gallery/'; 
    $config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
    $config['file_name'] = $new_image_name;
    $config['max_size']  = '0';
    $config['max_width']  = '0';
    $config['max_height']  = '0';
    $config['$min_width'] = '0';
    $config['min_height'] = '0';
    $this->load->library('upload', $config);
    $upload = $this->upload->do_upload('image_file');
    $title=$this->input->post('title');
    $value=array('title'=>$title,'image_name'=>
    $new_image_name,'crop_name'=>$crop_image_name);}

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

SQL Statement using Where clause with multiple values

Try this:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

The number in the having should match the amount of people. If you also need the Status to be Complete use this where clause instead of the previous one:

where personName in ('Ryan', 'Holly') and status = 'Complete'

How do I find the length/number of items present for an array?

I'm not sure that i know exactly what you mean.

But to get the length of an initialized array,

doesn't strlen(string) work ??

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

How can I see the raw SQL queries Django is running?

No other answer covers this method, so:

I find by far the most useful, simple, and reliable method is to ask your database. For example on Linux for Postgres you might do:

sudo su postgres
tail -f /var/log/postgresql/postgresql-8.4-main.log

Each database will have slightly different procedure. In the database logs you'll see not only the raw SQL, but any connection setup or transaction overhead django is placing on the system.

A failure occurred while executing com.android.build.gradle.internal.tasks

If you getting this error saying signing-config.json (Access denied) means just exit the android studio and just go to the desktop home and click on the android studio icon and give Run as Administrator, this will sort out the problem (or) you can delete the signing-config.json and re-run the program :)

Java - How to create a custom dialog box?

i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.

Sample Error Dialog from CUstomDialog API: CustomDialog Error Message

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

JPanel setBackground(Color.BLACK) does nothing

You need to create a new Jpanel object in the Board constructor. for example

public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 

jQuery Set Cursor Position in Text Area

I do realize that this is a very old post, but I thought that I should offer perhaps a simpler solution to update it using only jQuery.

function getTextCursorPosition(ele) {   
    return ele.prop("selectionStart");
}

function setTextCursorPosition(ele,pos) {
    ele.prop("selectionStart", pos + 1);
    ele.prop("selectionEnd", pos + 1);
}

function insertNewLine(text,cursorPos) {
    var firstSlice = text.slice(0,cursorPos);
    var secondSlice = text.slice(cursorPos);

    var new_text = [firstSlice,"\n",secondSlice].join('');

    return new_text;
}

Usage for using ctrl-enter to add a new line (like in Facebook):

$('textarea').on('keypress',function(e){
    if (e.keyCode == 13 && !e.ctrlKey) {
        e.preventDefault();
        //do something special here with just pressing Enter
    }else if (e.ctrlKey){
        //If the ctrl key was pressed with the Enter key,
        //then enter a new line break into the text
        var cursorPos = getTextCursorPosition($(this));                

        $(this).val(insertNewLine($(this).val(), cursorPos));
        setTextCursorPosition($(this), cursorPos);
    }
});

I am open to critique. Thank you.

UPDATE: This solution does not allow normal copy and paste functionality to work (i.e. ctrl-c, ctrl-v), so I will have to edit this in the future to make sure that part works again. If you have an idea how to do that, please comment here, and I will be happy to test it out. Thanks.

Interfaces — What's the point?

Consider the case where you don't control or own the base classes.

Take visual controls for instance, in .NET for Winforms they all inherit from the base class Control, that is completely defined in the .NET framework.

Let's assume you're in the business of creating custom controls. You want to build new buttons, textboxes, listviews, grids, whatnot and you'd like them all to have certain features unique to your set of controls.

For instance you might want a common way to handle theming, or a common way to handle localization.

In this case you can't "just create a base class" because if you do that, you have to reimplement everything that relates to controls.

Instead you will descend from Button, TextBox, ListView, GridView, etc. and add your code.

But this poses a problem, how can you now identify which controls are "yours", how can you build some code that says "for all the controls on the form that are mine, set the theme to X".

Enter interfaces.

Interfaces are a way to look at an object, to determine that the object adheres to a certain contract.

You would create "YourButton", descend from Button, and add support for all the interfaces you need.

This would allow you to write code like the following:

foreach (Control ctrl in Controls)
{
    if (ctrl is IMyThemableControl)
        ((IMyThemableControl)ctrl).SetTheme(newTheme);
}

This would not be possible without interfaces, instead you would have to write code like this:

foreach (Control ctrl in Controls)
{
    if (ctrl is MyThemableButton)
        ((MyThemableButton)ctrl).SetTheme(newTheme);
    else if (ctrl is MyThemableTextBox)
        ((MyThemableTextBox)ctrl).SetTheme(newTheme);
    else if (ctrl is MyThemableGridView)
        ((MyThemableGridView)ctrl).SetTheme(newTheme);
    else ....
}

Jersey stopped working with InjectionManagerFactory not found

Here is the new dependency (August 2017)

    <!-- https://mvnrepository.com/artifact/org.glassfish.jersey.core/jersey-common -->
<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-common</artifactId>
    <version>2.0-m03</version>
</dependency>

MVC DateTime binding with incorrect date format

It going to be slightly different in MVC 3.

Suppose we have a controller and a view with Get method

public ActionResult DoSomething(DateTime dateTime)
{
    return View();
}

We should add ModelBinder

public class DateTimeBinder : IModelBinder
{
    #region IModelBinder Members
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        DateTime dateTime;
        if (DateTime.TryParse(controllerContext.HttpContext.Request.QueryString["dateTime"], CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out dateTime))
            return dateTime;
        //else
        return new DateTime();//or another appropriate default ;
    }
    #endregion
}

and the command in Application_Start() of Global.asax

ModelBinders.Binders.Add(typeof(DateTime), new DateTimeBinder());

count number of lines in terminal output

Pipe the result to wc using the -l (line count) switch:

grep -Rl "curl" ./ | wc -l

GROUP BY without aggregate function

That's how GROUP BY works. It takes several rows and turns them into one row. Because of this, it has to know what to do with all the combined rows where there have different values for some columns (fields). This is why you have two options for every field you want to SELECT : Either include it in the GROUP BY clause, or use it in an aggregate function so the system knows how you want to combine the field.

For example, let's say you have this table:

Name | OrderNumber
------------------
John | 1
John | 2

If you say GROUP BY Name, how will it know which OrderNumber to show in the result? So you either include OrderNumber in group by, which will result in these two rows. Or, you use an aggregate function to show how to handle the OrderNumbers. For example, MAX(OrderNumber), which means the result is John | 2 or SUM(OrderNumber) which means the result is John | 3.

how to change php version in htaccess in server

Go to File Manager on your CPanel >>> Public html >>> find the .htaccess file >>> right click on the on it >>>> click edit.see picture

Type the number of the version you want to change to. i.e - 73, 70 or 71.

Hope this helps. After that, save changes.

The best way to remove duplicate values from NSMutableArray in Objective-C?

just use this simple code :

NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];

since nsset doesn't allow duplicate values and all objects returns an array

Html.EditorFor Set Default Value

Shouldn't the @Html.EditorFor() make use of the Attributes you put in your model?

[DefaultValue(false)]
public bool TestAccount { get; set; }

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

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }

Difference between save and saveAndFlush in Spring data jpa

Depending on the hibernate flush mode that you are using (AUTO is the default) save may or may not write your changes to the DB straight away. When you call saveAndFlush you are enforcing the synchronization of your model state with the DB.

If you use flush mode AUTO and you are using your application to first save and then select the data again, you will not see a difference in bahvior between save() and saveAndFlush() because the select triggers a flush first. See the documention.

Global variables in Javascript across multiple files

OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:

  1. One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
  2. Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
  3. One HTML file, open by 2 browsers, will it work and will they interfere?

All the results were as expected.

  1. It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
  2. They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
  3. All works independently, as expected.

Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.

My example files follow:

EXTERNAL JS:

var global = 0;

function f1()
{
    alert('fired: f1');
    global = 1;
    alert('global changed to 1');
}

function f2()
{
    alert('fired f2');
    alert('value of global: '+global);
}

HTML 1:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

HTML 2

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>

SharePoint 2013 get current user using JavaScript

I found a much easier way, it doesn't even use SP.UserProfiles.js. I don't know if it applies to each one's particular case, but definitely worth sharing.

//assume we have a client context called context.
var web = context.get_web();
var user = web.get_currentUser(); //must load this to access info.
context.load(user);
context.executeQueryAsync(function(){
    alert("User is: " + user.get_title()); //there is also id, email, so this is pretty useful.
}, function(){alert(":(");});

Anyways, thanks to your answers, I got to mingle a bit with UserProfiles, even though it is not really necessary for my case.

Array versus List<T>: When to use which?

Populating a list is easier than an array. For arrays, you need to know the exact length of data, but for lists, data size can be any. And, you can convert a list into an array.

List<URLDTO> urls = new List<URLDTO>();

urls.Add(new URLDTO() {
    key = "wiki",
    url = "https://...",
});

urls.Add(new URLDTO()
{
    key = "url",
    url = "http://...",
});

urls.Add(new URLDTO()
{
    key = "dir",
    url = "https://...",
});

// convert a list into an array: URLDTO[]
return urls.ToArray();

Turn off display errors using file "php.ini"

Open your php.ini file (If you are using Linux - sudo vim /etc/php5/apache2/php.ini)

Add this lines into that file

   error_reporting = E_ALL & ~E_WARNING 

(If you need to disabled any other errors -> error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING)

    display_errors = On

And finally you need to restart your APACHE server.

T-SQL: Selecting rows to delete via joins

DELETE TableA
FROM   TableA a
       INNER JOIN TableB b
               ON b.Bid = a.Bid
                  AND [my filter condition] 

should work

Pure Javascript listen to input value change

As a basic example...

HTML:

<input type="text" name="Thing" value="" />

Script:

/* event listener */
document.getElementsByName("Thing")[0].addEventListener('change', doThing);

/* function */
function doThing(){
   alert('Horray! Someone wrote "' + this.value + '"!');
}

Here's a fiddle: http://jsfiddle.net/Niffler/514gg4tk/

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

ASP.NET MVC controller actions that return JSON or partial html

Alternative solution with incoding framework

Action return json

Controller

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncJson(new SomeVm(){Id = 1,Name ="Inc"});
    }

Razor page

@using (var template = Html.Incoding().ScriptTemplate<SomeVm>("tmplId"))
{
    using (var each = template.ForEach())
    {
        <span> Id: @each.For(r=>r.Id) Name: @each.For(r=>r.Name)</span>
    }
}

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core()
                              .Insert
                              .WithTemplate(Selector.Jquery.Id("tmplId"))
                              .Html())
  .AsHtmlAttributes()
  .ToDiv())

Action return html

Controller

    [HttpGet]
    public ActionResult SomeActionMethod()
    {
        return IncView();
    }

Razor page

@(Html.When(JqueryBind.InitIncoding)
  .Do()
  .AjaxGet(Url.Action("SomeActionMethod","SomeContoller"))
  .OnSuccess(dsl => dsl.Self().Core().Insert.Html())
  .AsHtmlAttributes()
  .ToDiv())

Ruby: How to convert a string to boolean

if value.to_s == 'true'
  true
elsif value.to_s == 'false'
  false
end

How to switch to another domain and get-aduser

I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.

$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite

Get-ADUser -Server $dc.HostName[0] `
    -Filter { EmailAddress -Like "*Smith_Karla*" } `
    -Properties EmailAddress

Javascript: Fetch DELETE and PUT requests

Just Simple Answer. FETCH DELETE

function deleteData(item, url) {
  return fetch(url + '/' + item, {
    method: 'delete'
  })
  .then(response => response.json());
}

Rotating and spacing axis labels in ggplot2

OUTDATED - see this answer for a simpler approach


To obtain readable x tick labels without additional dependencies, you want to use:

  ... +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
  ...

This rotates the tick labels 90° counterclockwise and aligns them vertically at their end (hjust = 1) and their centers horizontally with the corresponding tick mark (vjust = 0.5).

Full example:

library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))


Note, that vertical/horizontal justification parameters vjust/hjust of element_text are relative to the text. Therefore, vjust is responsible for the horizontal alignment.

Without vjust = 0.5 it would look like this:

q + theme(axis.text.x = element_text(angle = 90, hjust = 1))

Without hjust = 1 it would look like this:

q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

If for some (wired) reason you wanted to rotate the tick labels 90° clockwise (such that they can be read from the left) you would need to use: q + theme(axis.text.x = element_text(angle = -90, vjust = 0.5, hjust = -1)).

All of this has already been discussed in the comments of this answer but I come back to this question so often, that I want an answer from which I can just copy without reading the comments.

SQL get the last date time record

Considering that max(dates) can be different for each filename, my solution :

select filename, dates, status
from yt a
where a.dates = (
  select max(dates)
    from yt b
    where a.filename = b.filename
)
;

http://sqlfiddle.com/#!18/fdf8d/1/0

HTH

Android WebView not loading an HTTPS URL

Setting thoses two properties were enough to make it work for me, and doesn't expose to security issues :

 WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);

Dots in URL causes 404 with ASP.NET mvc and IIS

As solution could be also considering encoding to a format which doesn't contain symbol., as base64.

In js should be added

btoa(parameter); 

In controller

byte[] bytes = Convert.FromBase64String(parameter);
string parameter= Encoding.UTF8.GetString(bytes);

Permission denied on CopyFile in VBS

Another thing to check is if any applications still have a hold on the file.

Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.

In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."

how to redirect to home page

_x000D_
_x000D_
var url = location.href;_x000D_
var newurl = url.replace('some-domain.com','another-domain.com';);_x000D_
location.href=newurl;
_x000D_
_x000D_
_x000D_

See this answer https://stackoverflow.com/a/42291014/3901511

How do you remove duplicates from a list whilst preserving order?

sequence = ['1', '2', '3', '3', '6', '4', '5', '6']
unique = []
[unique.append(item) for item in sequence if item not in unique]

unique ? ['1', '2', '3', '6', '4', '5']

how to File.listFiles in alphabetical order?

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

Display the current date and time using HTML and Javascript with scrollable effects in hta application

This will help you.

Javascript

debugger;
var today = new Date();
document.getElementById('date').innerHTML = today

Fiddle Demo

Can vue-router open a link in a new tab?

In case that you define your route like the one asked in the question (path: '/link/to/page'):

import Vue from 'vue'
import Router from 'vue-router'
import MyComponent from '@/components/MyComponent.vue';

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/link/to/page',
      component: MyComponent
    }
  ]
})

You can resolve the URL in your summary page and open your sub page as below:

<script>
export default {
  methods: {
    popup() {
      let route = this.$router.resolve({path: '/link/to/page'});
      // let route = this.$router.resolve('/link/to/page'); // This also works.
      window.open(route.href, '_blank');
    }
  }
};
</script>

Of course if you've given your route a name, you can resolve the URL by name:

routes: [
  {
    path: '/link/to/page',
    component: MyComponent,
    name: 'subPage'
  }
]

...

let route = this.$router.resolve({name: 'subPage'});

References:

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

What are Keycloak's OAuth2 / OpenID Connect endpoints?

For Keycloak 1.2 the above information can be retrieved via the url

http://keycloakhost:keycloakport/auth/realms/{realm}/.well-known/openid-configuration

For example, if the realm name is demo:

http://keycloakhost:keycloakport/auth/realms/demo/.well-known/openid-configuration

An example output from above url:

{
    "issuer": "http://localhost:8080/auth/realms/demo",
    "authorization_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/auth",
    "token_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token",
    "userinfo_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/userinfo",
    "end_session_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/logout",
    "jwks_uri": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs",
    "grant_types_supported": [
        "authorization_code",
        "refresh_token",
        "password"
    ],
    "response_types_supported": [
        "code"
    ],
    "subject_types_supported": [
        "public"
    ],
    "id_token_signing_alg_values_supported": [
        "RS256"
    ],
    "response_modes_supported": [
        "query"
    ]
}

Found information at https://issues.jboss.org/browse/KEYCLOAK-571

Note: You might need to add your client to the Valid Redirect URI list