Programs & Examples On #Memory model

For questions on memory ordering models at the programming language level (above the ISA or machine language level).

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

This is now a multiple-year old question, but being very popular, it's worth mentioning a fantastic resource for learning about the C++11 memory model. I see no point in summing up his talk in order to make this yet another full answer, but given this is the guy who actually wrote the standard, I think it's well worth watching the talk.

Herb Sutter has a three hour long talk about the C++11 memory model titled "atomic<> Weapons", available on the Channel9 site - part 1 and part 2. The talk is pretty technical, and covers the following topics:

  1. Optimizations, Races, and the Memory Model
  2. Ordering – What: Acquire and Release
  3. Ordering – How: Mutexes, Atomics, and/or Fences
  4. Other Restrictions on Compilers and Hardware
  5. Code Gen & Performance: x86/x64, IA64, POWER, ARM
  6. Relaxed Atomics

The talk doesn't elaborate on the API, but rather on the reasoning, background, under the hood and behind the scenes (did you know relaxed semantics were added to the standard only because POWER and ARM do not support synchronized load efficiently?).

How do I restrict an input to only accept numbers?

DECIMAL

directive('decimal', function() {
                return {
                    require: 'ngModel',
                    restrict: 'A',
                    link: function(scope, element, attr, ctrl) {
                        function inputValue(val) {
                            if (val) {
                                var digits = val.replace(/[^0-9.]/g, '');

                                if (digits.split('.').length > 2) {
                                    digits = digits.substring(0, digits.length - 1);
                                }

                                if (digits !== val) {
                                    ctrl.$setViewValue(digits);
                                    ctrl.$render();
                                }
                                return parseFloat(digits);
                            }
                            return "";
                        }
                        ctrl.$parsers.push(inputValue);
                    }
                };
            });

DIGITS

directive('entero', function() {
            return {
                require: 'ngModel',
                restrict: 'A',
                link: function(scope, element, attr, ctrl) {
                    function inputValue(val) {
                        if (val) {
                            var value = val + ''; //convert to string
                            var digits = value.replace(/[^0-9]/g, '');

                            if (digits !== value) {
                                ctrl.$setViewValue(digits);
                                ctrl.$render();
                            }
                            return parseInt(digits);
                        }
                        return "";
                    }
                    ctrl.$parsers.push(inputValue);
                }
            };
        });

angular directives for validate numbers

How can I combine flexbox and vertical scroll in a full-height app?

The current spec says this regarding flex: 1 1 auto:

Sizes the item based on the width/height properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are either flex: auto, flex: initial, or flex: none, any positive free space after the items have been sized will be distributed evenly to the items with flex: auto.

http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common

It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0 (or any other smallish number).

Open the terminal in visual studio?

Visual Studio 2019 update:

Now vs has built-in terminal

TerminalSS

View > Terminal (Ctrl+")

To change default terminal

Tools > Options - Terminal > Set As Default

enter image description here


Before Visual Studio 2019

From comments best answer is from @Hans Passant

  1. Add an external tool.

Tools > External Tools > Add

Title: Terminal (or name it yourself)

Command=cmd.exe Or Command=powershell.exe

Arguments= /k

Initial Directory=$(ProjectDir)

  1. Tools > Terminal (or whatever you put in title)

  2. Enjoy!

Delete with "Join" in Oracle sql Query

Use a subquery in the where clause. For a delete query requirig a join, this example will delete rows that are unmatched in the joined table "docx_document" and that have a create date > 120 days in the "docs_documents" table.

delete from docs_documents d
where d.id in (
    select a.id from docs_documents a
    left join docx_document b on b.id = a.document_id
    where b.id is null
        and floor(sysdate - a.create_date) > 120
 );

Getting "project" nuget configuration is invalid error

NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.

Updating Visual Studio to 'Update 2' got it working again.

Tools -> Extensions and Updates ->Visual Studio Update 2

As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.

Virtualbox "port forward" from Guest to Host

Network communication Host -> Guest

Connect to the Guest and find out the ip address:

ifconfig 

example of result (ip address is 10.0.2.15):

eth0      Link encap:Ethernet  HWaddr 08:00:27:AE:36:99
          inet addr:10.0.2.15  Bcast:10.0.2.255  Mask:255.255.255.0

Go to Vbox instance window -> Menu -> Network adapters:

  • adapter should be NAT
  • click on "port forwarding"
  • insert new record (+ icon)
    • for host ip enter 127.0.0.1, and for guest ip address you got from prev. step (in my case it is 10.0.2.15)
    • in your case port is 8000 - put it on both, but you can change host port if you prefer

Go to host system and try it in browser:

http://127.0.0.1:8000

or your network ip address (find out on the host machine by running: ipconfig).

Network communication Guest -> Host

In this case port forwarding is not needed, the communication goes over the LAN back to the host.

On the host machine - find out your netw ip address:

ipconfig

example of result:

IP Address. . . . . . . . . . . . : 192.168.5.1

On the guest machine you can communicate directly with the host, e.g. check it with ping:

# ping 192.168.5.1
PING 192.168.5.1 (192.168.5.1) 56(84) bytes of data.
64 bytes from 192.168.5.1: icmp_seq=1 ttl=128 time=2.30 ms
...

Firewall issues?

@Stranger suggested that in some cases it would be necessary to open used port (8000 or whichever is used) in firewall like this (example for ufw firewall, I haven't tested):

sudo ufw allow 8000 

How to get the first day of the current week and month?

This week in milliseconds:

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
System.out.println("Start of this week:       " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

// start of the next week
cal.add(Calendar.WEEK_OF_YEAR, 1);
System.out.println("Start of the next week:   " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

This month in milliseconds:

// get today and clear time of day
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0); // ! clear would not reset the hour of day !
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

// get start of the month
cal.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Start of the month:       " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

// get start of the next month
cal.add(Calendar.MONTH, 1);
System.out.println("Start of the next month:  " + cal.getTime());
System.out.println("... in milliseconds:      " + cal.getTimeInMillis());

Getting the difference between two repositories

You can add other repo first as a remote to your current repo:

git remote add other_name PATH_TO_OTHER_REPO

then fetch brach from that remote:

git fetch other_name branch_name:branch_name

this creates that branch as a new branch in your current repo, then you can diff that branch with any of your branches, for example, to compare current branch against new branch(branch_name):

git diff branch_name

How can I combine two commits into one commit?

Lazy simple version for forgetfuls like me:

git rebase -i HEAD~3 or however many commits instead of 3.

Turn this

pick YourCommitMessageWhatever
pick YouGetThePoint
pick IdkManItsACommitMessage

into this

pick YourCommitMessageWhatever
s YouGetThePoint
s IdkManItsACommitMessage

and do some action where you hit esc then enter to save the changes. [1]

When the next screen comes up, get rid of those garbage # lines [2] and create a new commit message or something, and do the same escape enter action. [1]

Wowee, you have fewer commits. Or you just broke everything.


[1] - or whatever works with your git configuration. This is just a sequence that's efficient given my setup.

[2] - you'll see some stuff like # this is your n'th commit a few times, with your original commits right below these message. You want to remove these lines, and create a commit message to reflect the intentions of the n commits that you're combining into 1.

Send parameter to Bootstrap modal window?

I found the solution at: Passing data to a bootstrap modal

So simply use:

 $(e.relatedTarget).data('book-id'); 

with 'book-id' is a attribute of modal with pre-fix 'data-'

Using $setValidity inside a Controller

This line:

myForm.file.$setValidity("myForm.file.$error.size", false);

Should be

$scope.myForm.file.$setValidity("size", false);

Get Table and Index storage size in sql server

This query here will list the total size that a table takes up - clustered index, heap and all nonclustered indices:

SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
INNER JOIN 
    sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN      
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN 
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
WHERE 
    t.NAME NOT LIKE 'dt%'    -- filter out system tables for diagramming
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
    s.Name, t.Name

If you want to separate table space from index space, you need to use AND i.index_id IN (0,1) for the table space (index_id = 0 is the heap space, index_id = 1 is the size of the clustered index = data pages) and AND i.index_id > 1 for the index-only space

Link to all Visual Studio $ variables

While there does not appear to be one complete list, the following may also be helpful:

How to use Environment properties:
  http://msdn.microsoft.com/en-us/library/ms171459.aspx

MSBuild reserved properties:
  http://msdn.microsoft.com/en-us/library/ms164309.aspx

Well-known item properties (not sure how these are used):
  http://msdn.microsoft.com/en-us/library/ms164313.aspx

Why does range(start, end) not include end?

It's also useful for splitting ranges; range(a,b) can be split into range(a, x) and range(x, b), whereas with inclusive range you would write either x-1 or x+1. While you rarely need to split ranges, you do tend to split lists quite often, which is one of the reasons slicing a list l[a:b] includes the a-th element but not the b-th. Then range having the same property makes it nicely consistent.

Set a thin border using .css() in javascript

After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:

border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.

Can not change UILabel text color

It is possible, they are not connected in InterfaceBuilder.

Text colour(colorWithRed:(188/255) green:(149/255) blue:(88/255)) is correct, may be mistake in connections,

backgroundcolor is used for the background colour of label and textcolor is used for property textcolor.

Copy Paste Values only( xlPasteValues )

Personally, I would shorten it a touch too if all you need is the columns:

For i = LBound(arr1) To UBound(arr1)
    Sheets("SheetA").Columns(arr1(i)).Copy
    Sheets("SheetB").Columns(arr2(i)).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
Next

as from this code snippet, there isnt much point in lastrow or firstrowDB

wget ssl alert handshake failure

I was in SLES12 and for me it worked after upgrading to wget 1.14, using --secure-protocol=TLSv1.2 and using --auth-no-challenge.

wget --no-check-certificate --secure-protocol=TLSv1.2 --user=satul --password=xxx --auth-no-challenge -v --debug https://jenkins-server/artifact/build.x86_64.tgz

Why "no projects found to import"?

After a long time finally i found that! Here my Way: File -> New Project -> Android Project From Existing Code -> Browse to your project root directory finish!

List of Stored Procedures/Functions Mysql Command Line

List user's procedures and functions for all databases:

SELECT 
    `ROUTINE_SCHEMA` AS `database`
    ,`ROUTINE_TYPE` AS `type`
    ,`SPECIFIC_NAME` AS `name`
    ,`DTD_IDENTIFIER` AS `data_type`
FROM 
    `INFORMATION_SCHEMA`.`ROUTINES`
WHERE
  `definer` LIKE
  CONCAT('%', CONCAT((SUBSTRING_INDEX((SELECT user()), '@', 1)), '%'))
ORDER BY
    `database`
    ,`type`
    ,`name`
;

List user's procedures and functions for the database in use:

SELECT 
    `ROUTINE_SCHEMA` AS `database`
    ,`ROUTINE_TYPE` AS `type`
    ,`SPECIFIC_NAME` AS `name`
    ,`DTD_IDENTIFIER` AS `data_type`
FROM 
    `INFORMATION_SCHEMA`.`ROUTINES`
WHERE
  `definer` LIKE
  CONCAT('%', CONCAT((SUBSTRING_INDEX((SELECT user()), '@', 1)), '%'))
AND
   `ROUTINE_SCHEMA` = DATABASE()
ORDER BY
    `type`
    ,`name`
;

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

CSS3 has a pseudo-class called :not()

_x000D_
_x000D_
input:not([type='checkbox']) {    
    visibility: hidden;
}
_x000D_
<p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
                                      
<ul>
  <li>text: (<input type="text">)</li>  
  <li>password (<input type="password">)</li>       
  <li>checkbox (<input type="checkbox">)</li> 
 </ul>
_x000D_
_x000D_
_x000D_


Multiple selectors

As Vincent mentioned, it's possible to string multiple :not()s together:

input:not([type='checkbox']):not([type='submit'])

CSS4, which is supported in many of the latest browser releases, allows multiple selectors in a :not()

input:not([type='checkbox'],[type='submit'])

Legacy support

All modern browsers support the CSS3 syntax. At the time this question was asked, we needed a fall-back for IE7 and IE8. One option was to use a polyfill like IE9.js. Another was to exploit the cascade in CSS:

input {
   // styles for most inputs
}   

input[type=checkbox] {
  // revert back to the original style
} 

input.checkbox {
  // for completeness, this would have worked even in IE3!
} 

How to detect the physical connected state of a network cable/connector?

On OpenWRT the only way to reliably do this, at least for me, is by running these commands:

# Get switch name
swconfig list

# assuming switch name is "switch0"
swconfig dev switch0 show | grep link:

# Possible output
root@OpenWrt:~# swconfig dev switch0 show | grep link:
        link: port:0 link:up speed:1000baseT full-duplex txflow rxflow
        link: port:1 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
        link: port:2 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
        link: port:3 link:down
        link: port:4 link:up speed:1000baseT full-duplex eee100 eee1000 auto
        link: port:5 link:down
        link: port:6 link:up speed:1000baseT full-duplex txflow rxflow

This will show either "link:down" or "link:up" on every port of your switch.

Downloading folders from aws s3, cp or sync?

Just used version 2 of the AWS CLI. For the s3 option, there is also a --dryrun option now to show you what will happen:

aws s3 --dryrun cp s3://bucket/filename /path/to/dest/folder --recursive

What integer hash function are good that accepts an integer hash key?

Depends on how your data is distributed. For a simple counter, the simplest function

f(i) = i

will be good (I suspect optimal, but I can't prove it).

How to Generate Unique ID in Java (Integer)?

How unique does it need to be?

If it's only unique within a process, then you can use an AtomicInteger and call incrementAndGet() each time you need a new value.

Singleton: How should it be used

  • How do you implement a Singleton correctly

There's one issue I've never seen mentioned, something I ran into at a previous job. We had C++ singletons that were shared between DLLs, and the usual mechanics of ensuring a single instance of a class just don't work. The problem is that each DLL gets its own set of static variables, along with the EXE. If your get_instance function is inline or part of a static library, each DLL will wind up with its own copy of the "singleton".

The solution is to make sure the singleton code is only defined in one DLL or EXE, or create a singleton manager with those properties to parcel out instances.

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

How can I get name of element with jQuery?

To read a property of an object you use .propertyName or ["propertyName"] notation.

This is no different for elements.

var name = $('#item')[0].name;
var name = $('#item')[0]["name"];

If you specifically want to use jQuery methods, then you'd use the .prop() method.

var name = $('#item').prop('name');

Please note that attributes and properties are not necessarily the same.

How can I force clients to refresh JavaScript files?

Appending the current time to the URL is indeed a common solution. However, you can also manage this at the web server level, if you want to. The server can be configured to send different HTTP headers for javascript files.

For example, to force the file to be cached for no longer than 1 day, you would send:

Cache-Control: max-age=86400, must-revalidate

For beta, if you want to force the user to always get the latest, you would use:

Cache-Control: no-cache, must-revalidate

Django URL Redirect

You can try the Class Based View called RedirectView

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

Notice how as url in the <url_to_home_view> you need to actually specify the url.

permanent=False will return HTTP 302, while permanent=True will return HTTP 301.

Alternatively you can use django.shortcuts.redirect

Update for Django 2+ versions

With Django 2+, url() is deprecated and replaced by re_path(). Usage is exactly the same as url() with regular expressions. For replacements without the need of regular expression, use path().

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

Webkit browsers (not sure about FireBug) allow you to copy the HTML of an element easily, so that's one part of the process out of the way.

Running this (in the javascript console) prior to copying the HTML for an element will move all the computed styles for the parent element given, as well as all child elements, into the inline style attribute which will then be available as part of the HTML.

var el = document.querySelector("#someid");
var els = el.getElementsByTagName("*");

for(var i = -1, l = els.length; ++i < l;){

    els[i].setAttribute("style", window.getComputedStyle(els[i]).cssText);

}

It's a total hack and you'll have alot of "junk" css attributes to wade through, but should at least get your started.

Finishing current activity from a fragment

As mentioned by Jon F Hancock, this is how a fragment can 'close' the activity by suggesting the activity to close. This makes the fragment portable as is the reason for them. If you use it in a different activity, you might not want to close the activity.

Code below is a snippet from an activity and fragment which has a save and cancel button.

PlayerActivity

public class PlayerActivity extends Activity 
    implements PlayerInfo.PlayerAddListener {

    public void onPlayerCancel() {
       // Decide if its suitable to close the activity, 
       //e.g. is an edit being done in one of the other fragments?
       finish();
    }
}

PlayerInfoFragment, which contains an interface which the calling activity needs to implement.

public class PlayerInfoFragment extends Fragment {
   private PlayerAddListener callback; // implemented in the Activity

   @Override
   public void onAttach(Activity activity) {
     super.onAttach(activity);
     callback= (PlayerAddListener) activity;
   }

   public interface PlayerAddListener {
       public void onPlayerSave(Player p); // not shown in impl above
       public void onPlayerCancel();
   }

   public void btnCancel(View v) {
      callback.onPlayerCancel(); // the activity's implementation
   }
}

Angular-cli from css to scss

Open angular.json file

1.change from

"schematics": {}

to

"schematics": {
           "@schematics/angular:component": {
                   "styleext": "scss"       
             }  
  }
  1. change from (at two places)

"src/styles.css"

to

"src/styles.scss"

then check and rename all .css files and update component.ts files styleUrls from .css to .scss

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

How to get the number of characters in a string

If you need to take grapheme clusters into account, use regexp or unicode module. Counting the number of code points(runes) or bytes also is needed for validaiton since the length of grapheme cluster is unlimited. If you want to eliminate extremely long sequences, check if the sequences conform to stream-safe text format.

package main

import (
    "regexp"
    "unicode"
    "strings"
)

func main() {

    str := "\u0308" + "a\u0308" + "o\u0308" + "u\u0308"
    str2 := "a" + strings.Repeat("\u0308", 1000)

    println(4 == GraphemeCountInString(str))
    println(4 == GraphemeCountInString2(str))

    println(1 == GraphemeCountInString(str2))
    println(1 == GraphemeCountInString2(str2))

    println(true == IsStreamSafeString(str))
    println(false == IsStreamSafeString(str2))
}


func GraphemeCountInString(str string) int {
    re := regexp.MustCompile("\\PM\\pM*|.")
    return len(re.FindAllString(str, -1))
}

func GraphemeCountInString2(str string) int {

    length := 0
    checked := false
    index := 0

    for _, c := range str {

        if !unicode.Is(unicode.M, c) {
            length++

            if checked == false {
                checked = true
            }

        } else if checked == false {
            length++
        }

        index++
    }

    return length
}

func IsStreamSafeString(str string) bool {
    re := regexp.MustCompile("\\PM\\pM{30,}") 
    return !re.MatchString(str) 
}

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

Nested Recycler view height doesn't wrap its content

Here I have found a solution: https://code.google.com/p/android/issues/detail?id=74772

It is in no way my solution. I have just copied it from there, but I hope it will help someone as much as it helped me when implementing horizontal RecyclerView and wrap_content height (should work also for vertical one and wrap_content width)

The solution is to extend the LayoutManager and override its onMeasure method as @yigit suggested.

Here is the code in case the link dies:

public static class MyLinearLayoutManager extends LinearLayoutManager {

    public MyLinearLayoutManager(Context context) {
        super(context);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                          int widthSpec, int heightSpec) {
        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        measureScrapChild(recycler, 0,
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);

        int width = mMeasuredDimension[0];
        int height = mMeasuredDimension[1];

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
            case View.MeasureSpec.AT_MOST:
                width = widthSize;
                break;
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
            case View.MeasureSpec.AT_MOST:
                height = heightSize;
                break;
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        View view = recycler.getViewForPosition(position);
        if (view != null) {
            RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
            int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight(), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom(), p.height);
            view.measure(childWidthSpec, childHeightSpec);
            measuredDimension[0] = view.getMeasuredWidth();
            measuredDimension[1] = view.getMeasuredHeight();
            recycler.recycleView(view);
        }
    }
}

How to add a spinner icon to button when it's in the Loading state?

Simple solution for Bootstrap 3 using CSS3 animations.

Put the following in your CSS:

.glyphicon.spinning {
    animation: spin 1s infinite linear;
    -webkit-animation: spin2 1s infinite linear;
}

@keyframes spin {
    from { transform: scale(1) rotate(0deg); }
    to { transform: scale(1) rotate(360deg); }
}

@-webkit-keyframes spin2 {
    from { -webkit-transform: rotate(0deg); }
    to { -webkit-transform: rotate(360deg); }
}

Then just add the spinning class to a glyphicon while loading to get your spinning icon:

<button class="btn btn-lg btn-warning">
    <span class="glyphicon glyphicon-refresh spinning"></span> Loading...    
</button>

Based on http://www.bootply.com/128062#

  • Note: IE9 and below do not support CSS3 animations.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

gradle.properties:

theGroup=some.group
theName=someName
theVersion=1.0
theSourceCompatibility=1.6

settings.gradle:

rootProject.name = theName

build.gradle:

apply plugin: "java"

group = theGroup
version = theVersion
sourceCompatibility = theSourceCompatibility

Find all elements with a certain attribute value in jquery

You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:

<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...

You can use the code:

var abc = $('div[id^=abc]')

This will return a DOM array of divs which have id starting with abc:

<div id="abc_1"></div>
<div id="abc_2"></div>

Here is the demo: http://jsfiddle.net/mCuWS/

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

What is the 'realtime' process priority setting for?

Like all other answers before real time gives that program the utmost priority class. Nothing is processed until that program has been processed.
On my pentium 4 machine I set minecraft to real time a lot since it increases the game performance a lot, and the system seems completely stable. so realtime isn't as bad as it seems, just if you have a multi-core set a program's affinity to a specific core or cores (just not all of them, just to let everything else be able to run in case the real time set programs gets hung up) and set the priority to real time.

How to use Global Variables in C#?

First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.

Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,

  1. Wrap all such Global variables into a single static class (for manageability).
  2. Have Properties instead of fields(='variables'). This way you have some mechanisms to address any issues with concurrent writes to Globals in the future.

The basic outline for such a class would be:

public class Globals
{
    private static bool _expired;
    public static bool Expired 
    {
        get
        {
            // Reads are usually simple
            return _expired;
        }
        set
        {
            // You can add logic here for race conditions,
            // or other measurements
            _expired = value;
        }
    }
    // Perhaps extend this to have Read-Modify-Write static methods
    // for data integrity during concurrency? Situational.
}

Usage from other classes (within same namespace)

// Read
bool areWeAlive = Globals.Expired;

// Write
// past deadline
Globals.Expired = true;

Difference between Visibility.Collapsed and Visibility.Hidden

Visibility : Hidden Vs Collapsed

Consider following code which only shows three Labels and has second Label visibility as Collapsed:

 <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Center">
    <StackPanel.Resources>
        <Style TargetType="Label">
            <Setter Property="Height" Value="30" />
            <Setter Property="Margin" Value="0"/>
            <Setter Property="BorderBrush" Value="Black"/>
            <Setter Property="BorderThickness" Value="1" />
        </Style>
    </StackPanel.Resources>
    <Label Width="50" Content="First"/>
    <Label Width="50" Content="Second" Visibility="Collapsed"/>
    <Label Width="50" Content="Third"/>
</StackPanel>

Output Collapsed:

Collapsed

Now change the second Label visibility to Hiddden.

<Label Width="50" Content="Second" Visibility="Hidden"/>

Output Hidden:

Hidden

As simple as that.

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

Capture the screen shot using .NET

It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap object and draw into that using the Graphics.CopyFromScreen method.

Sample code:

using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width, 
                                            Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
    g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                     Screen.PrimaryScreen.Bounds.Y,
                     0, 0,
                     bmpScreenCapture.Size,
                     CopyPixelOperation.SourceCopy);
}

Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.

Display / print all rows of a tibble (tbl_df)

I prefer to turn the tibble to data.frame. It shows everything and you're done

df %>% data.frame 

Getter and Setter?

Why use getters and setters?

  1. Scalability: It's easier refactor a getter than search all the var assignments in a project code.
  2. Debugging: You can put breakpoints at setters and getters.
  3. Cleaner: Magic functions are not good solution for writting less, your IDE will not suggest the code. Better use templates for fast-writting getters.

direct assignment and getters/setters

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

Font Awesome not working, icons showing as squares

If the MIME TYPE is already having the .woff and .woff2 file types and still it's giving HTTP-404 error, check the request filtering. If this is restrictive, add these file types these with allow to serve and it shall work. Check it out!

Drop columns whose name contains a specific string from pandas DataFrame

import pandas as pd

import numpy as np

array=np.random.random((2,4))

df=pd.DataFrame(array, columns=('Test1', 'toto', 'test2', 'riri'))

print df

      Test1      toto     test2      riri
0  0.923249  0.572528  0.845464  0.144891
1  0.020438  0.332540  0.144455  0.741412

cols = [c for c in df.columns if c.lower()[:4] != 'test']

df=df[cols]

print df
       toto      riri
0  0.572528  0.144891
1  0.332540  0.741412

How to get hostname from IP (Linux)?

Another simple way I found for using in LAN is

ssh [username@ip] uname -n

If you need to login command line will be

sshpass -p "[password]" ssh [username@ip] uname -n

Escaping quotation marks in PHP

You can use the PHP function addslashes() to any string to make it compatible

What is the difference between iterator and iterable and how to use them?

Question:Difference between Iterable and Iterator?
Ans:

iterable: It is related to forEach loop
iterator: Is is related to Collection

The target element of the forEach loop shouble be iterable.
We can use Iterator to get the object one by one from the Collection

Iterable present in java.?ang package
Iterator present in java.util package

Contains only one method iterator()
Contains three method hasNext(), next(), remove()

Introduced in 1.5 version
Introduced in 1.2 version

EOL conversion in notepad ++

That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".

screenshot of the option for even quicker finding (or different language versions)

You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
CASE
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

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

What you have is on the right track.

def dosomething( thelist ):
    for element in thelist:
        print element

dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )  

Produces the output:

1
2
3
red
green
blue

A couple of things to note given your comment above: unlike in C-family languages, you often don't need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list) to get index,element pairs, rather than doing the x in range(len(thelist)) dance.

How to print the ld(linker) search path

On Linux, you can use ldconfig, which maintains the ld.so configuration and cache, to print out the directories search by ld.so with

ldconfig -v 2>/dev/null | grep -v ^$'\t'

ldconfig -v prints out the directories search by the linker (without a leading tab) and the shared libraries found in those directories (with a leading tab); the grep gets the directories. On my machine, this line prints out

/usr/lib64/atlas:
/usr/lib/llvm:
/usr/lib64/llvm:
/usr/lib64/mysql:
/usr/lib64/nvidia:
/usr/lib64/tracker-0.12:
/usr/lib/wine:
/usr/lib64/wine:
/usr/lib64/xulrunner-2:
/lib:
/lib64:
/usr/lib:
/usr/lib64:
/usr/lib64/nvidia/tls: (hwcap: 0x8000000000000000)
/lib/i686: (hwcap: 0x0008000000000000)
/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib/sse2: (hwcap: 0x0000000004000000)
/usr/lib64/tls: (hwcap: 0x8000000000000000)
/usr/lib64/sse2: (hwcap: 0x0000000004000000)

The first paths, without hwcap in the line, are either built-in or read from /etc/ld.so.conf. The linker can then search additional directories under the basic library search path, with names like sse2 corresponding to additional CPU capabilities. These paths, with hwcap in the line, can contain additional libraries tailored for these CPU capabilities.

One final note: using -p instead of -v above searches the ld.so cache instead.

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

The Advanced Editor did not resolve my issue, instead I was forced to edit dtsx-file through notepad (or your favorite text/xml editor) and manually replace values in attributes to

length="0" dataType="nText" (I'm using unicode)

Always make a backup of the dtsx-file before you edit in text/xml mode.

Running SQL Server 2008 R2

How to Split Image Into Multiple Pieces in Python

I find it easier to skimage.util.view_as_windows or `skimage.util.view_as_blocks which also allows you to configure the step

http://scikit-image.org/docs/dev/api/skimage.util.html?highlight=view_as_windows#skimage.util.view_as_windows

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

DynamoDB vs MongoDB NoSQL

I have worked on both and kind of fan of both.

But you need to understand when to use what and for what purpose.

I don't think It's a great idea to move all your database to DynamoDB, reason being querying is difficult except on primary and secondary keys, Indexing is limited and scanning in DynamoDB is painful.

I would go for a hybrid sort of DB, where extensive query-able data should be there is MongoDB, with all it's feature you would never feel constrained to provide enhancements or modifications.

DynamoDB is lightning fast (faster than MongoDB) so DynamoDB is often used as an alternative to sessions in scalable applications. DynamoDB best practices also suggests that if there are plenty of data which are less being used, move it to other table.

So suppose you have a articles or feeds. People are more likely to look for last week stuff or this month's stuff. chances are really rare for people to visit two year old data. For these purposes DynamoDB prefers to have data stored by month or years in different tables.

DynamoDB is seemlessly scalable, something you will have to do manually in MongoDB. however you would lose on performance of DynamoDB, if you don't understand about throughput partition and how scaling works behind the scene.

DynamoDB should be used where speed is critical, MongoDB on the other hand has too many hands and features, something DynamoDB lacks.

for example, you can have a replica set of MongoDB in such a way that one of the replica holds data instance of 8(or whatever) hours old. Really useful, if you messed up something big time in your DB and want to get the data as it is before.

That's my opinion though.

What is the difference between docker-compose ports vs expose

According to the docker-compose reference,

Ports is defined as:

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

  • Ports mentioned in docker-compose.yml will be shared among different services started by the docker-compose.
  • Ports will be exposed to the host machine to a random port or a given port.

My docker-compose.yml looks like:

mysql:
  image: mysql:5.7
  ports:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                     Command               State            Ports
-------------------------------------------------------------------------------------
  mysql_1       docker-entrypoint.sh mysqld      Up      0.0.0.0:32769->3306/tcp

Expose is defined as:

Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.

Ports are not exposed to host machines, only exposed to other services.

mysql:
  image: mysql:5.7
  expose:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                  Command             State    Ports
---------------------------------------------------------------
 mysql_1      docker-entrypoint.sh mysqld   Up      3306/tcp

Edit

In recent versions of Docker, expose doesn't have any operational impact anymore, it is just informative. (see also)

Cannot read property 'addEventListener' of null

I think the easiest approach would be to just check that el is not null before adding an event listener:

var el = document.getElementById('overlayBtn');
if(el){
  el.addEventListener('click', swapper, false);
}

c# dictionary How to add multiple values for single key?

Instead of using a Dictionary, why not convert to an ILookup?

var myData = new[]{new {a=1,b="frog"}, new {a=1,b="cat"}, new {a=2,b="giraffe"}};
ILookup<int,string> lookup = myData.ToLookup(x => x.a, x => x.b);
IEnumerable<string> allOnes = lookup[1]; //enumerable of 2 items, frog and cat

An ILookup is an immutable data structure that allows multiple values per key. Probably not much use if you need to add items at different times, but if you have all your data up-front, this is definitely the way to go.

How to find nth occurrence of character in a string?

public class Sam_Stringnth {

    public static void main(String[] args) {
        String str="abcabcabc";
        int n = nthsearch(str, 'c', 3);
        if(n<=0)
            System.out.println("Character not found");
        else
            System.out.println("Position is:"+n);
    }
    public static int nthsearch(String str, char ch, int n){
        int pos=0;
        if(n!=0){
            for(int i=1; i<=n;i++){
                pos = str.indexOf(ch, pos)+1;
            }
            return pos;
        }
        else{
            return 0;
        }
    }
}

What do parentheses surrounding an object/function/class declaration mean?

...but what about the previous round parenteses surrounding all the function declaration?

Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:

function() {
    alert('hello');
}();

You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:

function doSomething() {
}

...and you can't have a function statement without a function name.

function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!

Dynamic WHERE clause in LINQ

alt text
(source: scottgu.com)

You need something like this? Use the Linq Dynamic Query Library (download includes examples).

Check out ScottGu's blog for more examples.

Sorting a tab delimited file

pipe it through something like awk '{ print print $1"\t"$2"\t"$3"\t"$4"\t"$5 }'. This will change the spaces to tabs.

Delete an element from a dictionary

pop mutates the dictionary.

 >>> lol = {"hello": "gdbye"}
 >>> lol.pop("hello")
     'gdbye'
 >>> lol
     {}

If you want to keep the original you could just copy it.

Creating a batch file, for simple javac and java command execution

I do not have a JDK installed on my machine to verify this, but here's something to get you started with

%CLASSPATH%=C:\Program Files\Java\jdk1.6\bin rem or whatever your path is
START %CLASSPATH%\javac Main.java
START %CLASSPATH%\java Main

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

How do I clone a generic List in Java?

With Java 8 it can be cloned with a stream.

import static java.util.stream.Collectors.toList;

...

List<AnObject> clone = myList.stream().collect(toList());

How do MySQL indexes work?

Basically an index on a table works like an index in a book (that's where the name came from):

Let's say you have a book about databases and you want to find some information about, say, storage. Without an index (assuming no other aid, such as a table of contents) you'd have to go through the pages one by one, until you found the topic (that's a full table scan). On the other hand, an index has a list of keywords, so you'd consult the index and see that storage is mentioned on pages 113-120,231 and 354. Then you could flip to those pages directly, without searching (that's a search with an index, somewhat faster).

Of course, how useful the index will be, depends on many things - a few examples, using the simile above:

  • if you had a book on databases and indexed the word "database", you'd see that it's mentioned on pages 1-59,61-290, and 292 to 400. In such case, the index is not much help and it might be faster to go through the pages one by one (in a database, this is "poor selectivity").
  • For a 10-page book, it makes no sense to make an index, as you may end up with a 10-page book prefixed by a 5-page index, which is just silly - just scan the 10 pages and be done with it.
  • The index also needs to be useful - there's generally no point to index e.g. the frequency of the letter "L" per page.

Cannot execute RUN mkdir in a Dockerfile

Apart from the previous use cases, you can also use Docker Compose to create directories in case you want to make new dummy folders on docker-compose up:

    volumes:
  - .:/ftp/
  - /ftp/node_modules
  - /ftp/files

What is the use of static synchronized method in java?

Java VM contains a single class object per class. Each class may have some shared variables called static variables. If the critical section of the code plays with these variables in a concurrent environment, then we need to make that particular section as synchronized. When there is more than one static synchronized method only one of them will be executed at a time without preemption. That's what lock on class object does.

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I have this simple solution I have been using and its works.

In App/Exceptions/Handler.php

Add this at top:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

Then inside the render method

public function render($request, Exception $exception)
{
    .......

       if ($exception instanceof NotFoundHttpException){

        $segment = $request->segments();

        //eg. http://site.dev/member/profile
        //module => member
        // view => member.index
        //where member.index is the root of your angular app could be anything :)
        if(head($segment) != 'api' && $module = $segment[0]){
            return response(view("$module.index"), 404);
        }

        return response()->fail('not_found', $exception->getCode());

    }
    .......

     return parent::render($request, $exception);
}

REST API Authentication

For e.g. when a user has login.Now lets say the user want to create a forum topic, How will I know that the user is already logged in?

Think about it - there must be some handshake that tells your "Create Forum" API that this current request is from an authenticated user. Since REST APIs are typically stateless, the state must be persisted somewhere. Your client consuming the REST APIs is responsible for maintaining that state. Usually, it is in the form of some token that gets passed around since the time the user was logged in. If the token is good, your request is good.

Check how Amazon AWS does authentications. That's a perfect example of "passing the buck" around from one API to another.

*I thought of adding some practical response to my previous answer. Try Apache Shiro (or any authentication/authorization library). Bottom line, try and avoid custom coding. Once you have integrated your favorite library (I use Apache Shiro, btw) you can then do the following:

  1. Create a Login/logout API like: /api/v1/login and api/v1/logout
  2. In these Login and Logout APIs, perform the authentication with your user store
  3. The outcome is a token (usually, JSESSIONID) that is sent back to the client (web, mobile, whatever)
  4. From this point onwards, all subsequent calls made by your client will include this token
  5. Let's say your next call is made to an API called /api/v1/findUser
  6. The first thing this API code will do is to check for the token ("is this user authenticated?")
  7. If the answer comes back as NO, then you throw a HTTP 401 Status back at the client. Let them handle it.
  8. If the answer is YES, then proceed to return the requested User

That's all. Hope this helps.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

ADB Driver and Windows 8.1

In Windows 7, 8 or 8.1, in Devices Manager:

  1. Select tree 'Android Device': remove 'Android Composite ADB Interface' [?]
  2. Press on main root of devices tree and call context menu (by right mouse click) and click on 'Update configuration'
  3. After updating your device should appear in 'Other devices'
  4. Select your device, call context menu from it and choose 'Update driver' and perform this updating

Warning comparison between pointer and integer

This: "\0" is a string, not a character. A character uses single quotes, like '\0'.

Convert hex string (char []) to int?

i have done a similar thing, think it might help u its actually working for me

int main(){ int co[8],i;char ch[8];printf("please enter the string:");scanf("%s",ch);for(i=0;i<=7;i++){if((ch[i]>='A')&&(ch[i]<='F')){co[i]=(unsigned int)ch[i]-'A'+10;}else if((ch[i]>='0')&&(ch[i]<='9')){co[i]=(unsigned int)ch[i]-'0'+0;}}

here i have only taken a string of 8 characters. if u want u can add similar logic for 'a' to 'f' to give their equivalent hex values,i haven't done that cause i didn't needed it.

how to calculate binary search complexity

Let's say the iteration in Binary Search terminates after k iterations. At each iteration, the array is divided by half. So let’s say the length of the array at any iteration is n At Iteration 1,

Length of array = n

At Iteration 2,

Length of array = n/2

At Iteration 3,

Length of array = (n/2)/2 = n/22

Therefore, after Iteration k,

Length of array = n/2k

Also, we know that after After k divisions, the length of the array becomes 1 Therefore

Length of array = n/2k = 1
=> n = 2k

Applying log function on both sides:

=> log2 (n) = log2 (2k)
=> log2 (n) = k log2 (2)
As (loga (a) = 1)

Therefore,

As (loga (a) = 1)
k = log2 (n)

Hence the time complexity of Binary Search is

log2 (n)

Where does Chrome store cookies?

Actually the current browsing path to the Chrome cookies in the address bar is: chrome://settings/content/cookies

Unicode (UTF-8) reading and writing to files in Python

Well, your favorite text editor does not realize that \xc3\xa1 are supposed to be character literals, but it interprets them as text. That's why you get the double backslashes in the last line -- it's now a real backslash + xc3, etc. in your file.

If you want to read and write encoded files in Python, best use the codecs module.

Pasting text between the terminal and applications is difficult, because you don't know which program will interpret your text using which encoding. You could try the following:

>>> s = file("f1").read()
>>> print unicode(s, "Latin-1")
Capitán

Then paste this string into your editor and make sure that it stores it using Latin-1. Under the assumption that the clipboard does not garble the string, the round trip should work.

How to style UITextview to like Rounded Rect text field?

One way I found to do it without programming is to make the textfield background transparent, then place a Round Rect Button behind it. Make sure to change the button settings to disable it and uncheck the Disable adjusts image checkbox.

How to "pull" from a local branch into another one?

you have to tell git where to pull from, in this case from the current directory/repository:

git pull . master

but when working locally, you usually just call merge (pull internally calls merge):

git merge master

How to call on a function found on another file?

You can use header files.

Good practice.

You can create a file called player.h declare all functions that are need by other cpp files in that header file and include it when needed.

player.h

#ifndef PLAYER_H    // To make sure you don't declare the function more than once by including the header multiple times.
#define PLAYER_H

#include "stdafx.h"
#include <SFML/Graphics.hpp>

int playerSprite();

#endif

player.cpp

#include "player.h"  // player.h must be in the current directory. or use relative or absolute path to it. e.g #include "include/player.h"

int playerSprite(){
    sf::Texture Texture;
    if(!Texture.loadFromFile("player.png")){
        return 1;
    }
    sf::Sprite Sprite;
    Sprite.setTexture(Texture);
    return 0;
}

main.cpp

#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include "player.h"            //Here. Again player.h must be in the current directory. or use relative or absolute path to it.

int main()
{
    // ...
    int p = playerSprite();  
    //...

Not such a good practice but works for small projects. declare your function in main.cpp

#include "stdafx.h"
#include <SFML/Graphics.hpp>
// #include "player.cpp"


int playerSprite();  // Here

int main()
{
    // ...   
    int p = playerSprite();  
    //...

How to convert unsigned long to string

Try using sprintf:

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

Edit:

Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit longs, which can produce numbers as big as 10 digits.

See Carl Smotricz's answer for a better explanation of the issues involved.

Is it possible to have SSL certificate for IP address, not domain name?

The answer I guess, is yes. Check this link for instance.

Issuing an SSL Certificate to a Public IP Address

An SSL certificate is typically issued to a Fully Qualified Domain Name (FQDN) such as "https://www.domain.com". However, some organizations need an SSL certificate issued to a public IP address. This option allows you to specify a public IP address as the Common Name in your Certificate Signing Request (CSR). The issued certificate can then be used to secure connections directly with the public IP address (e.g., https://123.456.78.99.).

How to log request and response body with Retrofit-Android?

There doesn't appear to be a way to do basic + body, but you can use FULL and filter the headers you don't want.

RestAdapter adapter = new RestAdapter.Builder()
                          .setEndpoint(syncServer)
                          .setErrorHandler(err)
                          .setConverter(new GsonConverter(gson))
                          .setLogLevel(logLevel)
                          .setLog(new RestAdapter.Log() {
                              @Override
                              public void log(String msg) {
                                  String[] blacklist = {"Access-Control", "Cache-Control", "Connection", "Content-Type", "Keep-Alive", "Pragma", "Server", "Vary", "X-Powered-By"};
                                  for (String bString : blacklist) {
                                      if (msg.startsWith(bString)) {
                                          return;
                                      }
                                  }
                                  Log.d("Retrofit", msg);
                              }
                          }).build();

It appears that when overriding the log, the body is prefixed with a tag similar to

[ 02-25 10:42:30.317 25645:26335 D/Retrofit ]

so it should be easy to log basic + body by adjusting the custom filter. I am using a blacklist, but a whitelist could also be used depending on your needs.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Use its value directly:

In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]: 
array([[ 0.98836259,  0.82403141],
       [ 0.337358  ,  0.02054435],
       [ 0.29271728,  0.37813099],
       [ 0.70033513,  0.69919695]])

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

Streaming via RTSP or RTP in HTML5

The spirit of the question, I think, was not truly answered. No, you cannot use a video tag to play rtsp streams as of now. The other answer regarding the link to Chromium guy's "never" is a bit misleading as the linked thread / answer is not directly referring to Chrome playing rtsp via the video tag. Read the entire linked thread, especially the comments at the very bottom and links to other threads.

The real answer is this: No, you cannot just put a video tag on an html 5 page and play rtsp. You need to use a Javascript library of some sort (unless you want to get into playing things with flash and silverlight players) to play streaming video. {IMHO} At the rate the html 5 video discussion and implementation is going, the various vendors of proprietary video standards are not interested in helping this move forward so don't count of the promised ease of use of the video tag unless the browser makers take it upon themselves to somehow solve the problem...again, not likely.{/IMHO}

How to make join queries using Sequelize on Node.js

In my case i did following thing. In the UserMaster userId is PK and in UserAccess userId is FK of UserMaster

UserAccess.belongsTo(UserMaster,{foreignKey: 'userId'});
UserMaster.hasMany(UserAccess,{foreignKey : 'userId'});
var userData = await UserMaster.findAll({include: [UserAccess]});

sendKeys() in Selenium web driver

Try this, it will surely work:

driver.findElement(By.xpath("//label[text()='User Name:']/following::div/input")).sendKeys("UserName" + Keys.TAB);

How to show an empty view with a RecyclerView?

For my projects I made this solution (RecyclerView with setEmptyView method):

public class RecyclerViewEmptySupport extends RecyclerView {
    private View emptyView;

    private AdapterDataObserver emptyObserver = new AdapterDataObserver() {


        @Override
        public void onChanged() {
            Adapter<?> adapter =  getAdapter();
            if(adapter != null && emptyView != null) {
                if(adapter.getItemCount() == 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    RecyclerViewEmptySupport.this.setVisibility(View.GONE);
                }
                else {
                    emptyView.setVisibility(View.GONE);
                    RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE);
                }
            }

        }
    };

    public RecyclerViewEmptySupport(Context context) {
        super(context);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);

        if(adapter != null) {
            adapter.registerAdapterDataObserver(emptyObserver);
        }

        emptyObserver.onChanged();
    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
    }
}

And you should use it instead of RecyclerView class:

<com.maff.utils.RecyclerViewEmptySupport android:id="@+id/list1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    />

<TextView android:id="@+id/list_empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Empty"
    />

and

RecyclerViewEmptySupport list = 
    (RecyclerViewEmptySupport)rootView.findViewById(R.id.list1);
list.setLayoutManager(new LinearLayoutManager(context));
list.setEmptyView(rootView.findViewById(R.id.list_empty));

How to do the Recursive SELECT query in MySQL?

The accepted answer by @Meherzad only works if the data is in a particular order. It happens to work with the data from the OP question. In my case, I had to modify it to work with my data.

Note This only works when every record's "id" (col1 in the question) has a value GREATER THAN that record's "parent id" (col3 in the question). This is often the case, because normally the parent will need to be created first. However if your application allows changes to the hierarchy, where an item may be re-parented somewhere else, then you cannot rely on this.

This is my query in case it helps someone; note it does not work with the given question because the data does not follow the required structure described above.

select t.col1, t.col2, @pv := t.col3 col3
from (select * from table1 order by col1 desc) t
join (select @pv := 1) tmp
where t.col1 = @pv

The difference is that table1 is being ordered by col1 so that the parent will be after it (since the parent's col1 value is lower than the child's).

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

For rails6, I was facing the same problem, as I was missing following files, once I added them, the issue resolved:

1. config/master.key
2. config/credentials.yml.enc

Make sure you have this files.!!!

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

Make sure you are loading from a URL such as:

https://www.youtube.com/embed/HIbAz29L-FA?modestbranding=1&playsinline=0&showinfo=0&enablejsapi=1&origin=https%3A%2F%2Fintercoin.org&widgetid=1

Note the "origin" component, as well as "enablejsapi=1". The origin must match what your domain is, and then it will be whitelisted and work.

How to display Base64 images in HTML?

you can put your data directly in a url statment like

src = 'url(imageData)' ;

and to get the image data u can use the php function

$imageContent = file_get_contents("imageDir/".$imgName);

$imageData = base64_encode($imageContent);

so you can copy paste the value of imageData and paste it directly to your url and assign it to the src attribute of your image

How to make a JSONP request from Javascript without JQuery?

What is JSONP?

The important thing to remember with jsonp is that it isn't actually a protocol or data type. Its just a way of loading a script on the fly and processing the script that is introduced to the page. In the spirit of JSONP, this means introducing a new javascript object from the server into the client application/ script.

When is JSONP needed?

It is 1 method of allowing one domain to access/ process data from another in the same page asyncronously. Primarily, it is used to override CORS (Cross Origin Resource Sharing) restrictions which would occur with an XHR (ajax) request. Script loads are not subject to CORS restrictions.

How is it done

Introducing a new javascript object from the server can be implemented in many ways, but the most common practice is for the server to implement the execution of a 'callback' function, with the required object passed into it. The callback function is just a function you have already set up on the client which the script you load calls at the point the script loads to process the data passed in to it.

Example:

I have an application which logs all items in someone's home. My application is set up and I now want to retrieve all the items in the main bedroom.

My application is on app.home.com. The apis I need to load data from are on api.home.com.

Unless the server is explicitly set up to allow it, I cannot use ajax to load this data, as even pages on separate subdomains are subject to XHR CORS restrictions.

Ideally, set things up to allow x-domain XHR

Ideally, since the api and app are on the same domain, I might have access to set up the headers on api.home.com. If I do, I can add an Access-Control-Allow-Origin: header item granting access to app.home.com. Assuming the header is set up as follows: Access-Control-Allow-Origin: "http://app.home.com", this is far more secure than setting up JSONP. This is because app.home.com can get everything it wants from api.home.com without api.home.com giving CORS access to the whole internet.

The above XHR solution isn't possible. Set up JSONP On my client script: I set up a function to process the reponse from the server when I make the JSONP call.:

function processJSONPResponse(data) {
    var dataFromServer = data;
}

The server will need to be set up to return a mini script looking something like "processJSONPResponse('{"room":"main bedroom","items":["bed","chest of drawers"]}');" It might be designed to return such a string if something like //api.home.com?getdata=room&room=main_bedroom is called.

Then the client sets up a script tag as such:

var script = document.createElement('script');
script.src = '//api.home.com?getdata=room&room=main_bedroom';

document.querySelector('head').appendChild(script);

This loads the script and immediately calls window.processJSONPResponse() as written/ echo/ printed out by the server. The data passed in as the parameter to the function is now stored in the dataFromServer local variable and you can do with it whatever you need.

Clean up

Once the client has the data, ie. immediately after the script is added to the DOM, the script element can be removed from the DOM:

script.parentNode.removeChild(script);

Bluetooth pairing without user confirmation

This need is exactly why createInsecureRfcommSocketToServiceRecord() was added to BluetoothDevice starting in Android 2.3.3 (API Level 10) (SDK Docs)...before that there was no SDK support for this. It was designed to allow Android to connect to devices without user interfaces for entering a PIN code (like an embedded device), but it just as usable for setting up a connection between two devices without user PIN entry.

The corollary method listenUsingInsecureRfcommWithServiceRecord() in BluetoothAdapter is used to accept these types of connections. It's not a security breach because the methods must be used as a pair. You cannot use this to simply attempt to pair with any old Bluetooth device.

You can also do short range communications over NFC, but that hardware is less prominent on Android devices. Definitely pick one, and don't try to create a solution that uses both.

Hope that Helps!

P.S. There are also ways to do this on many devices prior to 2.3 using reflection, because the code did exist...but I wouldn't necessarily recommend this for mass-distributed production applications. See this StackOverflow.

In PHP, how do you change the key of an array element?

Hmm, I'm not test before, but I think this code working

function replace_array_key($data) {
    $mapping = [
        'old_key_1' => 'new_key_1',
        'old_key_2' => 'new_key_2',
    ];

    $data = json_encode($data);
    foreach ($mapping as $needed => $replace) {
        $data = str_replace('"'.$needed.'":', '"'.$replace.'":', $data);
    }

    return json_decode($data, true);
}

How to convert integer to char in C?

To convert int to char use:

int a=8;  
char c=a+'0';
printf("%c",c);       //prints 8  

To Convert char to int use:

char c='5';
int a=c-'0';
printf("%d",a);        //prints 5

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

Original Source - https://www.techrepublic.com/article/how-to-install-mongodb-community-edition-on-ubuntu-linux/


If you're on Ubuntu 16.04 and face the unrecognized service error, these instructions will fix it for you:-

  1. Open a terminal window.
  2. Issue the command sudo apt-key adv —keyserver hkp://keyserver.ubuntu.com:80 —recv EA312927
  3. Issue the command sudo touch /etc/apt/sources.list.d/mongodb-org.list
  4. Issue the command sudo gedit /etc/apt/sources.list.d/mongodb-org.list
  5. Copy and paste one of the following lines from below (depending upon your release) into the open file. For 12.04: deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.6 multiverse For 14.04: deb http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.6 multiverse For 16.04: deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse

Make sure to edit the version number with the appropriate latest version and save the file.

Installation Open a terminal window and issue command sudo apt-get update && sudo apt-get install -y mongodb-org

Let the installation complete.

Running MongoDB To start the database, issue the command sudo service mongodb start. You should now be able to issue the command to see that MongoDB is running: systemctl status mongodb

Ubuntu 16.04 solution If you are using Ubuntu 16.04, you may run into an issue where you see the error mongodb: unrecognized service due to the switch from upstart to systemd. To get around this, you have to follow these steps.

  • If you added the /etc/apt/sources.list.d/mongodb-org.list, remove it with the command sudo rm /etc/apt/sources.list.d/mongodb-org.list

  • Update apt with the command sudo apt-get update

  • Install the official MongoDB version from the standard repositories with the command sudo apt-get install mongodb in order to get the service set up properly

  • Remove what you just installed with the command sudo apt-get remove mongodb && sudo apt-get autoremove

Now follow steps 1 through 5 listed above to install MongoDB; this should re-install the latest version of MongoDB with the systemd services already in place. When you issue the command systemctl status mongodb you should see that the server is active.


I mostly copy pasted the above (with minor modifications and typo fixes) from here - https://www.techrepublic.com/article/how-to-install-mongodb-community-edition-on-ubuntu-linux/

Convert a secure string to plain text

The easiest way to convert back it in PowerShell

[System.Net.NetworkCredential]::new("", $SecurePassword).Password

Select folder dialog WPF

The FolderBrowserDialog class from System.Windows.Forms is the recommended way to display a dialog that allows a user to select a folder.

Until recently, the appearance and behaviour of this dialog was not in keeping with the other filesystem dialogs, which is one of the reasons why people were reluctant to use it.

The good news is that FolderBrowserDialog was "modernized" in NET Core 3.0, so is now a viable option for those writing either Windows Forms or WPF apps targeting that version or later.

In .NET Core 3.0, Windows Forms users [sic] a newer COM-based control that was introduced in Windows Vista: FolderBrowserDialog in NET Core 3.0

To reference System.Windows.Forms in a NET Core WPF app, it is necessary to edit the project file and add the following line:

<UseWindowsForms>true</UseWindowsForms>

This can be placed directly after the existing <UseWPF> element.

Then it's just a case of using the dialog:

using System;
using System.Windows.Forms;

...

using var dialog = new FolderBrowserDialog
{
    Description = "Time to select a folder",
    UseDescriptionForTitle = true,
    SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
        + Path.DirectorySeparatorChar,
    ShowNewFolderButton = true
};

if (dialog.ShowDialog() == DialogResult.OK)
{
    ...
}

FolderBrowserDialog has a RootFolder property that supposedly "sets the root folder where the browsing starts from" but whatever I set this to it didn't make any difference; SelectedPath seemed to be the better property to use for this purpose, however the trailing backslash is required.

Also, the ShowNewFolderButton property seems to be ignored as well, the button is always shown regardless.

Fixed height and width for bootstrap carousel

Apply following style to carousel listbox.

_x000D_
_x000D_
<div class="carousel-inner" role="listbox" style=" width:100%; height: 500px !important;">_x000D_
_x000D_
..._x000D_
_x000D_
</div
_x000D_
_x000D_
_x000D_

Request UAC elevation from within a Python script?

It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:

import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'

if sys.argv[-1] != ASADMIN:
    script = os.path.abspath(sys.argv[0])
    params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
    shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
    sys.exit(0)

Convert negative data into positive data in SQL Server

An easy and straightforward solution using the CASE function:

SELECT CASE WHEN ( a > 0 ) THEN (a*-1) ELSE (a*-1) END AS NegativeA,
       CASE WHEN ( b > 0 ) THEN (b*-1) ELSE (b*-1) END AS PositiveB
FROM YourTableName

What is the optimal way to compare dates in Microsoft SQL server?

You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN would be faster; however, in actual testing they performed the same.

Sorting a Data Table

This worked for me:

dt.DefaultView.Sort = "Town ASC, Cutomer ASC";
dt = dt.DefaultView.ToTable();

How to determine if a number is odd in JavaScript

Many people misunderstand the meaning of odd

  • isOdd("str") should be false.
    Only an integer can be odd.
  • isOdd(1.223) and isOdd(-1.223) should be false.
    A float is not an integer.
  • isOdd(0) should be false.
    Zero is an even integer (https://en.wikipedia.org/wiki/Parity_of_zero).
  • isOdd(-1) should be true.
    It's an odd integer.

Solution

function isOdd(n) {

  // Must be a number
  if (isNaN(n)) {
    return false;
  }

  // Number must not be a float
  if ((n % 1) !== 0) {
    return false;
  }

  // Integer must not be equal to zero
  if (n === 0) {
    return false;
  }

  // Integer must be odd
  if ((n % 2) !== 0) {
    return true;
  }

  return false;
}

JS Fiddle (if needed): https://jsfiddle.net/9dzdv593/8/

1-liner

Javascript 1-liner solution. For those who don't care about readability.

const isOdd = n => !(isNaN(n) && ((n % 1) !== 0) && (n === 0)) && ((n % 2) !== 0) ? true : false;

Func delegate with no return type

All Func delegates return something; all the Action delegates return void.

Func<TResult> takes no arguments and returns TResult:

public delegate TResult Func<TResult>()

Action<T> takes one argument and does not return a value:

public delegate void Action<T>(T obj)

Action is the simplest, 'bare' delegate:

public delegate void Action()

There's also Func<TArg1, TResult> and Action<TArg1, TArg2> (and others up to 16 arguments). All of these (except for Action<T>) are new to .NET 3.5 (defined in System.Core).

Java: Why is the Date constructor deprecated, and what do I use instead?

As the Date constructor is deprecated, you can try this code.

import java.util.Calendar;

  Calendar calendar = Calendar.getInstance();
     calendar.set(Calendar.HOUR_OF_DAY, 6);// for 6 hour
     calendar.set(Calendar.MINUTE, 0);// for 0 min
     calendar.set(Calendar.SECOND, 0);// for 0 sec
     calendar.set(1996,0,26);// for Date [year,month(0 to 11), date]

    Date date = new Date(calendar.getTimeInMillis());// calendar gives long value

    String mConvertedDate = date.toString();// Fri Jan 26 06:00:00 GMT+05:30 1996

Set angular scope variable in markup

You can use the ng-value directive in a hidden field as below :-

<input type="hidden" ng-value="myScopeVar = someValue"/>

This will set the value of the scope variable (myScopeVar) to "someValue"

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

I used the below to solve this problem.

import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);

Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.

Camel Case is usually without spaces between words.

Arrow operator (->) usage in C

#include<stdio.h>

int main()
{
    struct foo
    {
        int x;
        float y;
    } var1;
    struct foo var;
    struct foo* pvar;

    pvar = &var1;
    /* if pvar = &var; it directly 
       takes values stored in var, and if give  
       new > values like pvar->x = 6; pvar->y = 22.4; 
       it modifies the values of var  
       object..so better to give new reference. */
    var.x = 5;
    (&var)->y = 14.3;
    printf("%i - %.02f\n", var.x, (&var)->y);

    pvar->x = 6;
    pvar->y = 22.4;
    printf("%i - %.02f\n", pvar->x, pvar->y);

    return 0;
}

How to make android listview scrollable?

I know this question is 4-5 years old, but still, this might be useful:

Sometimes, if you have only a few elements that "exit the screen", the list might not scroll. That's because the operating system doesn't view it as actually exceeding the screen.

I'm saying this because I ran into this problem today - I only had 2 or 3 elements that were exceeding the screen limits, and my list wasn't scrollable. And it was a real mystery. As soon as I added a few more, it started to scroll.

So you have to make sure it's not a design problem at first, like the list appearing to go beyond the borders of the screen but in reality, "it doesn't", and adjust its dimensions and margin values and see if it's starting to "become scrollable". It did, for me.

Casting objects in Java

Lets say you have Class A as superclass and Class B subclass of A.

public class A {

    public void printFromA(){
        System.out.println("Inside A");
    }
}
public class B extends A {

    public void printFromB(){
        System.out.println("Inside B");
    }

}

public class MainClass {

    public static void main(String []args){

        A a = new B();
        a.printFromA(); //this can be called without typecasting

        ((B)a).printFromB(); //the method printFromB needs to be typecast 
    }
}

How to analyze disk usage of a Docker container

After 1.13.0, Docker includes a new command docker system df to show docker disk usage.

$ docker system df
TYPE            TOTAL        ACTIVE     SIZE        RECLAIMABLE
Images          5            1          2.777 GB    2.647 GB (95%)
Containers      1            1          0 B         0B
Local Volumes   4            1          3.207 GB    2.261 (70%)

To show more detailed information on space usage:

$ docker system df --verbose

Round a divided number in Bash

bash will not give you correct result of 3/2 since it doesn't do floating pt maths. you can use tools like awk

$ awk  'BEGIN { rounded = sprintf("%.0f", 3/2); print rounded }'
2

or bc

$ printf "%.0f" $(echo "scale=2;3/2" | bc)
2

Load an image from a url into a PictureBox

If you are trying to load the image at your form_load, it's a better idea to use the code

pictureBox1.LoadAsync(@"http://google.com/test.png");

not only loading from web but also no lag in your form loading.

Execute script after specific delay using JavaScript

If you only need to test a delay you can use this:

function delay(ms) {
   ms += new Date().getTime();
   while (new Date() < ms){}
}

And then if you want to delay for 2 second you do:

delay(2000);

Might not be the best for production though. More on that in the comments

Right click to select a row in a Datagridview and show a menu to delete it

private void dgvOferty_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
    {
        dgvOferty.ClearSelection();
        int rowSelected = e.RowIndex;
        if (e.RowIndex != -1)
        {
            this.dgvOferty.Rows[rowSelected].Selected = true;
        }
        e.ContextMenuStrip = cmstrip;
    }

TADA :D. The easiest way period. For custom cells just modify a little.

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

used ast, example

In [15]: a = "[{'start_city': '1', 'end_city': 'aaa', 'number': 1},\
...:      {'start_city': '2', 'end_city': 'bbb', 'number': 1},\
...:      {'start_city': '3', 'end_city': 'ccc', 'number': 1}]"
In [16]: import ast
In [17]: ast.literal_eval(a)
Out[17]:
[{'end_city': 'aaa', 'number': 1, 'start_city': '1'},
 {'end_city': 'bbb', 'number': 1, 'start_city': '2'},
 {'end_city': 'ccc', 'number': 1, 'start_city': '3'}]

How to send a POST request using volley with string body?

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("Rest response",response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Rest response",error.toString());
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String,String>();
            params.put("name","xyz");
            return params;
        }

        @Override
        public Map<String,String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String,String>();
            params.put("content-type","application/fesf");
            return params;
        }

    };

    requestQueue.add(stringRequest);

How to delete files older than X hours

You could to this trick: create a file 1 hour ago, and use the -newer file argument.

(Or use touch -t to create such a file).

How to enable SOAP on CentOS

The yum install php-soap command will install the Soap module for php 5.x

For installing the correct version for your environment I recommend to create a file info.php and put this code: <?php echo phpinfo(); ?>

In the header you'll see the version you're using:

enter image description here

Now that you know the correct version you can run this command: yum search php-soap

This command will return the avaliable versions:

php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol

Now you just need to choose the correct module to your php version.

For this example, you should run this command php72-php-soap.x86_64

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

If you have UTF8, use this (actually works with SVG source), like:

btoa(unescape(encodeURIComponent(str)))

example:

 var imgsrc = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(markup)));
 var img = new Image(1, 1); // width, height values are optional params 
 img.src = imgsrc;

If you need to decode that base64, use this:

var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);

Example:

var str = "äöüÄÖÜçéèñ";
var b64 = window.btoa(unescape(encodeURIComponent(str)))
console.log(b64);

var str2 = decodeURIComponent(escape(window.atob(b64)));
console.log(str2);

Note: if you need to get this to work in mobile-safari, you might need to strip all the white-space from the base64 data...

function b64_to_utf8( str ) {
    str = str.replace(/\s/g, '');    
    return decodeURIComponent(escape(window.atob( str )));
}

2017 Update

This problem has been bugging me again.
The simple truth is, atob doesn't really handle UTF8-strings - it's ASCII only.
Also, I wouldn't use bloatware like js-base64.
But webtoolkit does have a small, nice and very maintainable implementation:

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info
*
**/
var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="

    // public method for encoding
    , encode: function (input)
    {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length)
        {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2))
            {
                enc3 = enc4 = 64;
            }
            else if (isNaN(chr3))
            {
                enc4 = 64;
            }

            output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        } // Whend 

        return output;
    } // End Function encode 


    // public method for decoding
    ,decode: function (input)
    {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length)
        {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64)
            {
                output = output + String.fromCharCode(chr2);
            }

            if (enc4 != 64)
            {
                output = output + String.fromCharCode(chr3);
            }

        } // Whend 

        output = Base64._utf8_decode(output);

        return output;
    } // End Function decode 


    // private method for UTF-8 encoding
    ,_utf8_encode: function (string)
    {
        var utftext = "";
        string = string.replace(/\r\n/g, "\n");

        for (var n = 0; n < string.length; n++)
        {
            var c = string.charCodeAt(n);

            if (c < 128)
            {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048))
            {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else
            {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        } // Next n 

        return utftext;
    } // End Function _utf8_encode 

    // private method for UTF-8 decoding
    ,_utf8_decode: function (utftext)
    {
        var string = "";
        var i = 0;
        var c, c1, c2, c3;
        c = c1 = c2 = 0;

        while (i < utftext.length)
        {
            c = utftext.charCodeAt(i);

            if (c < 128)
            {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224))
            {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else
            {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        } // Whend 

        return string;
    } // End Function _utf8_decode 

}

https://www.fileformat.info/info/unicode/utf8.htm

  • For any character equal to or below 127 (hex 0x7F), the UTF-8 representation is one byte. It is just the lowest 7 bits of the full unicode value. This is also the same as the ASCII value.

  • For characters equal to or below 2047 (hex 0x07FF), the UTF-8 representation is spread across two bytes. The first byte will have the two high bits set and the third bit clear (i.e. 0xC2 to 0xDF). The second byte will have the top bit set and the second bit clear (i.e. 0x80 to 0xBF).

  • For all characters equal to or greater than 2048 but less that 65535 (0xFFFF), the UTF-8 representation is spread across three bytes.

Run command on the Ansible host

I'd like to share that Ansible can be run on localhost via shell:

ansible all -i "localhost," -c local -m shell -a 'echo hello world'

This could be helpful for simple tasks or for some hands-on learning of Ansible.

The example of code is taken from this good article:

Running ansible playbook in localhost

Convert a object into JSON in REST service by Spring MVC

Another simple solution is to add jackson-databind dependency in POM.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.1</version>
    </dependency>

Keep Rest of the code as it is.

matplotlib colorbar for scatter

Here is the OOP way of adding a colorbar:

fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)

How to find largest objects in a SQL Server database?

@marc_s's answer is very great and I've been using it for few years. However, I noticed that the script misses data in some columnstore indexes and doesn't show complete picture. E.g. when you do SUM(TotalSpace) against the script and compare it with total space database property in Management Studio the numbers don't match in my case (Management Studio shows larger numbers). I modified the script to overcome this issue and extended it a little bit:

select
    tables.[name] as table_name,
    schemas.[name] as schema_name,
    isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown') as database_name,
    sum(allocation_units.total_pages) * 8 as total_space_kb,
    cast(round(((sum(allocation_units.total_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as total_space_mb,
    sum(allocation_units.used_pages) * 8 as used_space_kb,
    cast(round(((sum(allocation_units.used_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as used_space_mb,
    (sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8 as unused_space_kb,
    cast(round(((sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8) / 1024.00, 2) as numeric(36, 2)) as unused_space_mb,
    count(distinct indexes.index_id) as indexes_count,
    max(dm_db_partition_stats.row_count) as row_count,
    iif(max(isnull(user_seeks, 0)) = 0 and max(isnull(user_scans, 0)) = 0 and max(isnull(user_lookups, 0)) = 0, 1, 0) as no_reads,
    iif(max(isnull(user_updates, 0)) = 0, 1, 0) as no_writes,
    max(isnull(user_seeks, 0)) as user_seeks,
    max(isnull(user_scans, 0)) as user_scans,
    max(isnull(user_lookups, 0)) as user_lookups,
    max(isnull(user_updates, 0)) as user_updates,
    max(last_user_seek) as last_user_seek,
    max(last_user_scan) as last_user_scan,
    max(last_user_lookup) as last_user_lookup,
    max(last_user_update) as last_user_update,
    max(tables.create_date) as create_date,
    max(tables.modify_date) as modify_date
from 
    sys.tables
    left join sys.schemas on schemas.schema_id = tables.schema_id
    left join sys.indexes on tables.object_id = indexes.object_id
    left join sys.partitions on indexes.object_id = partitions.object_id and indexes.index_id = partitions.index_id
    left join sys.allocation_units on partitions.partition_id = allocation_units.container_id
    left join sys.dm_db_index_usage_stats on tables.object_id = dm_db_index_usage_stats.object_id and indexes.index_id = dm_db_index_usage_stats.index_id
    left join sys.dm_db_partition_stats on tables.object_id = dm_db_partition_stats.object_id and indexes.index_id = dm_db_partition_stats.index_id
group by schemas.[name], tables.[name], isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown')
order by 5 desc

Hope it will be helpful for someone. This script was tested against large TB-wide databases with hundreds of different tables, indexes and schemas.

What does character set and collation mean exactly?

I suggest to use utf8mb4_unicode_ci, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.

async at console app in C#?

In most project types, your async "up" and "down" will end at an async void event handler or returning a Task to your framework.

However, Console apps do not support this.

You can either just do a Wait on the returned task:

static void Main()
{
  MainAsync().Wait();
  // or, if you want to avoid exceptions being wrapped into AggregateException:
  //  MainAsync().GetAwaiter().GetResult();
}

static async Task MainAsync()
{
  ...
}

or you can use your own context like the one I wrote:

static void Main()
{
  AsyncContext.Run(() => MainAsync());
}

static async Task MainAsync()
{
  ...
}

More information for async Console apps is on my blog.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

Add play-services-safetynet library in android build.gradle:

implementation 'com.google.android.gms:play-services-safetynet:+'

and add this code to your MainApplication.java:

@Override
  public void onCreate() {
    super.onCreate();
    upgradeSecurityProvider();
    SoLoader.init(this, /* native exopackage */ false);
  }

  private void upgradeSecurityProvider() {
    ProviderInstaller.installIfNeededAsync(this, new ProviderInstallListener() {
      @Override
      public void onProviderInstalled() {

      }

      @Override
      public void onProviderInstallFailed(int errorCode, Intent recoveryIntent) {
//        GooglePlayServicesUtil.showErrorNotification(errorCode, MainApplication.this);
        GoogleApiAvailability.getInstance().showErrorNotification(MainApplication.this, errorCode);
      }
    });
  }

Test if registry value exists

My version:

Function Test-RegistryValue($Key, $Name)
{
    (Get-ChildItem (Split-Path -Parent -Path $Key) | Where-Object {$_.PSChildName -eq (Split-Path -Leaf $Key)}).Property -contains $Name
}

postgresql sequence nextval in schema

The quoting rules are painful. I think you want:

SELECT nextval('foo."SQ_ID"');

to prevent case-folding of SQ_ID.

Display Parameter(Multi-value) in Report

You can use the "Join" function to create a single string out of the array of labels, like this:

=Join(Parameters!Product.Label, ",")

How do I get a list of folders and sub folders without the files?

I am using this from PowerShell:

dir -directory -name -recurse > list_my_folders.txt

Converting BigDecimal to Integer

I found that the above did not work for me. I was pulling a cell value from a JTable but could not cast to double or int etc. My solution:

Object obj = getTable().getValueAt(row, 0);

where row 0 would always be a number. Hope this helps anyone still scrolling!

How to POST JSON request using Apache HttpClient?

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

Delete all the records

If you want to reset your table, you can do

truncate table TableName

truncate needs privileges, and you can't use it if your table has dependents (another tables that have FK of your table,

Exploring Docker container's file system

The file system of the container is in the data folder of docker, normally in /var/lib/docker. In order to start and inspect a running containers file system do the following:

hash=$(docker run busybox)
cd /var/lib/docker/aufs/mnt/$hash

And now the current working directory is the root of the container.

How to use an output parameter in Java?

This is not accurate ---> "...* pass array. arrays are passed by reference. i.e. if you pass array of integers, modified the array inside the method.

Every parameter type is passed by value in Java. Arrays are object, its object reference is passed by value.

This includes an array of primitives (int, double,..) and objects. The integer value is changed by the methodTwo() but it is still the same arr object reference, the methodTwo() cannot add an array element or delete an array element. methodTwo() cannot also, create a new array then set this new array to arr. If you really can pass an array by reference, you can replace that arr with a brand new array of integers.

Every object passed as parameter in Java is passed by value, no exceptions.

Java function for arrays like PHP's join()?

To get "str1, str2" from "str1", "str2", "" :

Stream.of("str1", "str2", "").filter(str -> !str.isEmpty()).collect(Collectors.joining(", ")); 

Also you can add extra null-check

Read input stream twice

if your InputStream support using mark, then you can mark() your inputStream and then reset() it . if your InputStrem doesn't support mark then you can use the class java.io.BufferedInputStream,so you can embed your stream inside a BufferedInputStream like this

    InputStream bufferdInputStream = new BufferedInputStream(yourInputStream);
    bufferdInputStream.mark(some_value);
    //read your bufferdInputStream 
    bufferdInputStream.reset();
    //read it again

Adding a new value to an existing ENUM Type

As discussed above, ALTER command cannot be written inside a transaction. The suggested way is to insert into the pg_enum table directly, by retrieving the typelem from pg_type table and calculating the next enumsortorder number;

Following is the code that I use. (Checks if duplicate value exists before inserting (constraint between enumtypid and enumlabel name)

INSERT INTO pg_enum (enumtypid, enumlabel, enumsortorder)
    SELECT typelem,
    'NEW_ENUM_VALUE',
    (SELECT MAX(enumsortorder) + 1 
        FROM pg_enum e
        JOIN pg_type p
        ON p.typelem = e.enumtypid
        WHERE p.typname = '_mytypename'
    )
    FROM pg_type p
    WHERE p.typname = '_mytypename'
    AND NOT EXISTS (
        SELECT * FROM 
        pg_enum e
        JOIN pg_type p
        ON p.typelem = e.enumtypid
        WHERE e.enumlabel = 'NEW_ENUM_VALUE'
        AND p.typname = '_mytypename'
    )

Note that your type name is prepended with an underscore in the pg_type table. Also, the typname needs to be all lowercase in the where clause.

Now this can be written safely into your db migrate script.

Does C# have extension properties?

Update (thanks to @chaost for pointing this update out):

Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"

Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/


I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.

Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.

So instead of doing this...

public static class IntExtensions
{
   public static bool Even(this int value)
   {
        return value % 2 == 0;
   }
}

We'll be finally able to do it like so...

public extension IntExtension extends int
{
    public bool Even => this % 2 == 0;
}

Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/

Import a file from a subdirectory?

Try import .lib.BoxTime. For more information read about relative import in PEP 328.

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

Convert an integer to a byte array

Check out the "encoding/binary" package. Particularly the Read and Write functions:

binary.Write(a, binary.LittleEndian, myInt)

vector vs. list in STL

When you have a lot of insertion or deletion in the middle of the sequence. e.g. a memory manager.

count (non-blank) lines-of-code in bash

awk '/^[[:space:]]*$/ {++x} END {print x}' "$testfile"

How to extract the substring between two markers?

regular expression

import re

re.search(r"(?<=AAA).*?(?=ZZZ)", your_text).group(0)

The above as-is will fail with an AttributeError if there are no "AAA" and "ZZZ" in your_text

string methods

your_text.partition("AAA")[2].partition("ZZZ")[0]

The above will return an empty string if either "AAA" or "ZZZ" don't exist in your_text.

PS Python Challenge?

Sound alarm when code finishes

This one seems to work on both Windows and Linux* (from this question):

def beep():
    print("\a")

beep()

In Windows, can put at the end:

import winsound
winsound.Beep(500, 1000)

where 500 is the frequency in Herz
      1000 is the duration in miliseconds

To work on Linux, you may need to do the following (from QO's comment):

  • in a terminal, type 'cd /etc/modprobe.d' then 'gksudo gedit blacklist.conf'
  • comment the line that says 'blacklist pcspkr', then reboot
  • check also that the terminal preferences has the 'Terminal Bell' checked.

Hide HTML element by id

.nav ul li a#nav-ask{
    display:none;
}

DropDownList's SelectedIndexChanged event not firing

Also make sure the page is valid. You can check this in the browsers developer tools (F12)

In the Console tab select the correct Target/Frame and check for the [Page_IsValid] property

If the page is not valid the form will not submit and therefore not fire the event.

Java ArrayList of Arrays?

This works very well.

ArrayList<String[]> a = new ArrayList<String[]>();
    a.add(new String[3]);
    a.get(0)[0] = "Zubair";
    a.get(0)[1] = "Borkala";
    a.get(0)[2] = "Kerala";
System.out.println(a.get(0)[1]);

Result will be

Borkala

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

you can use

style="display:none"

Ex:

<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>

ng-repeat: access key and value for each object in array of objects

In fact, your data is not well design. You'd better use something like :

$scope.steps = [
    {stepName: "companyName", isComplete: true},
    {stepName: "businessType", isComplete: true},
    {stepName: "physicalAddress", isComplete: true}
];

Then it is easy to do what you want :

<div ng-repeat="step in steps">
 Step {{step.stepName}} status : {{step.isComplet}}
</div>

Example: http://jsfiddle.net/rX7ba/

creating json object with variables

It's called on Object Literal

I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.

var formObject =  {"formObject": [
                {"firstName": firstName, "lastName": lastName},
                {"phoneNumber": phone},
                {"address": address},
                ]}

Although this seems to make more sense (Why do you have an array in the above literal?):

var formObject = {
   firstName: firstName
   ...
}

Do standard windows .ini files allow comments?

I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.

Edit

The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.

Cannot connect to local SQL Server with Management Studio

Same as matt said. The "SQL Server(SQLEXPRESS)" was stopped. Enabled it by opening Control Panel > Administrative Tools > Services, right-clicking on the "SQL Server(SQLEXPRESS)" service and selecting "Start" from the available options. Could connect fine after that.

HTML display result in text (input) field?

 <HTML>
      <HEAD>
        <TITLE>Sum</TITLE>

        <script type="text/javascript">
          function sum()
          {

             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').value = sum;
          }
        </script>
      </HEAD>

      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
          <INPUT TYPE="text" NAME="number2" VALUE=""/>
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
          <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
        </FORM>

      </BODY>
</HTML>

This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags

How to diff a commit with its parent?

Uses aliases, so doesn't answer your question exactly but I find these useful for doing what you intend...

alias gitdiff-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"
alias gitdiff-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git diff"

alias gitlog-1="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 2|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-2="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 3|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"
alias gitlog-3="git log --reverse|grep commit|cut -d ' ' -f2|tail -n 4|head -n 2|xargs echo|sed -e 's/\s/../'|xargs -n 1 git log --summary"

Get the length of a String

Swift 1.2 Update: There's no longer a countElements for counting the size of collections. Just use the count function as a replacement: count("Swift")

Swift 2.0, 3.0 and 3.1:

let strLength = string.characters.count

Swift 4.2 (4.0 onwards): [Apple Documentation - Strings]

let strLength = string.count

How do you build a Singleton in Dart?

Here's a concise example that combines the other solutions. Accessing the singleton can be done by:

  • Using a singleton global variable that points to the instance.
  • The common Singleton.instance pattern.
  • Using the default constructor, which is a factory that returns the instance.

Note: You should implement only one of the three options so that code using the singleton is consistent.

Singleton get singleton => Singleton.instance;
ComplexSingleton get complexSingleton => ComplexSingleton._instance;

class Singleton {
  static final Singleton instance = Singleton._private();
  Singleton._private();
  factory Singleton() => instance;
}

class ComplexSingleton {
  static ComplexSingleton _instance;
  static ComplexSingleton get instance => _instance;
  static void init(arg) => _instance ??= ComplexSingleton._init(arg);

  final property;
  ComplexSingleton._init(this.property);
  factory ComplexSingleton() => _instance;
}

If you need to do complex initialization, you'll just have to do so before using the instance later in the program.

Example

void main() {
  print(identical(singleton, Singleton.instance));        // true
  print(identical(singleton, Singleton()));               // true
  print(complexSingleton == null);                        // true
  ComplexSingleton.init(0); 
  print(complexSingleton == null);                        // false
  print(identical(complexSingleton, ComplexSingleton())); // true
}

get unique machine id

Check out this article. It is very exhaustive and you will find how to extract various hardware information.

Quote from the article:

To get hardware information, you need to create an object of ManagementObjectSearcher class.

using System.Management;
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
foreach (ManagementObject share in searcher.Get()) {
    // Some Codes ...
}

The Key on the code above, is a variable that is replaced with appropriate data. For example, to get the information of the CPU, you have to replace the Key with Win32_Processor.

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

Remove last commit from remote git repository

Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:

git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit

If you want to still have it in your local repository and only remove it from the remote, then you can use:

git push origin +HEAD^:<name of your branch, most likely 'master'>

How to prevent line breaks in list items using CSS

If you want to achieve this selectively (ie: only to that particular link), you can use a non-breaking space instead of a normal space:

<li>submit&nbsp;resume</li>

https://en.wikipedia.org/wiki/Non-breaking_space#Encodings

edit: I understand that this is HTML, not CSS as requested by the OP, but some may find it helpful…

How to allow only integers in a textbox?

try this instead

Note:This is using Ajax Toolkit

First add Ajax Script Manager and use the below Code to apply filter to the textbox

Provide the Namespace at the beginning of the asp.net page

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<asp:TextBox ID="TxtBox" runat="server"></asp:TextBox>
<cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" Enabled="True" TargetControlID="TxtBox" FilterType="Numbers" FilterMode="ValidChars">
</cc1:FilteredTextBoxExtender>

mysql datetime comparison

But this is obviously performing a 'string' comparison

No. The string will be automatically cast into a DATETIME value.

See 11.2. Type Conversion in Expression Evaluation.

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

How to convert password into md5 in jquery?

Get the field value through the id and send with ajax

var field = $("#field").val();
$.ajax({
    type: "POST",
    url: "db.php",
    data: {variable_name:field},
    async:false,
    dataType:"json",
    success: function(response) {
       alert(response);
    }
 });

At db.php file get the variable name

$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");

Could not find or load main class

Try:

java -cp . p1

This worked for me when I had the same problem, using Fedora (linux)

Javascript onHover event

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

Checking letter case (Upper/Lower) within a string in Java

I have streamlined the answer of @Quirliom above into functions that can be used:

private static boolean hasLength(CharSequence data) {
    if (String.valueOf(data).length() >= 8) return true;
    else return false;
}

private static boolean hasSymbol(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
    return hasSpecial;
}

private static boolean hasUpperCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasUppercase = !password.equals(password.toLowerCase());
    return hasUppercase;
}

private static boolean hasLowerCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasLowercase = !password.equals(password.toUpperCase());
    return hasLowercase;
}

Get value from SimpleXMLElement Object

you can convert array with this function

function xml2array($xml){
$arr = array();

foreach ($xml->children() as $r)
{
    $t = array();
    if(count($r->children()) == 0)
    {
        $arr[$r->getName()] = strval($r);
    }
    else
    {
        $arr[$r->getName()][] = xml2array($r);
    }
}
return $arr;
}

Structure of a PDF file?

You need the PDF Reference manual to start reading about the details and structure of PDF files. I suggest to start with version 1.7.

On windows I used a free tool PDF Analyzer to see the internal structure of PDF files. This will help in your understanding when reading the reference manual.

enter image description here

(I'm affiliated with PDF Analyzer, no intention to promote)

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

How can I reverse a list in Python?

For reversing the same list use:

array.reverse()

To assign reversed list into some other list use:

newArray = array[::-1] 

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

How do I compile a .cpp file on Linux?

You'll need to compile it using:

g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

Get Environment Variable from Docker Container

@aisbaa's answer works if you don't care when the environment variable was declared. If you want the environment variable, even if it has been declared inside of an exec /bin/bash session, use something like:

IFS="=" read -a out <<< $(docker exec container /bin/bash -c "env | grep ENV_VAR" 2>&1)

It's not very pretty, but it gets the job done.

To then get the value, use:

echo ${out[1]}

How to use a BackgroundWorker?

I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;  //Tell the user how the process went
    backgroundWorker1.WorkerReportsProgress = true;
    backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}

//Start Process
private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
    //Check if background worker is doing anything and send a cancellation if it is
    if (backgroundWorker1.IsBusy)
    {
        backgroundWorker1.CancelAsync();
    }

}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);

        //Check if there is a request to cancel the process
        if (backgroundWorker1.CancellationPending)
        {
            e.Cancel = true;
            backgroundWorker1.ReportProgress(0);
            return;
        }
    }
    //If the process exits the loop, ensure that progress is set to 100%
    //Remember in the loop we set i < 100 so in theory the process will complete at 99%
    backgroundWorker1.ReportProgress(100);
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
         lblStatus.Text = "Process was cancelled";
    }
    else if (e.Error != null)
    {
         lblStatus.Text = "There was an error running the process. The thread aborted";
    }
    else
    {
       lblStatus.Text = "Process was completed";
    }
}

JavaScript listener, "keypress" doesn't detect backspace?

KeyPress event is invoked only for character (printable) keys, KeyDown event is raised for all including nonprintable such as Control, Shift, Alt, BackSpace, etc.

UPDATE:

The keypress event is fired when a key is pressed down and that key normally produces a character value

Reference.

how to install gcc on windows 7 machine?

I use msysgit to install gcc on Windows, it has a nice installer which installs most everything that you might need. Most devs will need more than just the compiler, e.g. the shell, shell tools, make, git, svn, etc. msysgit comes with all of that. https://msysgit.github.io/

edit: I am now using msys2. Msys2 uses pacman from Arch Linux to install packages, and includes three environments, for building msys2 apps, 32-bit native apps, and 64-bit native apps. (You probably want to build 32-bit native apps.)

https://msys2.github.io/

You could also go full-monty and install code::blocks or some other gui editor that comes with a compiler. I prefer to use vim and make.

Python Pandas : group by in group by and average?

If you want to first take mean on the combination of ['cluster', 'org'] and then take mean on cluster groups, you can use:

In [59]: (df.groupby(['cluster', 'org'], as_index=False).mean()
            .groupby('cluster')['time'].mean())
Out[59]:
cluster
1          15
2          54
3           6
Name: time, dtype: int64

If you want the mean of cluster groups only, then you can use:

In [58]: df.groupby(['cluster']).mean()
Out[58]:
              time
cluster
1        12.333333
2        54.000000
3         6.000000

You can also use groupby on ['cluster', 'org'] and then use mean():

In [57]: df.groupby(['cluster', 'org']).mean()
Out[57]:
               time
cluster org
1       a    438886
        c        23
2       d      9874
        h        34
3       w         6

What's a concise way to check that environment variables are set in a Unix shell script?

Try this:

[ -z "$STATE" ] && echo "Need to set STATE" && exit 1;

Difference between "include" and "require" in php

<?PHP
echo "Firstline";
include('classes/connection.php');
echo "I will run if include but not on Require";
?>

A very simple Practical example with code. The first echo will be displayed. No matter you use include or require because its runs before include or required.

To check the result, In second line of a code intentionally provide the wrong path to the file or make error in file name. Thus the second echo to be displayed or not will be totally dependent on whether you use require or include.

If you use require the second echo will not execute but if you use include not matter what error comes you will see the result of second echo too.

Efficient SQL test query or validation query that will work across all (or most) databases

How about

SELECT user()

I use this before.MySQL, H2 is OK, I don't know others.