Programs & Examples On #Demos

Google Recaptcha v3 example demo

We use recaptcha-V3 only to see site traffic quality, and used it as non blocking. Since recaptcha-V3 doesn't require to show on site and can be used as hidden but you have to show recaptcha privacy etc links (as recommended)

Script Tag in Head

<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallbackV3&render='SITE KEY' async defer></script>

Note: "async defer" make sure its non blocking which is our specific requirement

JS Code:

<script>
    ReCaptchaCallbackV3 = function() {
        grecaptcha.ready(function() {
            grecaptcha.execute("SITE KEY").then(function(token) {
                $.ajax({
                    type: "POST",
                    url: `https://api.${window.appInfo.siteDomain}/v1/recaptcha/score`,
                    data: {
                        "token" : token,
                    },
                    success: function(data) {
                        if(data.response.success) {
                            window.recaptchaScore = data.response.score;
                            console.log('user score ' + data.response.score)
                        }
                    },
                    error: function() {
                        console.log('error while getting google recaptcha score!')
                    }
                });

            });
        });
    };
</script> 

HTML/Css Code:

there is no html code since our requirement is just to get score and don't want to show recaptcha badge.

Backend - Laravel Code:

Route:

Route::post('/recaptcha/score', 'Api\\ReCaptcha\\RecaptchaScore@index');


Class:

class RecaptchaScore extends Controller
{
    public function index(Request $request)
    {
        $score = null;

        $response = (new Client())->request('post', 'https://www.google.com/recaptcha/api/siteverify', [
            'form_params' => [
                'response' => $request->get('token'),
                'secret' => 'SECRET HERE',
            ],
        ]);

        $score = json_decode($response->getBody()->getContents(), true);

        if (!$score['success']) {
            Log::warning('Google ReCaptcha Score', [
                'class' => __CLASS__,
                'message' => json_encode($score['error-codes']),
            ]);
        }

        return [
            'response' => $score,
        ];
    }
} 

we get back score and save in variable which we later user when submit form.

Reference: https://developers.google.com/recaptcha/docs/v3 https://developers.google.com/recaptcha/

Can I use an HTML input type "date" to collect only a year?

_x000D_
_x000D_
 <!--This yearpicker development from Zlatko Borojevic_x000D_
 html elemnts can generate with java function_x000D_
    and then declare as custom type for easy use in all html documents _x000D_
 For this version for implementacion in your document can use:_x000D_
 1. Save this code for example: "yearonly.html"_x000D_
 2. creaate one div with id="yearonly"_x000D_
 3. Include year picker with function: $("#yearonly").load("yearonly.html"); _x000D_
 _x000D_
 <div id="yearonly"></div>_x000D_
 <script>_x000D_
 $("#yearonly").load("yearonly.html"); _x000D_
 </script>_x000D_
 -->_x000D_
_x000D_
 _x000D_
 _x000D_
 <!DOCTYPE html>_x000D_
 <meta name="viewport" content="text-align:center; width=device-width, initial-scale=1.0">_x000D_
 <html>_x000D_
 <body>_x000D_
 <style>_x000D_
 .ydiv {_x000D_
 border:solid 1px;_x000D_
 width:200px;_x000D_
 //height:150px;_x000D_
 background-color:#D8D8D8;_x000D_
 display:none;_x000D_
 position:absolute;_x000D_
 top:40px;_x000D_
 }_x000D_
_x000D_
 .ybutton {_x000D_
_x000D_
    border: none;_x000D_
    width:35px;_x000D_
 height:35px;_x000D_
    background-color:#D8D8D8;_x000D_
 font-size:100%;_x000D_
 }_x000D_
_x000D_
 .yhr {_x000D_
 background-color:black;_x000D_
 color:black;_x000D_
 height:1px">_x000D_
 }_x000D_
_x000D_
 .ytext {_x000D_
 border:none;_x000D_
 text-align:center;_x000D_
 width:118px;_x000D_
 font-size:100%;_x000D_
 background-color:#D8D8D8;_x000D_
 font-weight:bold;_x000D_
_x000D_
 }_x000D_
 </style>_x000D_
 <p>_x000D_
 <!-- input text for display result of yearpicker -->_x000D_
 <input type = "text" id="yeardate"><button style="width:21px;height:21px"onclick="enabledisable()">V</button></p>_x000D_
_x000D_
 <!-- yearpicker panel for change only year-->_x000D_
 <div class="ydiv" id = "yearpicker">_x000D_
 <button class="ybutton" style="font-weight:bold;"onclick="changedecade('back')"><</button>_x000D_
_x000D_
 <input class ="ytext" id="dec"  type="text" value ="2018" >_x000D_
 _x000D_
 <button class="ybutton" style="font-weight:bold;" onclick="changedecade('next')">></button>_x000D_
 <hr></hr>_x000D_
_x000D_
_x000D_
_x000D_
    <!-- subpanel with one year 0-9 -->_x000D_
 <button  class="ybutton"  onclick="yearone = 0;setyear()">0</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 1;setyear()">1</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 2;setyear()">2</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 3;setyear()">3</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 4;setyear()">4</button><br>_x000D_
 <button  class="ybutton"  onclick="yearone = 5;setyear()">5</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 6;setyear()">6</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 7;setyear()">7</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 8;setyear()">8</button>_x000D_
 <button  class="ybutton"  onclick="yearone = 9;setyear()">9</button>_x000D_
 </div>_x000D_
    <!-- end year panel -->_x000D_
_x000D_
_x000D_
_x000D_
 <script>_x000D_
 var date = new Date();_x000D_
 var year = date.getFullYear(); //get current year_x000D_
 //document.getElementById("yeardate").value = year;// can rem if filing text from database_x000D_
_x000D_
 var yearone = 0;_x000D_
 _x000D_
 function changedecade(val1){ //change decade for year_x000D_
_x000D_
 var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
 if (val1 == "next"){_x000D_
 document.getElementById('dec').value = x + 10;_x000D_
 }else{_x000D_
 document.getElementById('dec').value = x - 10;_x000D_
 }_x000D_
 }_x000D_
 _x000D_
 function setyear(){ //set full year as sum decade and one year in decade_x000D_
 var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
    var y = parseFloat(yearone);_x000D_
_x000D_
 var suma = x + y;_x000D_
    var d = new Date();_x000D_
    d.setFullYear(suma);_x000D_
 var year = d.getFullYear();_x000D_
 document.getElementById("dec").value = year;_x000D_
 document.getElementById("yeardate").value = year;_x000D_
 document.getElementById("yearpicker").style.display = "none";_x000D_
 yearone = 0;_x000D_
 }_x000D_
 _x000D_
 function enabledisable(){ //enable/disable year panel_x000D_
 if (document.getElementById("yearpicker").style.display == "block"){_x000D_
 document.getElementById("yearpicker").style.display = "none";}else{_x000D_
 document.getElementById("yearpicker").style.display = "block";_x000D_
 }_x000D_
 _x000D_
 }_x000D_
 </script>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

Change the Bootstrap Modal effect

Here is pure Bootstrap 4 with CSS 3 solution.

<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>
.fade2 {
    transform: scale(0.9);
    opacity: 0;
    transition: all .2s linear;
    display: block !important;
}

.fade2.show {
    opacity: 1;
    transform: scale(1);
}
$('#exampleModal').modal();

function afterModalTransition(e) {
  e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
    setTimeout( () => afterModalTransition(this), 200);
})

Full example here.

Maybe it will help someone.

--

Thank you @DavidDomain too.

How can I validate google reCAPTCHA v2 using javascript/jQuery?

This Client side verification of reCaptcha - the following worked for me :

if reCaptcha is not validated on client side grecaptcha.getResponse(); returns null, else is returns a value other than null.

Javascript Code:

var response = grecaptcha.getResponse();

if(response.length == 0)
    //reCaptcha not verified

else
    //reCaptch verified

Error inflating class android.support.v7.widget.Toolbar?

For me, the error was that I had:

    <android:support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

instead of:

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"/>

Specifically, I had a colon between "android" and "support" on the first line instead of a period.

Flexbox and Internet Explorer 11 (display:flex in <html>?)

Here is an example of using flex that also works in Internet Explorer 11 and Chrome.

HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >_x000D_
<title>Flex Test</title>_x000D_
<style>_x000D_
html, body {_x000D_
    margin: 0px;_x000D_
    padding: 0px;_x000D_
    height: 100vh;_x000D_
}_x000D_
.main {_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -ms-flex-direction: row;_x000D_
    flex-direction: row;_x000D_
    align-items: stretch;_x000D_
    min-height: 100vh;_x000D_
}_x000D_
_x000D_
.main::after {_x000D_
  content: '';_x000D_
  height: 100vh;_x000D_
  width: 0;_x000D_
  overflow: hidden;_x000D_
  visibility: hidden;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.left {_x000D_
    width: 200px;_x000D_
    background: #F0F0F0;_x000D_
    flex-shrink: 0;_x000D_
}_x000D_
_x000D_
.right {_x000D_
    flex-grow: 1;_x000D_
    background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class="main">_x000D_
    <div class="left">_x000D_
        <div style="height: 300px;">_x000D_
        </div>_x000D_
    </div>_x000D_
_x000D_
    <div class="right">_x000D_
        <div style="height: 1000px;">_x000D_
            test test test_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

"The public type <<classname>> must be defined in its own file" error in Eclipse

error in the very first line public class StaticDemo {

Any Class A which has access modifier as public must have a separate source file as A.java or A.jav. This is specified in JLS 7.6 section:

If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:

  • The type is referred to by code in other compilation units of the package in which the type is declared.

  • The type is declared public (and therefore is potentially accessible from code in other packages).

However, you may have to remove public access modifier from the Class declaration StaticDemo. Then as StaticDemo class will have no modifier it will become package-private, That is, it will be visible only within its own package.

Check out Controlling Access to Members of a Class

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    })
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;
        jqTag.data('autocomplete-item', ui.item);
    })
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
            jqTag.data('autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);
    });
})();

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

Show hide divs on click in HTML and CSS without jQuery

Using label and checkbox input

Keeps the selected item opened and togglable.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="checkbox"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="checkbox">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using label and named radio input

Similar to checkboxes, it just closes the already opened one.
Use name="c1" type="radio" on both inputs.

_x000D_
_x000D_
.collapse{_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse + input{_x000D_
  display: none; /* hide the checkboxes */_x000D_
}_x000D_
.collapse + input + div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse + input:checked + div{_x000D_
  display:block;_x000D_
}
_x000D_
<label class="collapse" for="_1">Collapse 1</label>_x000D_
<input id="_1" type="radio" name="c1"> _x000D_
<div>Content 1</div>_x000D_
_x000D_
<label class="collapse" for="_2">Collapse 2</label>_x000D_
<input id="_2" type="radio" name="c1">_x000D_
<div>Content 2</div>
_x000D_
_x000D_
_x000D_

Using tabindex and :focus

Similar to radio inputs, additionally you can trigger the states using the Tab key.
Clicking outside of the accordion will close all opened items.

_x000D_
_x000D_
.collapse > a{_x000D_
  background: #cdf;_x000D_
  cursor: pointer;_x000D_
  display: block;_x000D_
}_x000D_
.collapse:focus{_x000D_
  outline: none;_x000D_
}_x000D_
.collapse > div{_x000D_
  display: none;_x000D_
}_x000D_
.collapse:focus div{_x000D_
  display: block; _x000D_
}
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 1</a>_x000D_
  <div>Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse" tabindex="1">_x000D_
  <a>Collapse 2</a>_x000D_
  <div>Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using :target

Similar to using radio input, you can additionally use Tab and keys to operate

_x000D_
_x000D_
.collapse a{_x000D_
  display: block;_x000D_
  background: #cdf;_x000D_
}_x000D_
.collapse > div{_x000D_
  display:none;_x000D_
}_x000D_
.collapse > div:target{_x000D_
  display:block; _x000D_
}
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_1">Collapse 1</a>_x000D_
  <div id="targ_1">Content 1....</div>_x000D_
</div>_x000D_
_x000D_
<div class="collapse">_x000D_
  <a href="#targ_2">Collapse 2</a>_x000D_
  <div id="targ_2">Content 2....</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using <detail> and <summary> tags (pure HTML)

You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer.

_x000D_
_x000D_
<details>_x000D_
  <summary>Collapse 1</summary>_x000D_
  <p>Content 1...</p>_x000D_
</details>_x000D_
<details>_x000D_
  <summary>Collapse 2</summary>_x000D_
  <p>Content 2...</p>_x000D_
</details>
_x000D_
_x000D_
_x000D_

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

Adding this as a second reference because I had a similar problem..
I had to explicitly add '.aar' as a registered file type under the 'Archives' category in AS settings.

Change selected value of kendo ui dropdownlist

Since this is one of the top search results for questions related to this I felt it was worth mentioning how you can make this work with Kendo().DropDownListFor() as well.

Everything is the same as with OnaBai's post except for how you select the item based off of its text and your selector.

To do that you would swap out dataItem.symbol for dataItem.[DataTextFieldName]. Whatever model field you used for .DataTextField() is what you will be comparing against.

@(Html.Kendo().DropDownListFor(model => model.Status.StatusId)
    .Name("Status.StatusId")
    .DataTextField("StatusName")
    .DataValueField("StatusId")
    .BindTo(...)
)

//So that your ViewModel gets bound properly on the post, naming is a bit 
//different and as such you need to replace the periods with underscores
var ddl = $('#Status_StatusId').data('kendoDropDownList');    

ddl.select(function(dataItem) {
    return dataItem.StatusName === "Active";
});

Advantages of using display:inline-block vs float:left in CSS

In 3 words: inline-block is better.

Inline Block

The only drawback to the display: inline-block approach is that in IE7 and below an element can only be displayed inline-block if it was already inline by default. What this means is that instead of using a <div> element you have to use a <span> element. It's not really a huge drawback at all because semantically a <div> is for dividing the page while a <span> is just for covering a span of a page, so there's not a huge semantic difference. A huge benefit of display:inline-block is that when other developers are maintaining your code at a later point, it is much more obvious what display:inline-block and text-align:right is trying to accomplish than a float:left or float:right statement. My favorite benefit of the inline-block approach is that it's easy to use vertical-align: middle, line-height and text-align: center to perfectly center the elements, in a way that is intuitive. I found a great blog post on how to implement cross-browser inline-block, on the Mozilla blog. Here is the browser compatibility.

Float

The reason that using the float method is not suited for layout of your page is because the float CSS property was originally intended only to have text wrap around an image (magazine style) and is, by design, not best suited for general page layout purposes. When changing floated elements later, sometimes you will have positioning issues because they are not in the page flow. Another disadvantage is that it generally requires a clearfix otherwise it may break aspects of the page. The clearfix requires adding an element after the floated elements to stop their parent from collapsing around them which crosses the semantic line between separating style from content and is thus an anti-pattern in web development.

Any white space problems mentioned in the link above could easily be fixed with the white-space CSS property.

Edit:

SitePoint is a very credible source for web design advice and they seem to have the same opinion that I do:

If you’re new to CSS layouts, you’d be forgiven for thinking that using CSS floats in imaginative ways is the height of skill. If you have consumed as many CSS layout tutorials as you can find, you might suppose that mastering floats is a rite of passage. You’ll be dazzled by the ingenuity, astounded by the complexity, and you’ll gain a sense of achievement when you finally understand how floats work.

Don’t be fooled. You’re being brainwashed.

http://www.sitepoint.com/give-floats-the-flick-in-css-layouts/

2015 Update - Flexbox is a good alternative for modern browsers:

.container {
  display: flex; /* or inline-flex */
}

.item {
  flex: none | [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
}

More info

Dec 21, 2016 Update

Bootstrap 4 is removing support for IE9, and thus is getting rid of floats from rows and going full Flexbox.

Pull request #21389

CSS3 Spin Animation

To rotate, you can use key frames and a transform.

div {
    margin: 20px;
    width: 100px; 
    height: 100px;    
    background: #f00;
    -webkit-animation-name: spin;
    -webkit-animation-duration: 40000ms;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    -moz-animation-name: spin;
    -moz-animation-duration: 40000ms;
    -moz-animation-iteration-count: infinite;
    -moz-animation-timing-function: linear;
    -ms-animation-name: spin;
    -ms-animation-duration: 40000ms;
    -ms-animation-iteration-count: infinite;
    -ms-animation-timing-function: linear;
}

@-webkit-keyframes spin {
  from {
    -webkit-transform:rotate(0deg);
  }

  to {
    -webkit-transform:rotate(360deg);
  }
}

Example

Simulating Button click in javascript

Since you are using jQuery you can use this onClick handler which calls click:

$("#datepicker").click()

This is the same as $("#datepicker").trigger("click").

For a jQuery-free version check out this answer on SO.

make bootstrap twitter dialog modal draggable

i did this:

$("#myModal").modal({}).draggable();

and it make my very standard/basic modal draggable.

not sure how/why it worked, but it did.

Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers

It is most likely due to a cross-origin request, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Make sure that you haven't already used header in another file, or you will get a nasty error. See the docs for more.

Can media queries resize based on a div element instead of the screen?

From a layout perspective, it is possible using modern techniques.

Its made up (I believe) by Heydon Pickering. He details the process here: http://www.heydonworks.com/article/the-flexbox-holy-albatross

Chris Coyier picks it up and works through a demo of it here: https://css-tricks.com/putting-the-flexbox-albatross-to-real-use/

To restate the issue, below we see 3 of the same component, each made up of three orange divs labelled a, b and c.

The second two's blocks display vertically, because they are limited on horizontal room, while the top components 3 blocks are laid out horizontally.

It uses the flex-basis CSS property and CSS Variables to create this effect.

Final example

.panel{
  display: flex;
  flex-wrap: wrap;
  border: 1px solid #f00;
  $breakpoint: 600px;
  --multiplier: calc( #{$breakpoint} - 100%);
  .element{
    min-width: 33%;
    max-width: 100%;
    flex-grow: 1;
    flex-basis: calc( var(--multiplier) * 999 );
  }
}

Demo

Heydon's article is 1000 words explaining it in detail, and I'd highly recommend reading it.

How to handle windows file upload using Selenium WebDriver?

Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.

Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");

Please use below link for further assistance: http://www.guru99.com/use-autoit-selenium.html

How can JavaScript save to a local file?

Based on http://html5-demos.appspot.com/static/a.download.html:

var fileContent = "My epic novel that I don't want to lose.";
var bb = new Blob([fileContent ], { type: 'text/plain' });
var a = document.createElement('a');
a.download = 'download.txt';
a.href = window.URL.createObjectURL(bb);
a.click();

Modified the original fiddle: http://jsfiddle.net/9av2mfjx/

jQuery dialog popup

This HTML is fine:

<a href="#" id="contactUs">Contact Us</a>                   
<div id="dialog" title="Contact form">
  <p>appear now</p>
</div>

You need to initialize the Dialog (not sure if you are doing this):

$(function() {
  // this initializes the dialog (and uses some common options that I do)
  $("#dialog").dialog({
    autoOpen : false, modal : true, show : "blind", hide : "blind"
  });

  // next add the onclick handler
  $("#contactUs").click(function() {
    $("#dialog").dialog("open");
    return false;
  });
});

Making a button invisible by clicking another button in HTML

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

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

How to check if input date is equal to today's date?

TodayDate = new Date();
if (TodayDate > AnotherDate) {} else{}

< = also works, Although with =, it might have to match the milliseconds.

HTML 5 Geo Location Prompt in Chrome

if you're hosting behind a server, and still facing issues: try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/

The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).

For my sanity check I was using Remy Sharp's demo: https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html

and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):

"User denied Geolocation"

I made the following change to get more detailed error message:

function error(msg) {
  var s = document.querySelector('#status');
  msg = msg.message ? msg.message : msg; //add this line
  s.innerHTML = typeof msg == 'string' ? msg : "failed";
  s.className = 'fail';

  // console.log(arguments);
}

failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :

"The current location cannot be determined"

Javascript Drag and drop for touch devices

You can use the Jquery UI for drag and drop with an additional library that translates mouse events into touch which is what you need, the library I recommend is https://github.com/furf/jquery-ui-touch-punch, with this your drag and drop from Jquery UI should work on touch devises

or you can use this code which I am using, it also converts mouse events into touch and it works like magic.

function touchHandler(event) {
    var touch = event.changedTouches[0];

    var simulatedEvent = document.createEvent("MouseEvent");
        simulatedEvent.initMouseEvent({
        touchstart: "mousedown",
        touchmove: "mousemove",
        touchend: "mouseup"
    }[event.type], true, true, window, 1,
        touch.screenX, touch.screenY,
        touch.clientX, touch.clientY, false,
        false, false, false, 0, null);

    touch.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() {
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);
}

And in your document.ready just call the init() function

code found from Here

How do I format date in jQuery datetimepicker?

This works for me. Since it "extends" datepicker we can still use dateFormat:'dd/mm/yy'.

$(function() {
    $('.jqueryui-marker-datepicker').datetimepicker({
        showSecond: true,
        dateFormat: 'dd/mm/yy',
      timeFormat: 'hh:mm:ss',
      stepHour: 2,
      stepMinute: 10,
      stepSecond: 10

     });
});

Loading existing .html file with android WebView

If your structure should be like this:

/assets/html/index.html

/assets/scripts/index.js

/assets/css/index.css

Then just do ( Android WebView: handling orientation changes )

    if(WebViewStateHolder.INSTANCE.getBundle() == null) { //this works only on single instance of webview, use a map with TAG if you need more
        webView.loadUrl("file:///android_asset/html/index.html");
    } else {
        webView.restoreState(WebViewStateHolder.INSTANCE.getBundle());
    }

Make sure you add

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
    }

Then just use urls

<html>
<head>
    <meta charset="utf-8">
    <title>Zzzz</title>
    <script src="../scripts/index.js"></script>
    <link rel="stylesheet" type="text/css" href="../css/index.css">

Good tutorial for using HTML5 History API (Pushstate?)

Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:

http://railscasts.com/episodes/246-ajax-history-state

How to Animate Addition or Removal of Android ListView Rows

After inserting new row to ListView, I just scroll the ListView to new position.

ListView.smoothScrollToPosition(position);

How can I make a horizontal ListView in Android?

After reading this post, I have implemented my own horizontal ListView. You can find it here: http://dev-smart.com/horizontal-listview/ Let me know if this helps.

How can I disable a button on a jQuery UI dialog?

The following works from within the buttons click function:

$(function() {
    $("#dialog").dialog({
        height: 'auto', width: 700, modal: true,
        buttons: {
            'Add to request list': function(evt) {

                // get DOM element for button
                var buttonDomElement = evt.target;
                // Disable the button
                $(buttonDomElement).attr('disabled', true);

                $('form').submit();
            },
            'Cancel': function() {
                $(this).dialog('close');
            }
        }
    });
}

jQuery UI accordion that keeps multiple sections open?

Just call each section of the accordion as its own accordion. active: n will be 0 for the first one( so it will display) and 1, 2, 3, 4, etc for the rest. Since each one is it's own accordion, they will all have only 1 section, and the rest will be collapsed to start.

$('.accordian').each(function(n, el) {
  $(el).accordion({
    heightStyle: 'content',
    collapsible: true,
    active: n
  });
});

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

Jquery UI Datepicker not displaying

This may be helpful to someone. If you copied and pasted your form data (which has the datepicker input box, ensure you do not inadvertently copy the class="hasDatepicker"

This means your input box should look like this:

<input id="dateChooser" name="dateChooser" type="text" value=""/>

NOT

<input id="dateChooser" name="dateChooser" type="text" value="" class="hasDatepicker">

I made that mistake inadvertently. Removing the class and allowing the jQuery UI call appeared to fix it.

Hope that helps someone!

How to run a makefile in Windows?

Check out GnuWin's make (for windows), which provides a native port for Windows (without requiring a full runtime environment like Cygwin)

If you have winget, you can install via the CLI like this:

winget install GnuWin32.Make

Also, be sure to add the install path to your system PATH:

C:\Program Files (x86)\GnuWin32\bin

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

How do I localize the jQuery UI Datepicker?

  $.datepicker.setDefaults({
    closeText: "??",
    prevText: "&#x3C;??",
    nextText: "??&#x3E;",
    currentText: "??",
    monthNames: [ "??","??","??","??","??","??",
    "??","??","??","??","???","???" ],
    monthNamesShort: [ "??","??","??","??","??","??",
    "??","??","??","??","???","???" ],
    dayNames: [ "???","???","???","???","???","???","???" ],
    dayNamesShort: [ "??","??","??","??","??","??","??" ],
    dayNamesMin: [ "?","?","?","?","?","?","?" ],
    weekHeader: "?",
    dateFormat: "yy-mm-dd",
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: true,
    yearSuffix: "?"
  });

the i18n code could be copied from https://github.com/jquery/jquery-ui/tree/master/ui/i18n

What's the best UI for entering date of birth?

As perhaps one of the older people here, and born late in the month, I find drop-down menus for birthdates to be frustrating. I typically have to scroll down on two drop-down menus, and that's awkward. I'd much rather type it in.

If you can have a control designed so that it can either accept drop-down menus or be typed into, and make it clear both work, that would be excellent.

jQuery datepicker years shown

If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years" demo , and hit view source:

$("#restricting").datepicker({ 
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both", 
    buttonImage: "templates/images/calendar.gif", 
    buttonImageOnly: true 
});

You'll want to do the same (obviously changing -20 to -100 or something).

grid controls for ASP.NET MVC?

We have been using jqGrid on a project and have had some good luck with it. Lots of options for inline editing, etc. If that stuff isn't necessary, then we've just used a plain foreach loop like @Hrvoje.

Not able to access adb in OS X through Terminal, "command not found"

It's working fine..

brew install android-sdk

Later on:

android update sdk --no-ui --filter 'platform-tools'

How can I do an OrderBy with a dynamic string parameter?

You need to use the LINQ Dynamic Query Library in order to pass parameters at runtime,

This will allow linq statements like

string orderedBy = "Description";
var query = (from p in products
            orderby(orderedBy)
            select p);

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use a simple regex like this:

public static string StripHTML(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}

Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)

Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?

How to include scripts located inside the node_modules folder?

I would use the path npm module and then do something like this:

var path = require('path');
app.use('/scripts', express.static(path.join(__dirname, 'node_modules/bootstrap/dist')));

IMPORTANT: we use path.join to make paths joining using system agnostic way, i.e. on windows and unix we have different path separators (/ and )

SimpleXML - I/O warning : failed to load external entity

this also works:

$url = "http://www.some-url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml=simplexml_load_string($xmlresponse);

then I just run a forloop to grab the stuff from the nodes.

like this:`

for($i = 0; $i < 20; $i++) {
$title = $xml->channel->item[$i]->title;
$link = $xml->channel->item[$i]->link;
$desc = $xml->channel->item[$i]->description;
$html .="<div><h3>$title</h3>$link<br />$desc</div><hr>";
}
echo $html;

***note that your node names will differ, obviously..and your HTML might be structured differently...also your loop might be set to higher or lower amount of results.

No connection could be made because the target machine actively refused it 127.0.0.1

If you have this while Fiddler is running -> in Fiddler, go to 'Rules' and disable 'Automatically Authenticate' and it should work again.

Set transparent background of an imageview on Android

One more simple way:

mComponentName.setBackgroundResource(android.R.color.transparent);

Convert a python UTC datetime to a local datetime using only python standard library?

Python 3.9 adds the zoneinfo module so now it can be done as follows (stdlib only):

from zoneinfo import ZoneInfo
from datetime import datetime

utc_unaware = datetime(2020, 10, 31, 12)  # loaded from database
utc_aware = utc_unaware.replace(tzinfo=ZoneInfo('UTC'))  # make aware
local_aware = utc_aware.astimezone(ZoneInfo('localtime'))  # convert

Central Europe is 1 or 2 hours ahead of UTC, so local_aware is:

datetime.datetime(2020, 10, 31, 13, 0, tzinfo=backports.zoneinfo.ZoneInfo(key='localtime'))

as str:

2020-10-31 13:00:00+01:00

Windows has no system time zone database, so here an extra package is needed:

pip install tzdata  

There is a backport to allow use in Python 3.6 to 3.8:

sudo pip install backports.zoneinfo

Then:

from backports.zoneinfo import ZoneInfo

How to use `replace` of directive definition?

As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.

First result:

<span myd1="">directive template1</span>

Second result:

<div myd2=""><span>directive template2</span></div>

console.log showing contents of array object

there are two potential simple solutions to dumping an array as string. Depending on the environment you're using:

…with modern browsers use JSON:

JSON.stringify(filters);
// returns this
"{"dvals":[{"brand":"1","count":"1"},{"brand":"2","count":"2"},{"brand":"3","count":"3"}]}"

…with something like node.js you can use console.info()

console.info(filters);
// will output:
{ dvals: 
[ { brand: '1', count: '1' },
  { brand: '2', count: '2' },
  { brand: '3', count: '3' } ] }

Edit:

JSON.stringify comes with two more optional parameters. The third "spaces" parameter enables pretty printing:

JSON.stringify(
                obj,      // the object to stringify
                replacer, // a function or array transforming the result
                spaces    // prettyprint indentation spaces
              )

example:

JSON.stringify(filters, null, "  ");
// returns this
"{
 "dvals": [
  {
   "brand": "1",
   "count": "1"
  },
  {
   "brand": "2",
   "count": "2"
  },
  {
   "brand": "3",
   "count": "3"
  }
 ]
}"

Android Notification Sound

Just put your sound file in the Res\raw\siren.mp3 folder, then use this code:

For Custom Sound:

Notification notification = builder.build();
notification.sound = Uri.parse("android.resource://"
            + context.getPackageName() + "/" + R.raw.siren);

For Default Sound:

notification.defaults |= Notification.DEFAULT_SOUND;

For Custom Vibrate:

long[] vibrate = { 0, 100, 200, 300 };
notification.vibrate = vibrate;

For Default Vibrate:

notification.defaults |= Notification.DEFAULT_VIBRATE;

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

In case it helps anyone I will post what worked for me.

I had to plug my S3 into a direct USB port of my PC for it to prompt me to accept the RSA signature. I had my S3 plugged into a hub before then.

Now the S3 is detected when using both the direct USB port of the PC and via the hub.

NOTE - You may need to also run adb devices from the command line to get your S3 to re-request permission.

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
9283759342847566        unauthorized

...accept signature on phone...

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
9283759342847566        device

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Add vertical whitespace using Twitter Bootstrap?

Wrapping works but when you just want a space, I like:

<div class="col-xs-12" style="height:50px;"></div>

JSLint says "missing radix parameter"

Just put an empty string in the radix place, because parseInt() take two arguments:

parseInt(string, radix);

string The value to parse. If the string argument is not a string, then it is converted to a string (using the ToString abstract operation). Leading whitespace in the string argument is ignored.

radix An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above-mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified, usually defaulting the value to 10.

imageIndex = parseInt(id.substring(id.length - 1))-1;
imageIndex = parseInt(id.substring(id.length - 1), '')-1;

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

How to initialize struct?

Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.

In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:

  • You could have the only public field be the string, and then have a read-only "helper" property called length which would report its length if the string is non-null, or return zero if the string is null.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length would be a property that would report the length of the stored string.

  • You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode value.

It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.

PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.

specifying goal in pom.xml

Add the goal like -

 <build>
        <defaultGoal>install</defaultGoal>
        <!-- Source directory configuration -->
        <sourceDirectory>src</sourceDirectory>
</build>

This will solve the issue

dropzone.js - how to do something after ALL files are uploaded

I up-voted you as your method is simple. I did make only a couple of slight amends as sometimes the event fires even though there are no bytes to send - On my machine it did it when I clicked the remove button on a file.

myDropzone.on("totaluploadprogress", function(totalPercentage, totalBytesToBeSent, totalBytesSent ){
            if(totalPercentage >= 100 && totalBytesSent) {
                // All done! Call func here
            }
        });

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

Is there a limit on number of tcp/ip connections between machines on linux?

The quick answer is 2^16 TCP ports, 64K.

The issues with system imposed limits is a configuration issue, already touched upon in previous comments.

The internal implications to TCP is not so clear (to me). Each port requires memory for it's instantiation, goes onto a list and needs network buffers for data in transit.

Given 64K TCP sessions the overhead for instances of the ports might be an issue on a 32-bit kernel, but not a 64-bit kernel (correction here gladly accepted). The lookup process with 64K sessions can slow things a bit and every packet hits the timer queues, which can also be problematic. Storage for in transit data can theoretically swell to the window size times ports (maybe 8 GByte).

The issue with connection speed (mentioned above) is probably what you are seeing. TCP generally takes time to do things. However, it is not required. A TCP connect, transact and disconnect can be done very efficiently (check to see how the TCP sessions are created and closed).

There are systems that pass tens of gigabits per second, so the packet level scaling should be OK.

There are machines with plenty of physical memory, so that looks OK.

The performance of the system, if carefully configured should be OK.

The server side of things should scale in a similar fashion.

I would be concerned about things like memory bandwidth.

Consider an experiment where you login to the local host 10,000 times. Then type a character. The entire stack through user space would be engaged on each character. The active footprint would likely exceed the data cache size. Running through lots of memory can stress the VM system. The cost of context switches could approach a second!

This is discussed in a variety of other threads: https://serverfault.com/questions/69524/im-designing-a-system-to-handle-10000-tcp-connections-per-second-what-problems

Iterating through a List Object in JSP

another example with just scriplets, when iterating through an ArrayList that contains Maps.

<%   
java.util.List<java.util.Map<String,String>> employees=(java.util.List<java.util.Map<String, String>>)request.getAttribute("employees");    

for (java.util.Map employee: employees) {
%>
<tr>
<td><input value="<%=employee.get("fullName") %>"/></td>    
</tr>
...
<%}%>

How do I add multiple conditions to "ng-disabled"?

Actually the ng-disabled directive works with the " || " logical operator for me. The " && " evaluate only one condition.

http://jsbin.com/kuqilejesi/2/edit?html,js,output

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

Java RegEx meta character (.) and ordinary dot?

Perl-style regular expressions (which the Java regex engine is more or less based upon) treat the following characters as special characters:

.^$|*+?()[{\ have special meaning outside of character classes,

]^-\ have special meaning inside of character classes ([...]).

So you need to escape those (and only those) symbols depending on context (or, in the case of character classes, place them in positions where they can't be misinterpreted).

Needlessly escaping other characters may work, but some regex engines will treat this as syntax errors, for example \_ will cause an error in .NET.

Some others will lead to false results, for example \< is interpreted as a literal < in Perl, but in egrep it means "word boundary".

So write -?\d+\.\d+\$ to match 1.50$, -2.00$ etc. and [(){}[\]] for a character class that matches all kinds of brackets/braces/parentheses.

If you need to transform a user input string into a regex-safe form, use java.util.regex.Pattern.quote.

Further reading: Jan Goyvaert's blog RegexGuru on escaping metacharacters

R apply function with multiple parameters

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
mapply(mult_one,vars1,vars2)

which gives you:

> mapply(mult_one,vars1,vars2)
[1] 10 40 90

How to convert date to timestamp?

For those who wants to have readable timestamp in format of, yyyymmddHHMMSS

> (new Date()).toISOString().replace(/[^\d]/g,'')              // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"

Usage example: a backup file extension. /my/path/my.file.js.20190220

List<String> to ArrayList<String> conversion issue

Cast works where the actual instance of the list is an ArrayList. If it is, say, a Vector (which is another extension of List) it will throw a ClassCastException.

The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList. The exception tells you that it did not found the method it was looking for.

Create a new ArrayList with the contents of the old one.

new ArrayList<String>(myList);

Is there a command to list all Unix group names?

On Linux, macOS and Unix to display the groups to which you belong, use:

id -Gn

which is equivalent to groups utility which has been obsoleted on Unix (as per Unix manual).

On macOS and Unix, the command id -p is suggested for normal interactive.

Explanation of the parameters:

-G, --groups - print all group IDs

-n, --name - print a name instead of a number, for -ugG

-p - Make the output human-readable.

Android 'Unable to add window -- token null is not for an application' exception

You can continue to use getApplicationContext(), but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT), and the error will not show.

And don't forget to add permission:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

What is the difference between _tmain() and main() in C++?

the _T convention is used to indicate the program should use the character set defined for the application (Unicode, ASCII, MBCS, etc.). You can surround your strings with _T( ) to have them stored in the correct format.

 cout << _T( "There are " ) << argc << _T( " arguments:" ) << endl;

Read large files in Java

First, if your file contains binary data, then using BufferedReader would be a big mistake (because you would be converting the data to String, which is unnecessary and could easily corrupt the data); you should use a BufferedInputStream instead. If it's text data and you need to split it along linebreaks, then using BufferedReader is OK (assuming the file contains lines of a sensible length).

Regarding memory, there shouldn't be any problem if you use a decently sized buffer (I'd use at least 1MB to make sure the HD is doing mostly sequential reading and writing).

If speed turns out to be a problem, you could have a look at the java.nio packages - those are supposedly faster than java.io,

Convert character to Date in R

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1] "2009-10-09" "2009-10-15"

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.

How to read files and stdout from a running Docker container

To view the stdout, you can start the docker container with -i. This of course does not enable you to leave the started process and explore the container.

docker start -i containerid

Alternatively you can view the filesystem of the container at

/var/lib/docker/containers/containerid/root/

However neither of these are ideal. If you want to view logs or any persistent storage, the correct way to do so would be attaching a volume with the -v switch when you use docker run. This would mean you can inspect log files either on the host or attach them to another container and inspect them there.

Access host database from a docker container

If you want access to a Docker container where there is a DB, you have to add a bash:

docker exec -it postgresql bash

postgresql is the container name.

Once inside, from the bash, access to DB e.g:

$psql -U postgres

How to write :hover condition for a:before and a:after?

You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    span {
    font-size:12px;
    }
    a {
        color:green;
    }
    .test1>a:hover span {
        display:none;
    }
    .test1>a:hover:before {
        color:red;
        content:"Apple";
    }
  </style>
</head>

<body>
  <div class="test1">
    <a href="#"><span>Google</span></a>
  </div>
  <div class="test2">
    <a href="#"><span>Apple</span></a>
  </div>
</body>

</html>

Note: The hover:before switch works only on the .test1 class

show loading icon until the page is load?

Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.

<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
    jQuery("#" + id).html(jQuery("#loading").html());
    jQuery("#" + id).show();
}

Place a button right aligned

_x000D_
_x000D_
<div style = "display: flex; justify-content:flex-end">
    <button>Click me!</button>
</div>
_x000D_
_x000D_
_x000D_

<div style = "display: flex; justify-content: flex-end">
    <button>Click me!</button>
</div>

For-loop vs while loop in R

And about timing:

fn1 <- function (N) {
    for(i in as.numeric(1:N)) { y <- i*i }
}
fn2 <- function (N) {
    i=1
    while (i <= N) {
        y <- i*i
        i <- i + 1
    }
}

system.time(fn1(60000))
# user  system elapsed 
# 0.06    0.00    0.07 
system.time(fn2(60000))
# user  system elapsed 
# 0.12    0.00    0.13

And now we know that for-loop is faster than while-loop. You cannot ignore warnings during timing.

How to split a python string on new line characters

? Splitting line in Python:

Have you tried using str.splitlines() method?:

From the docs:

str.splitlines([keepends])

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

For example:

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()
['Line 1', '', 'Line 3', 'Line 4']

>>> 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines(True)
['Line 1\n', '\n', 'Line 3\r', 'Line 4\r\n']

Which delimiters are considered?

This method uses the universal newlines approach to splitting lines.

The main difference between Python 2.X and Python 3.X is that the former uses the universal newlines approach to splitting lines, so "\r", "\n", and "\r\n" are considered line boundaries for 8-bit strings, while the latter uses a superset of it that also includes:

  • \v or \x0b: Line Tabulation (added in Python 3.2).
  • \f or \x0c: Form Feed (added in Python 3.2).
  • \x1c: File Separator.
  • \x1d: Group Separator.
  • \x1e: Record Separator.
  • \x85: Next Line (C1 Control Code).
  • \u2028: Line Separator.
  • \u2029: Paragraph Separator.

splitlines VS split:

Unlike str.split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

>>> ''.splitlines()
[]

>>> 'Line 1\n'.splitlines()
['Line 1']

While str.split('\n') returns:

>>> ''.split('\n')
['']

>>> 'Line 1\n'.split('\n')
['Line 1', '']

?? Removing additional whitespace:

If you also need to remove additional leading or trailing whitespace, like spaces, that are ignored by str.splitlines(), you could use str.splitlines() together with str.strip():

>>> [str.strip() for str in 'Line 1  \n  \nLine 3 \rLine 4 \r\n'.splitlines()]
['Line 1', '', 'Line 3', 'Line 4']

? Removing empty strings (''):

Lastly, if you want to filter out the empty strings from the resulting list, you could use filter():

>>> # Python 2.X:
>>> filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines())
['Line 1', 'Line 3', 'Line 4']

>>> # Python 3.X:
>>> list(filter(bool, 'Line 1\n\nLine 3\rLine 4\r\n'.splitlines()))
['Line 1', 'Line 3', 'Line 4']

Additional comment regarding the original question:

As the error you posted indicates and Burhan suggested, the problem is from the print. There's a related question about that could be useful to you: UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

Sharing a variable between multiple different threads

AtomicBoolean

The succinct Answer by NPE sums up your three options. I'll add some example code for the second item listed there: AtomicBoolean.

You can think of the AtomicBoolean class as providing some thread-safety wrapping around a boolean value.

If you instantiate the AtomicBoolean only once, then you need not worry about the visibility issue in the Java Memory Model that requires volatile as a solution (the first item in that other Answer). Also, you need not concern yourself with synchronization (the third item in that other Answer) because AtomicBoolean performs that function of protecting multi-threaded access to its internal boolean value.

Let's look at some example code.

Firstly, in modern Java we generally do not address the Thread class directly. We now have the Executors framework to simplify handling of threads.

This code below is using Project Loom technology, coming to a future version of Java. Preliminary builds available now, built on early-access Java 16. This makes for simpler coding, with ExecutorService being AutoCloseable for convenient use with try-with-resources syntax. But Project Loom is not related to the point of this Answer; it just makes for simpler code that is easier to understand as “structured concurrency”.

The idea here is that we have three threads: the original thread, plus a ExecutorService that will create two more threads. The two new threads both report the value of our AtomicBoolean. The first new thread does so immediately, while the other waits 10 seconds before reporting. Meanwhile, our main thread sleeps for 5 seconds, wakes, changes the AtomicBoolean object’s contained value, and then waits for that second thread to wake and complete its work the report on the now-altered AtomicBoolean contained value. While we are installing seconds between each event, this is merely for dramatic demonstration. The real point is that these threads could coincidently try to access the AtomicBoolean simultaneously, but that object will protect access to its internal boolean value in a thread-safe manner. Protecting against simultaneous access is the job of the Atomic… classes.

try (
        ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
    AtomicBoolean flag = new AtomicBoolean( true );

    // This task, when run, will immediately report the flag.
    Runnable task1 = ( ) -> System.out.println( "First task reporting flag = " + flag.get() + ". " + Instant.now() );

    // This task, when run, will wait several seconds, then report the flag. Meanwhile, code below waits a shorter time before *changing* the flag.
    Runnable task2 = ( ) -> {
        try { Thread.sleep( Duration.ofSeconds( 10 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
        System.out.println( "Second task reporting flag = " + flag.get() + ". " + Instant.now() );
    };

    executorService.submit( task1 );
    executorService.submit( task2 );

    // Wait for first task to complete, so sleep here briefly. But wake before the sleeping second task awakens.
    try { Thread.sleep( Duration.ofSeconds( 5 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
    System.out.println( "INFO - Original thread waking up, and setting flag to false. " + Instant.now() );
    flag.set( false );
}
// At this point, with Project Loom technology, the flow-of-control blocks until the submitted tasks are done.
// Also, the `ExecutorService` is automatically closed/shutdown by this point, via try-with-resources syntax.
System.out.println( "INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone." + Instant.now() );

Methods such as AtomicBoolean#get and AtomicBoolean#set are built to be thread-safe, to internally protect access to the boolean value nested within. Read up on the various other methods as well.

When run:

First task reporting flag = true. 2021-01-05T06:42:17.367337Z
INFO - Original thread waking up, and setting flag to false. 2021-01-05T06:42:22.367456Z
Second task reporting flag = false. 2021-01-05T06:42:27.369782Z
INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone.2021-01-05T06:42:27.372597Z

Pro Tip: When engaging in threaded code in Java, always study the excellent book, Java Concurrency in Practice by Brian Goetz et al.

Return from lambda forEach() in java

I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.

You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.

What I identified in your first case is the following:

  • You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:

List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

  1. Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.
  2. Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.
  3. Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

  1. Code against interfaces, so code against List<E> over ArrayList<E>.
  2. Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:

You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

Combining a class selector and an attribute selector with jQuery

I think you just need to remove the space. i.e.

$(".myclass[reference=12345]").css('border', '#000 solid 1px');

There is a fiddle here http://jsfiddle.net/xXEHY/

Change URL without refresh the page

Update

Based on Manipulating the browser history, passing the empty string as second parameter of pushState method (aka title) should be safe against future changes to the method, so it's better to use pushState like this:

history.pushState(null, '', '/en/step2');    

You can read more about that in mentioned article

Original Answer

Use history.pushState like this:

history.pushState(null, null, '/en/step2');

Update 2 to answer Idan Dagan's comment:

Why not using history.replaceState()?

From MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one

That means if you use replaceState, yes the url will be changed but user can not use Browser's Back button to back to prev. state(s) anymore (because replaceState doesn't add new entry to history) and it's not recommended and provide bad UX.

Update 3 to add window.onpopstate

So, as this answer got your attention, here is additional info about manipulating the browser history, after using pushState, you can detect the back/forward button navigation by using window.onpopstate like this:

window.onpopstate = function(e) {
    // ... 
};

As the first argument of pushState is an object, if you passed an object instead of null, you can access that object in onpopstate which is very handy, here is how:

window.onpopstate = function(e) {
    if(e.state) {
        console.log(e.state);
    }
};

Update 4 to add Reading the current state:

When your page loads, it might have a non-null state object, you can read the state of the current history entry without waiting for a popstate event using the history.state property like this:

console.log(history.state);

Bonus: Use following to check history.pushState support:

if (history.pushState) {
  // \o/
}

node.js hash string?

Here you can benchmark all supported hashes on your hardware, supported by your version of node.js. Some are cryptographic, and some is just for a checksum. Its calculating "Hello World" 1 million times for each algorithm. It may take around 1-15 seconds for each algorithm (Tested on the Standard Google Computing Engine with Node.js 4.2.2).

for(var i1=0;i1<crypto.getHashes().length;i1++){
  var Algh=crypto.getHashes()[i1];
  console.time(Algh);
  for(var i2=0;i2<1000000;i2++){
    crypto.createHash(Algh).update("Hello World").digest("hex");
  }
  console.timeEnd(Algh);  
}

Result:
DSA: 1992ms
DSA-SHA: 1960ms
DSA-SHA1: 2062ms
DSA-SHA1-old: 2124ms
RSA-MD4: 1893ms
RSA-MD5: 1982ms
RSA-MDC2: 2797ms
RSA-RIPEMD160: 2101ms
RSA-SHA: 1948ms
RSA-SHA1: 1908ms
RSA-SHA1-2: 2042ms
RSA-SHA224: 2176ms
RSA-SHA256: 2158ms
RSA-SHA384: 2290ms
RSA-SHA512: 2357ms
dsaEncryption: 1936ms
dsaWithSHA: 1910ms
dsaWithSHA1: 1926ms
dss1: 1928ms
ecdsa-with-SHA1: 1880ms
md4: 1833ms
md4WithRSAEncryption: 1925ms
md5: 1863ms
md5WithRSAEncryption: 1923ms
mdc2: 2729ms
mdc2WithRSA: 2890ms
ripemd: 2101ms
ripemd160: 2153ms
ripemd160WithRSA: 2210ms
rmd160: 2146ms
sha: 1929ms
sha1: 1880ms
sha1WithRSAEncryption: 1957ms
sha224: 2121ms
sha224WithRSAEncryption: 2290ms
sha256: 2134ms
sha256WithRSAEncryption: 2190ms
sha384: 2181ms
sha384WithRSAEncryption: 2343ms
sha512: 2371ms
sha512WithRSAEncryption: 2434ms
shaWithRSAEncryption: 1966ms
ssl2-md5: 1853ms
ssl3-md5: 1868ms
ssl3-sha1: 1971ms
whirlpool: 2578ms

How to use regex in String.contains() method in Java

You can simply use matches method of String class.

boolean result = someString.matches("stores.*store.*product.*");

How to debug Google Apps Script (aka where does Logger.log log to?)

Just as a notice. I made a test function for my spreadsheet. I use the variable google throws in the onEdit(e) function (I called it e). Then I made a test function like this:

function test(){
var testRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,7)
var testObject = {
    range:testRange,
    value:"someValue"
}
onEdit(testObject)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,6).setValue(Logger.getLog())
}

Calling this test function makes all the code run as you had an event in the spreadsheet. I just put in the possision of the cell i edited whitch gave me an unexpected result, setting value as the value i put into the cell. OBS! for more variables googles gives to the function go here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

Getting strings recognized as variable names in R

Without any example data, it really is difficult to know exactly what you are wanting. For instance, I can't at all divine what your object set (or is it sets) looks like.

That said, does the following help at all?

set1 <- data.frame(x = 4:6, y = 6:4, z = c(1, 3, 5))

plot(1:10, type="n")
XX <- "set1"
with(eval(as.symbol(XX)), symbols(x, y, circles = z, add=TRUE))

EDIT:

Now that I see your real task, here is a one-liner that'll do everything you want without requiring any for() loops:

with(dat, symbols(sq, cu, circles = num,
                  bg = c("red", "blue")[(num>5) + 1]))

The one bit of code that may feel odd is the bit specifying the background color. Try out these two lines to see how it works:

c(TRUE, FALSE) + 1
# [1] 2 1
c("red", "blue")[c(F, F, T, T) + 1]
# [1] "red"  "red"  "blue" "blue"

Use YAML with variables

Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...

# fooz.yml
  foo:
    bar: <%= $ENV[:some_var] %>

No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.

If you can use the template like that or the << >> or the {{ }} styles depending on your reader, after that you just ...

In another yml file ...

# boo.yml

development:
  fooz: foo

Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.

VBA procedure to import csv file into access

Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work

Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant

    sFileIn = "z:\docs\FileName.csv"
    sFileOut = "z:\docs\FileOut.csv"

    Set fs = CreateObject("Scripting.FileSystemObject")
    Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading

    sTmp = tsIn.ReadAll

    Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
    aryFile = Split(sTmp, vbCrLf)

    ''Start at line 3 and end at last line -1
    For i = 3 To UBound(aryFile) - 1
        tsOut.WriteLine aryFile(i)
    Next

    tsOut.Close

    DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub

Edit re various comments

It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.

About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003

Introduction to importing and exporting data -- Applies to: Microsoft Access 2010

Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.

"Could not find a version that satisfies the requirement opencv-python"

I faced same issue while using Python 3.9.0. Upgrading python to latest version (currently 3.9.1) and reinstalling opencv-python solved this issue.

How to give a Blob uploaded as FormData a file name?

When you are using Google Chrome you can use/abuse the Google Filesystem API for this. Here you can create a file with a specified name and write the content of a blob to it. Then you can return the result to the user.

I have not found a good way for Firefox yet; probably a small piece of Flash like downloadify is required to name a blob.

IE10 has a msSaveBlob() function in the BlobBuilder.

Maybe this is more for downloading a blob, but it is related.

React PropTypes : Allow different types of PropTypes for one prop

import React from 'react';              <--as normal
import PropTypes from 'prop-types';     <--add this as a second line

    App.propTypes = {
        monkey: PropTypes.string,           <--omit "React."
        cat: PropTypes.number.isRequired    <--omit "React."
    };

    Wrong:  React.PropTypes.string
    Right:  PropTypes.string

DateTime.TryParseExact() rejecting valid formats

string DemoLimit = "02/28/2018";
 string pattern = "MM/dd/yyyy";
 CultureInfo enUS = new CultureInfo("en-US"); 
 DateTime.TryParseExact(DemoLimit, pattern, enUS, 
                     DateTimeStyles.AdjustToUniversal, out datelimit);

For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx

How to simplify a null-safe compareTo() implementation?

See the bottom of this answer for updated (2013) solution using Guava.


This is what I ultimately went with. It turned out we already had a utility method for null-safe String comparison, so the simplest solution was to make use of that. (It's a big codebase; easy to miss this kind of thing :)

public int compareTo(Metadata other) {
    int result = StringUtils.compare(this.getName(), other.getName(), true);
    if (result != 0) {
        return result;
    }
    return StringUtils.compare(this.getValue(), other.getValue(), true);
}

This is how the helper is defined (it's overloaded so that you can also define whether nulls come first or last, if you want):

public static int compare(String s1, String s2, boolean ignoreCase) { ... }

So this is essentially the same as Eddie's answer (although I wouldn't call a static helper method a comparator) and that of uzhin too.

Anyway, in general, I would have strongly favoured Patrick's solution, as I think it's a good practice to use established libraries whenever possible. (Know and use the libraries as Josh Bloch says.) But in this case that would not have yielded the cleanest, simplest code.

Edit (2009): Apache Commons Collections version

Actually, here's a way to make the solution based on Apache Commons NullComparator simpler. Combine it with the case-insensitive Comparator provided in String class:

public static final Comparator<String> NULL_SAFE_COMPARATOR 
    = new NullComparator(String.CASE_INSENSITIVE_ORDER);

@Override
public int compareTo(Metadata other) {
    int result = NULL_SAFE_COMPARATOR.compare(this.name, other.name);
    if (result != 0) {
        return result;
    }
    return NULL_SAFE_COMPARATOR.compare(this.value, other.value);
}

Now this is pretty elegant, I think. (Just one small issue remains: the Commons NullComparator doesn't support generics, so there's an unchecked assignment.)

Update (2013): Guava version

Nearly 5 years later, here's how I'd tackle my original question. If coding in Java, I would (of course) be using Guava. (And quite certainly not Apache Commons.)

Put this constant somewhere, e.g. in "StringUtils" class:

public static final Ordering<String> CASE_INSENSITIVE_NULL_SAFE_ORDER =
    Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast(); // or nullsFirst()

Then, in public class Metadata implements Comparable<Metadata>:

@Override
public int compareTo(Metadata other) {
    int result = CASE_INSENSITIVE_NULL_SAFE_ORDER.compare(this.name, other.name);
    if (result != 0) {
        return result;
    }
    return CASE_INSENSITIVE_NULL_SAFE_ORDER.compare(this.value, other.value);
}    

Of course, this is nearly identical to the Apache Commons version (both use JDK's CASE_INSENSITIVE_ORDER), the use of nullsLast() being the only Guava-specific thing. This version is preferable simply because Guava is preferable, as a dependency, to Commons Collections. (As everyone agrees.)

If you were wondering about Ordering, note that it implements Comparator. It's pretty handy especially for more complex sorting needs, allowing you for example to chain several Orderings using compound(). Read Ordering Explained for more!

regular expression for Indian mobile numbers

i have used this regex in my projects and this works fine.

pattern="[6-9]{1}[0-9]{9}"

Resize Google Maps marker icon image

If you are using vue2-google-maps like me, the code to set the size looks like this:

<gmap-marker
  ..
  :icon="{
    ..
    anchor: { x: iconSize, y: iconSize },
    scaledSize: { height: iconSize, width: iconSize },
  }"
>

How to cast the size_t to double or int C++

Static cast:

static_cast<int>(data);

Uncaught TypeError: Cannot set property 'onclick' of null

"blue_box" is null -- are you positive whatever it is with "id='blue'" exists when this is being run?

try console.log(document.getElementById("blue")) in chrome or FF with firebug. Your script might be running before the 'blue' element is loaded. In this case, you'll need to add the event after the page has loaded (window.onload).

Change default icon

Go to the Project properties Build the project Locate the .exe file in your favorite file explorer.

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I faced exactly the same issue in a Spring web app. In fact, I had removed spring-security by commenting the config annotation:

// @ImportResource({"/WEB-INF/spring-security.xml"})

but I had forgotten to remove the corresponding filters in web.xml:

<!-- Filters --> 
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Commenting filters solved the issue.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

It is working after adding to pom.xml following dependencies:

<dependency>
   <groupId>javax.el</groupId>
   <artifactId>javax.el-api</artifactId>
   <version>2.2.4</version>
</dependency>
<dependency>
   <groupId>org.glassfish.web</groupId>
   <artifactId>javax.el</artifactId>
   <version>2.2.4</version>
</dependency>

Getting started with Hibernate Validator:

Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages. When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container. In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance you can add the following two dependencies to use the JSR 341 reference implementation:

<dependency>
   <groupId>javax.el</groupId>
   <artifactId>javax.el-api</artifactId>
   <version>2.2.4</version>
</dependency>
<dependency>
   <groupId>org.glassfish.web</groupId>
   <artifactId>javax.el</artifactId>
   <version>2.2.4</version>
</dependency>

Check free disk space for current partition in bash

Yes:

df -k .

for the current directory.

df -k /some/dir

if you want to check a specific directory.

You might also want to check out the stat(1) command if your system has it. You can specify output formats to make it easier for your script to parse. Here's a little example:

$ echo $(($(stat -f --format="%a*%S" .)))

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

What worked for me - should really be moved to iPhone:

Charles

  1. Enable transparent Http proxying
  2. Enable SSL proxying
  3. Right click on incoming request and select SSL proxying

Mac

  1. Download Charles CA Certificate bundle http://www.charlesproxy.com/ssl.zip
  2. Email yourself charles-proxy-ssl-proxying-certificate.crt

iPhone

  1. Enable http proxy for Charles on port 8888
  2. Select and install email attachment, yes trust it!

Voila, you can now view encrypted traffic from the domain added in the SSL proxying

How to search multiple columns in MySQL?

You can use the AND or OR operators, depending on what you want the search to return.

SELECT title FROM pages WHERE my_col LIKE %$param1% AND another_col LIKE %$param2%;

Both clauses have to match for a record to be returned. Alternatively:

SELECT title FROM pages WHERE my_col LIKE %$param1% OR another_col LIKE %$param2%;

If either clause matches then the record will be returned.

For more about what you can do with MySQL SELECT queries, try the documentation.

How to install maven on redhat linux

Installing maven in Amazon Linux / redhat

--> sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

--> sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo

-->sudo yum install -y apache-maven

--> mvn --version

Output looks like


Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.amzn2.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-64.38.amzn2.x86_64", arch: "amd64", family: "unix"

*If its thrown error related to java please follow the below step to update java 8 *

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

Regular expression to extract numbers from a string

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

Check if a key is down?

My solution:

var pressedKeys = {};
window.onkeyup = function(e) { pressedKeys[e.keyCode] = false; }
window.onkeydown = function(e) { pressedKeys[e.keyCode] = true; }

I can now check if any key is pressed anywhere else in the script by checking

pressedKeys["code of the key"]

If it's true, the key is pressed.

Unsafe JavaScript attempt to access frame with URL

I found that using the XFBML version of the Facebook like button instead of the HTML5 version fixed this problem. Add the below code where you want the button to appear:

<div id="fb-root"></div>
<script>(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<fb:like send="true" layout="button_count" width="50" show_faces="false" font="arial"></fb:like>

Then add this to your HTML tag:

 xmlns:fb="http://ogp.me/ns/fb#"

Clone contents of a GitHub repository (without the folder itself)

You can specify the destination directory as second parameter of the git clone command, so you can do:

git clone <remote> .

This will clone the repository directly in the current local directory.

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

trap is your friend. You can trap on ERR in a lot of systems. You can trap EXIT, or on DEBUG to perform a piece of code after every command.

This in addition to all the standard signals.

Best way to test for a variable's existence in PHP; isset() is clearly broken

I have to say in all my years of PHP programming, I have never encountered a problem with isset() returning false on a null variable. OTOH, I have encountered problems with isset() failing on a null array entry - but array_key_exists() works correctly in that case.

For some comparison, Icon explicitly defines an unused variable as returning &null so you use the is-null test in Icon to also check for an unset variable. This does make things easier. On the other hand, Visual BASIC has multiple states for a variable that doesn't have a value (Null, Empty, Nothing, ...), and you often have to check for more than one of them. This is known to be a source of bugs.

What is the syntax meaning of RAISERROR()

It is the severity level of the error. The levels are from 11 - 20 which throw an error in SQL. The higher the level, the more severe the level and the transaction should be aborted.

You will get the syntax error when you do:

RAISERROR('Cannot Insert where salary > 1000').

Because you have not specified the correct parameters (severity level or state).

If you wish to issue a warning and not an exception, use levels 0 - 10.

From MSDN:

severity

Is the user-defined severity level associated with this message. When using msg_id to raise a user-defined message created using sp_addmessage, the severity specified on RAISERROR overrides the severity specified in sp_addmessage. Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions. For severity levels from 19 through 25, the WITH LOG option is required.

state

Is an integer from 0 through 255. Negative values or values larger than 255 generate an error. If the same user-defined error is raised at multiple locations, using a unique state number for each location can help find which section of code is raising the errors. For detailed description here

int value under 10 convert to string two digit number

The accepted answer is good and fast:

i.ToString("00")

or

i.ToString("000")

If you need more complexity, String.Format is worth a try:

var str1 = "";
var str2 = "";
for (int i = 1; i < 100; i++)
{
    str1 = String.Format("{0:00}", i);
    str2 = String.Format("{0:000}", i);
}

For the i = 10 case:

str1: "10"
str2: "010"

I use this, for example, to clear the text on particular Label Controls on my form by name:

private void EmptyLabelArray()
{
    var fmt = "Label_Row{0:00}_Col{0:00}";
    for (var rowIndex = 0; rowIndex < 100; rowIndex++)
    {
        for (var colIndex = 0; colIndex < 100; colIndex++)
        {
            var lblName = String.Format(fmt, rowIndex, colIndex);
            foreach (var ctrl in this.Controls)
            {
                var lbl = ctrl as Label;
                if ((lbl != null) && (lbl.Name == lblName))
                {
                    lbl.Text = null;
                }
            }
        }
    }
}

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Int division: Why is the result of 1/3 == 0?

Because it treats 1 and 3 as integers, therefore rounding the result down to 0, so that it is an integer.

To get the result you are looking for, explicitly tell java that the numbers are doubles like so:

double g = 1.0/3.0;

TypeError: 'undefined' is not a function (evaluating '$(document)')

 ;(function($){
        // your code
    })(jQuery);

Place your js code inside the closure above , it should solve the problem.

How do you use "git --bare init" repository?

It is nice to verify that the code you pushed actually got committed.

You can get a log of changes on a bare repository by explicitly setting the path using the --relative option.

$ cd test_repo
$ git log --relative=/

This will show you the committed changes as if this was a regular git repo.

HTML.ActionLink method

With MVC5 i have done it like this and it is 100% working code....

@Html.ActionLink(department.Name, "Index", "Employee", new { 
                            departmentId = department.DepartmentID }, null)

You guys can get an idea from this...

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

How can I format the output of a bash command in neat columns

column(1) is your friend.

$ column -t <<< '"option-y"      yank-pop
> "option-z"      execute-last-named-cmd
> "option-|"      vi-goto-column
> "option-~"      _bash_complete-word
> "option-control-?"      backward-kill-word
> "control-_"     undo
> "control-?"     backward-delete-char
> '
"option-y"          yank-pop
"option-z"          execute-last-named-cmd
"option-|"          vi-goto-column
"option-~"          _bash_complete-word
"option-control-?"  backward-kill-word
"control-_"         undo
"control-?"         backward-delete-char

Select folder dialog WPF

Windows Presentation Foundation 4.5 Cookbook by Pavel Yosifovich on page 155 in the section on "Using the common dialog boxes" says:

"What about folder selection (instead of files)? The WPF OpenFileDialog does not support that. One solution is to use Windows Forms' FolderBrowseDialog class. Another good solution is to use the Windows API Code Pack described shortly."

I downloaded the API Code Pack from Windows® API Code Pack for Microsoft® .NET Framework Windows API Code Pack: Where is it?, then added references to Microsoft.WindowsAPICodePack.dll and Microsoft.WindowsAPICodePack.Shell.dll to my WPF 4.5 project.

Example:

using Microsoft.WindowsAPICodePack.Dialogs;

var dlg = new CommonOpenFileDialog();
dlg.Title = "My Title";
dlg.IsFolderPicker = true;
dlg.InitialDirectory = currentDirectory;

dlg.AddToMostRecentlyUsedList = false;
dlg.AllowNonFileSystemItems = false;
dlg.DefaultDirectory = currentDirectory;
dlg.EnsureFileExists = true;
dlg.EnsurePathExists = true;
dlg.EnsureReadOnly = false;
dlg.EnsureValidNames = true;
dlg.Multiselect = false;
dlg.ShowPlacesList = true;

if (dlg.ShowDialog() == CommonFileDialogResult.Ok) 
{
  var folder = dlg.FileName;
  // Do something with selected folder string
}

Get Selected value from Multi-Value Select Boxes by jquery-select2?

Try like this,

jQuery('.leaderMultiSelctdropdown').select2('data');

In a Git repository, how to properly rename a directory?

lots of correct answers, but as I landed here to copy & paste a folder rename with history, I found that this

git mv <old name> <new name>

will move the old folder (itself) to nest within the new folder

while

git mv <old name>/ <new name>

(note the '/') will move the nested content from the old folder to the new folder

both commands didn't copy along the history of nested files. I eventually renamed each nested folder individually ?

git mv <old name>/<nest-folder> <new name>/<nest-folder>

Unicode character as bullet for list-item in CSS

You can construct it:

#modal-select-your-position li {
/* handle multiline */
    overflow: visible;
    padding-left: 17px;
    position: relative;
}

#modal-select-your-position li:before {
/* your own marker in content */
   content: "—";
   left: 0;
   position: absolute;
}

@Autowired - No qualifying bean of type found for dependency

The thing is that both the application context and the web application context are registered in the WebApplicationContext during server startup. When you run the test you must explicitly tell which contexts to load.

Try this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})

scrollTop jquery, scrolling to div with id?

instead of

$('html, body').animate({scrollTop:xxx}, 'slow');

use

$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

this will return the absolute top position of whatever element you select as #div_id

Android: how to hide ActionBar on certain activities

The ActionBar usually exists along Fragments so from the Activity you can hide it

getActionBar().hide();
getActionBar().show();

and from the Fragment you can do it

getActivity().getActionBar().hide();
getActivity().getActionBar().show();

When to use margin vs padding in CSS

I always use this principle:

box model image

This is the box model from the inspect element feature in Firefox. It works like an onion:

  • Your content is in the middle.
  • Padding is space between your content and edge of the tag it is inside.
  • The border and its specifications
  • The margin is the space around the tag.

So bigger margins will make more space around the box that contains your content.

Larger padding will increase the space between your content and the box of which it is inside.

Neither of them will increase or decrease the size of the box if it is set to a specific value.

Android - How to achieve setOnClickListener in Kotlin?

Simply do as below :

button.setOnClickListener{doSomething()}

php resize image on upload

You can use this library to manipulate the image while uploading. http://www.verot.net/php_class_upload.htm

Fixed size div?

As reply to Jonathan Sampson, this is the best way to do it, without a clearing div:

.container { width:450px; overflow:hidden }
.cube { width:150px; height:150px; float:left }

<div class="container">
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
    <div class="cube"></div>
</div>

Finding all the subsets of a set

In case anyone else comes by and was still wondering, here's a function using Michael's explanation in C++

vector< vector<int> > getAllSubsets(vector<int> set)
{
    vector< vector<int> > subset;
    vector<int> empty;
    subset.push_back( empty );

    for (int i = 0; i < set.size(); i++)
    {
        vector< vector<int> > subsetTemp = subset;  //making a copy of given 2-d vector.

        for (int j = 0; j < subsetTemp.size(); j++)
            subsetTemp[j].push_back( set[i] );   // adding set[i] element to each subset of subsetTemp. like adding {2}(in 2nd iteration  to {{},{1}} which gives {{2},{1,2}}.

        for (int j = 0; j < subsetTemp.size(); j++)
            subset.push_back( subsetTemp[j] );  //now adding modified subsetTemp to original subset (before{{},{1}} , after{{},{1},{2},{1,2}}) 
    }
    return subset;
}

Take into account though, that this will return a set of size 2^N with ALL possible subsets, meaning there will possibly be duplicates. If you don't want this, I would suggest actually using a set instead of a vector(which I used to avoid iterators in the code).

Laravel assets url

You have to put all your assets in app/public folder, and to access them from your views you can use asset() helper method.

Ex. you can retrieve assets/images/image.png in your view as following:

<img src="{{asset('assets/images/image.png')}}">

What is :: (double colon) in Python when subscripting sequences?

Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3] is every third element of the sequence.

How to discard all changes made to a branch?

git checkout -f

This is suffice for your question. Only thing is, once its done, its done. There is no undo.

How does the 'binding' attribute work in JSF? When and how should it be used?

each JSF component renders itself out to HTML and has complete control over what HTML it produces. There are many tricks that can be used by JSF, and exactly which of those tricks will be used depends on the JSF implementation you are using.

  • Ensure that every from input has a totaly unique name, so that when the form gets submitted back to to component tree that rendered it, it is easy to tell where each component can read its value form.
  • The JSF component can generate javascript that submitts back to the serer, the generated javascript knows where each component is bound too, because it was generated by the component.
  • For things like hlink you can include binding information in the url as query params or as part of the url itself or as matrx parameters. for examples.

    http:..../somelink?componentId=123 would allow jsf to look in the component tree to see that link 123 was clicked. or it could e htp:..../jsf;LinkId=123

The easiest way to answer this question is to create a JSF page with only one link, then examine the html output it produces. That way you will know exactly how this happens using the version of JSF that you are using.

How to stretch div height to fill parent div - CSS

Simply add height: 100%; onto the #B2 styling. min-height shouldn't be necessary.

Regular expression to match non-ASCII characters?

This should do it:

[^\x00-\x7F]+

It matches any character which is not contained in the ASCII character set (0-127, i.e. 0x0 to 0x7F).

You can do the same thing with Unicode:

[^\u0000-\u007F]+

For unicode you can look at this 2 resources:

how to get the attribute value of an xml node using java

try something like this :

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

please note the changes :

  • we ask for a nodeset (XPathConstants.NODESET) and not only for a single node.
  • the xpath is now //xml/ep/source/@type and not //xml/source/@type/text()

PS: can you add the tag java to your question ? thanks.

Convert list to tuple in Python

You might have done something like this:

>>> tuple = 45, 34  # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l)   # Will try to invoke the variable `tuple` rather than tuple type.

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple  # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)

Here's the problem... Since you have used a tuple variable to hold a tuple (45, 34) earlier... So, now tuple is an object of type tuple now...

It is no more a type and hence, it is no more Callable.

Never use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...

How to limit the maximum files chosen when using multiple file input

On change of the input track how many files are selected:

_x000D_
_x000D_
$("#image").on("change", function() {_x000D_
    if ($("#image")[0].files.length > 2) {_x000D_
        alert("You can select only 2 images");_x000D_
    } else {_x000D_
        $("#imageUploadForm").submit();_x000D_
    }_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<strong>On change of the input track how many files are selected:</strong>_x000D_
<input name="image[]" id="image" type="file"  multiple="multiple" accept="image/jpg, image/jpeg" >
_x000D_
_x000D_
_x000D_

Show data on mouseover of circle

I assume that what you want is a tooltip. The easiest way to do this is to append an svg:title element to each circle, as the browser will take care of showing the tooltip and you don't need the mousehandler. The code would be something like

vis.selectAll("circle")
   .data(datafiltered).enter().append("svg:circle")
   ...
   .append("svg:title")
   .text(function(d) { return d.x; });

If you want fancier tooltips, you could use tipsy for example. See here for an example.

Computational complexity of Fibonacci Sequence

The proof answers are good, but I always have to do a few iterations by hand to really convince myself. So I drew out a small calling tree on my whiteboard, and started counting the nodes. I split my counts out into total nodes, leaf nodes, and interior nodes. Here's what I got:

IN | OUT | TOT | LEAF | INT
 1 |   1 |   1 |   1  |   0
 2 |   1 |   1 |   1  |   0
 3 |   2 |   3 |   2  |   1
 4 |   3 |   5 |   3  |   2
 5 |   5 |   9 |   5  |   4
 6 |   8 |  15 |   8  |   7
 7 |  13 |  25 |  13  |  12
 8 |  21 |  41 |  21  |  20
 9 |  34 |  67 |  34  |  33
10 |  55 | 109 |  55  |  54

What immediately leaps out is that the number of leaf nodes is fib(n). What took a few more iterations to notice is that the number of interior nodes is fib(n) - 1. Therefore the total number of nodes is 2 * fib(n) - 1.

Since you drop the coefficients when classifying computational complexity, the final answer is ?(fib(n)).

How to tar certain file types in all subdirectories?

find ./someDir -name "*.php" -o -name "*.html" | tar -cf my_archive -T -

Trigger an event on `click` and `enter`

Use keypress event on usersSearch textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.

$('document').ready(function(){
    $('#searchButton').click(function(){
        var search = $('#usersSearch').val();
        $.post('../searchusers.php',{search: search},function(response){
            $('#userSearchResultsTable').html(response);
        });
    })
    $('#usersSearch').keypress(function(e){
        if(e.which == 13){//Enter key pressed
            $('#searchButton').click();//Trigger search button click event
        }
    });

});

Demo

Entity Framework Core add unique constraint code-first

None of these methods worked for me in .NET Core 2.2 but I was able to adapt some code I had for defining a different primary key to work for this purpose.

In the instance below I want to ensure the OutletRef field is unique:

public class ApplicationDbContext : IdentityDbContext
    {
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Outlet>()
                .HasIndex(o => new { o.OutletRef });
        }
    }

This adds the required unique index in the database. What it doesn't do though is provide the ability to specify a custom error message.

How to define a variable in a Dockerfile?

To answer your question:

In my Dockerfile, I would like to define variables that I can use later in the Dockerfile.

You can define a variable with:

ARG myvalue=3

Spaces around the equal character are not allowed.

And use it later with:

RUN echo $myvalue > /test

How to post JSON to a server using C#?

Ademar's solution can be improved by leveraging JavaScriptSerializer's Serialize method to provide implicit conversion of the object to JSON.

Additionally, it is possible to leverage the using statement's default functionality in order to omit explicitly calling Flush and Close.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    user = "Foo",
                    password = "Baz"
                });

    streamWriter.Write(json);
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Readably print out a python dict() sorted by key

Actually pprint seems to sort the keys for you under python2.5

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}

But not always under python 2.4

>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> d = dict(zip("kjihgfedcba",range(11)))
>>> pprint(d)
{'a': 10,
 'b': 9,
 'c': 8,
 'd': 7,
 'e': 6,
 'f': 5,
 'g': 4,
 'h': 3,
 'i': 2,
 'j': 1,
 'k': 0}
>>> 

Reading the source code of pprint.py (2.5) it does sort the dictionary using

items = object.items()
items.sort()

for multiline or this for single line

for k, v in sorted(object.items()):

before it attempts to print anything, so if your dictionary sorts properly like that then it should pprint properly. In 2.4 the second sorted() is missing (didn't exist then) so objects printed on a single line won't be sorted.

So the answer appears to be use python2.5, though this doesn't quite explain your output in the question.

Python3 Update

Pretty print by sorted keys (lambda x: x[0]):

for key, value in sorted(dict_example.items(), key=lambda x: x[0]): 
    print("{} : {}".format(key, value))

Pretty print by sorted values (lambda x: x[1]):

for key, value in sorted(dict_example.items(), key=lambda x: x[1]): 
    print("{} : {}".format(key, value))

What's alternative to angular.copy in Angular

If you are not already using lodash I wouldn't recommend installing it just for this one method. I suggest instead a more narrowly specialized library such as 'clone':

npm install clone

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

IIS7 defines a defaultDocument section in its configuration files which can be found in the %WinDir%\System32\InetSrv\Config folder. Most likely, the file index.aspx is already defined as a default document in one of IIS7's configuration files and you are adding it again in your web.config.

I suspect that removing the line <add value="index.aspx" />

from the defaultDocument/files section will fix your issue.

The defaultDocument section of your config will look like:

<defaultDocument>
  <files>
    <remove value="default.aspx" />
    <remove value="index.html" />
    <remove value="iisstart.htm" />
    <remove value="index.htm" />
    <remove value="Default.asp" />
    <remove value="Default.htm" />
  </files>
</defaultDocument>

Note that index.aspx will still appear in the list of default documents for your site in the IIS manager.

For more information about IIS7 configuration, click here.

How to calculate age in T-SQL with years, months, and days

DECLARE @DoB AS DATE = '1968-10-24'
DECLARE @cDate AS DATE = CAST('2000-10-23' AS DATE)

SELECT 
--Get Year difference
DATEDIFF(YEAR,@DoB,@cDate) -
--Cases where year difference will be augmented
CASE 
    --If Date of Birth greater than date passed return 0
    WHEN YEAR(@DoB) - YEAR(@cDate) >= 0 THEN DATEDIFF(YEAR,@DoB,@cDate)

    --If date of birth month less than date passed subtract one year
    WHEN MONTH(@DoB) - MONTH(@cDate) > 0 THEN 1 

    --If date of birth day less than date passed subtract one year
    WHEN MONTH(@DoB) - MONTH(@cDate) = 0 AND DAY(@DoB) - DAY(@cDate) > 0 THEN 1 

    --All cases passed subtract zero
    ELSE 0
END

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

Laravel Eloquent compare date from datetime field

If you're still wondering how to solve it.

I use

$protected $dates = ['created_at','updated_at','aired'];

In my model and in my where i do

where('aired','>=',time())

So just use the unix to compaire in where.

In views on the otherhand you have to use the date object.

Hope it helps someone!

Check whether an array is empty

I can't replicate that (php 5.3.6):

php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)

php > $error = array();
php > var_dump(empty($error));
bool(true)
php >

exactly where are you doing the empty() call that returns true?

The following untracked working tree files would be overwritten by merge, but I don't care

In addition to the accepted answer you can of course remove the files if they are no longer needed by specifying the file:

git clean -f '/path/to/file/'

Remember to run it with the -n flag first if you would like to see which files git clean will remove. Note that these files will be deleted. In my case I didn't care about them anyway, so that was a better solution for me.

Simultaneously merge multiple data.frames in a list

I had a list of dataframes with no common id column.
I had missing data on many dfs. There were Null values. The dataframes were produced using table function. The Reduce, Merging, rbind, rbind.fill, and their like could not help me to my aim. My aim was to produce an understandable merged dataframe, irrelevant of the missing data and common id column.

Therefore, I made the following function. Maybe this function can help someone.

##########################################################
####             Dependencies                        #####
##########################################################

# Depends on Base R only

##########################################################
####             Example DF                          #####
##########################################################

# Example df
ex_df           <- cbind(c( seq(1, 10, 1), rep("NA", 0), seq(1,10, 1) ), 
                         c( seq(1, 7, 1),  rep("NA", 3), seq(1, 12, 1) ), 
                         c( seq(1, 3, 1),  rep("NA", 7), seq(1, 5, 1), rep("NA", 5) ))

# Making colnames and rownames
colnames(ex_df) <- 1:dim(ex_df)[2]
rownames(ex_df) <- 1:dim(ex_df)[1]

# Making an unequal list of dfs, 
# without a common id column
list_of_df      <- apply(ex_df=="NA", 2, ( table) )

it is following the function

##########################################################
####             The function                        #####
##########################################################


# The function to rbind it
rbind_null_df_lists <- function ( list_of_dfs ) {
  length_df     <- do.call(rbind, (lapply( list_of_dfs, function(x) length(x))))
  max_no        <- max(length_df[,1])
  max_df        <- length_df[max(length_df),]
  name_df       <- names(length_df[length_df== max_no,][1])
  names_list    <- names(list_of_dfs[ name_df][[1]])

  df_dfs <- list()
  for (i in 1:max_no ) {

    df_dfs[[i]]            <- do.call(rbind, lapply(1:length(list_of_dfs), function(x) list_of_dfs[[x]][i]))

  }

  df_cbind               <- do.call( cbind, df_dfs )
  rownames( df_cbind )   <- rownames (length_df)
  colnames( df_cbind )   <- names_list

  df_cbind

}

Running the example

##########################################################
####             Running the example                 #####
##########################################################

rbind_null_df_lists ( list_of_df )

How to create a Restful web service with input parameters?

You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello in your browser...

package newpackage;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;

@Path("generic")
public class GenericResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GenericResource
     */
    public GenericResource() {
    }

    /**
     * Retrieves representation of an instance of newpackage.GenericResource

     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    @Consumes("text/plain")
    @Path("getText/")
    public String getText(@QueryParam("arg1")
            @DefaultValue("") String arg1) {

       return  arg1 ;  }

    @PUT
    @Consumes("text/plain")
    public void putText(String content) {





    }
}

How to save a data.frame in R?

There are several ways. One way is to use save() to save the exact object. e.g. for data frame foo:

save(foo,file="data.Rda")

Then load it with:

load("data.Rda")

You could also use write.table() or something like that to save the table in plain text, or dput() to obtain R code to reproduce the table.

I want to vertical-align text in select box

Try to set the "line-height" attribute

Like this:

select{
    height: 28px !important;
    line-height: 28px;
}

Here you are some documentation about this attribute:

http://www.w3.org/wiki/CSS/Properties/line-height

http://www.w3schools.com/cssref/pr_dim_line-height.asp

Is it possible to use a div as content for Twitter's Popover

First of all, if you want to use HTML inside the content you need to set the HTML option to true:

$('.danger').popover({ html : true});

Then you have two options to set the content for a Popover

  • Use the data-content attribute. This is the default option.
  • Use a custom JS function which returns the HTML content.

Using data-content: You need to escape the HTML content, something like this:

<a class='danger' data-placement='above' 
   data-content="&lt;div&gt;This is your div content&lt;/div&gt;" 
   title="Title" href='#'>Click</a>

You can either escape the HTML manually or use a function. I don't know about PHP but in Rails we use *html_safe*.

Using a JS function: If you do this, you have several options. The easiest I think is to put your div content hidden wherever you want and then write a function to pass its content to popover. Something like this:

$(document).ready(function(){
  $('.danger').popover({ 
    html : true,
    content: function() {
      return $('#popover_content_wrapper').html();
    }
  });
});

And then your HTML looks like this:

<a class='danger' data-placement='above' title="Popover Title" href='#'>Click</a>
<div id="popover_content_wrapper" style="display: none">
  <div>This is your div content</div>
</div>

Hope it helps!

PS: I've had some troubles when using popover and not setting the title attribute... so, remember to always set the title.

how to convert date to a format `mm/dd/yyyy`

Are you looking for something like this?

SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]' 
            THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts,   1), 101)
            ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
      END created_ts
  FROM table1

Output:

| CREATED_TS |
|------------|
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 02/20/2012 |
| 11/29/2012 |
| 11/16/2011 |
| 02/20/2012 |
| 11/29/2012 |

Here is SQLFiddle demo

Expand/collapse section in UITableView in iOS

Expanding on this answer written in Objective C, I wrote the following for those writing in Swift

The idea is to use sections within the table and set the number of rows in the section to 1 (collapsed) and 3(expanded) when the first row in that section is tapped

The table decides how many rows to draw based on an array of Boolean values

You'll need to create two rows in storyboard and give them the reuse identifiers 'CollapsingRow' and 'GroupHeading'

import UIKit

class CollapsingTVC:UITableViewController{

    var sectionVisibilityArray:[Bool]!// Array index corresponds to section in table

    override func viewDidLoad(){
        super.viewDidLoad()
        sectionVisibilityArray = [false,false,false]
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }

    override func numberOfSections(in tableView: UITableView) -> Int{
        return sectionVisibilityArray.count
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 0
    }

    // numberOfRowsInSection - Get count of entries
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var rowsToShow:Int = 0
        if(sectionVisibilityArray[section]){
            rowsToShow = 3 // Or however many rows should be displayed in that section
        }else{
            rowsToShow = 1
        }
        return rowsToShow
    }// numberOfRowsInSection


    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if(indexPath.row == 0){
            if(sectionVisibilityArray[indexPath.section]){
                sectionVisibilityArray[indexPath.section] = false
            }else{
                sectionVisibilityArray[indexPath.section] = true
            }
            self.tableView.reloadSections([indexPath.section], with: .automatic)
        }
    }

    // cellForRowAtIndexPath - Get table cell corresponding to this IndexPath
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell:UITableViewCell

        if(indexPath.row == 0){
             cell = tableView.dequeueReusableCell(withIdentifier: "GroupHeading", for: indexPath as IndexPath)
        }else{
            cell = tableView.dequeueReusableCell(withIdentifier: "CollapsingRow", for: indexPath as IndexPath)
        }

        return cell

    }// cellForRowAtIndexPath

}

What causes javac to issue the "uses unchecked or unsafe operations" warning

The "unchecked or unsafe operations" warning was added when java added Generics, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another.

For example. the code ArrayList foo = new ArrayList(); triggers that warning because javac is looking for ArrayList<String> foo = new ArrayList<String>();

XPath to select multiple tags

You can avoid the repetition with an attribute test instead:

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

Contrary to Dimitre's antagonistic opinion, the above is not incorrect in a vacuum where the OP has not specified the interaction with namespaces. The self:: axis is namespace restrictive, local-name() is not. If the OP's intention is to capture c|d|e regardless of namespace (which I'd suggest is even a likely scenario given the OR nature of the problem) then it is "another answer that still has some positive votes" which is incorrect.

You can't be definitive without definition, though I'm quite happy to delete my answer as genuinely incorrect if the OP clarifies his question such that I am incorrect.

Read file line by line in PowerShell

The almighty switch works well here:

'one
two
three' > file

$regex = '^t'

switch -regex -file file { 
  $regex { "line is $_" } 
}

Output:

line is two
line is three

Auto Increment after delete in MySQL

You can use your mysql client software/script to specify where the primary key should start from after deleting the required records.

Powershell: How can I stop errors from being displayed in a script?

Add -ErrorAction SilentlyContinue to your script and you'll be good to go.

PHP Sort a multidimensional array by element containing date

Use usort() and a custom comparison function:

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);
    return $t1 - $t2;
}    
usort($array, 'date_compare');

EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.

usort will pass two of these records to the given comparison function date_compare() at a a time. date_compare then extracts the "datetime" field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0 if both dates are equal, a positive number if the first one ($a) is larger or a negative value if the second argument ($b) is larger. usort() uses this information to sort the array.

How to count the occurrence of certain item in an ndarray?

Personally, I'd go for: (y == 0).sum() and (y == 1).sum()

E.g.

import numpy as np
y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
num_zeros = (y == 0).sum()
num_ones = (y == 1).sum()

How to define Singleton in TypeScript

After implementing a classic pattern like

class Singleton {
  private instance: Singleton;
  
  private constructor() {}

  public getInstance() {
    if (!this.instance) { 
      this.instance = new Singleton();
    }
    return this.instance;
  }
}

I realized it's pretty useless in case you want some other class to be a singleton too. It's not extendable. You have to write that singleton stuff for every class you want to be a singleton.

Decorators for the rescue.

@singleton
class MyClassThatIsSingletonToo {}

You can write decorator by yourself or take some from npm. I found this proxy-based implementation from @keenondrums/singleton package neat enough.

Math operations from string

The easiest way is to use eval as in:

 >>> eval("2   +    2")
 4

Pay attention to the fact I included spaces in the string. eval will execute a string as if it was a Python code, so if you want the input to be in a syntax other than Python, you should parse the string yourself and calculate, for example eval("2x7") would not give you 14 because Python uses * for multiplication operator rather than x.

Random number in range [min - max] using PHP

rand(1,20)

Docs for PHP's rand function are here:

http://php.net/manual/en/function.rand.php

Use the srand() function to set the random number generator's seed value.

Get height and width of a layout programmatically

In Kotlin you can simply do this:

fr.post {
    height=fr.height
    width=fr.width
}

Static Initialization Blocks

It is a common misconception to think that a static block has only access to static fields. For this I would like to show below piece of code that I quite often use in real-life projects (copied partially from another answer in a slightly different context):

public enum Language { 
  ENGLISH("eng", "en", "en_GB", "en_US"),   
  GERMAN("de", "ge"),   
  CROATIAN("hr", "cro"),   
  RUSSIAN("ru"),
  BELGIAN("be",";-)");

  static final private Map<String,Language> ALIAS_MAP = new HashMap<String,Language>(); 
  static { 
    for (Language l:Language.values()) { 
      // ignoring the case by normalizing to uppercase
      ALIAS_MAP.put(l.name().toUpperCase(),l); 
      for (String alias:l.aliases) ALIAS_MAP.put(alias.toUpperCase(),l); 
    } 
  } 

  static public boolean has(String value) { 
    // ignoring the case by normalizing to uppercase
    return ALIAS_MAP.containsKey(value.toUpper()); 
  } 

  static public Language fromString(String value) { 
    if (value == null) throw new NullPointerException("alias null"); 
    Language l = ALIAS_MAP.get(value); 
    if (l == null) throw new IllegalArgumentException("Not an alias: "+value); 
    return l; 
  } 

  private List<String> aliases; 
  private Language(String... aliases) { 
    this.aliases = Arrays.asList(aliases); 
  } 
} 

Here the initializer is used to maintain an index (ALIAS_MAP), to map a set of aliases back to the original enum type. It is intended as an extension to the built-in valueOf method provided by the Enum itself.

As you can see, the static initializer accesses even the private field aliases. It is important to understand that the static block already has access to the Enum value instances (e.g. ENGLISH). This is because the order of initialization and execution in the case of Enum types, just as if the static private fields have been initialized with instances before the static blocks have been called:

  1. The Enum constants which are implicit static fields. This requires the Enum constructor and instance blocks, and instance initialization to occur first as well.
  2. static block and initialization of static fields in the order of occurrence.

This out-of-order initialization (constructor before static block) is important to note. It also happens when we initialize static fields with the instances similarly to a Singleton (simplifications made):

public class Foo {
  static { System.out.println("Static Block 1"); }
  public static final Foo FOO = new Foo();
  static { System.out.println("Static Block 2"); }
  public Foo() { System.out.println("Constructor"); }
  static public void main(String p[]) {
    System.out.println("In Main");
    new Foo();
  }
}

What we see is the following output:

Static Block 1
Constructor
Static Block 2
In Main
Constructor

Clear is that the static initialization actually can happen before the constructor, and even after:

Simply accessing Foo in the main method, causes the class to be loaded and the static initialization to start. But as part of the Static initialization we again call the constructors for the static fields, after which it resumes static initialization, and completes the constructor called from within the main method. Rather complex situation for which I hope that in normal coding we would not have to deal with.

For more info on this see the book "Effective Java".

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

Had the same problem a few minutes ago, I was missing the 'Maven depencendies' library in my Deployment Assembly. I added it through the section 'Web Deployment Assembly' in Eclipse

Using Java with Nvidia GPUs (CUDA)

I'd start by using one of the projects out there for Java and CUDA: http://www.jcuda.org/

Quick Way to Implement Dictionary in C

Hashing is the key. I think use lookup table and hashing key for this. You can find many hashing function online.

Get an object attribute

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

Capitalize first letter. MySQL

If anyone try to capitalize the every word separate by space...

CREATE FUNCTION response(name VARCHAR(40)) RETURNS VARCHAR(200) DETERMINISTIC
BEGIN
   set @m='';
   set @c=0;
   set @l=1;
   while @c <= char_length(name)-char_length(replace(name,' ','')) do
      set @c = @c+1;
      set @p = SUBSTRING_INDEX(name,' ',@c);
      set @k = substring(name,@l,char_length(@p)-@l+1);
      set @l = char_length(@k)+2;
      set @m = concat(@m,ucase(left(@k,1)),lcase(substring(@k,2)),' ');
   end while;
   return trim(@m); 
END;
CREATE PROCEDURE updateNames()
BEGIN
  SELECT response(name) AS name FROM names;
END;

Result

+--------------+
| name         |
+--------------+
| Abdul Karim  | 
+--------------+

Enum ToString with user friendly strings

With respect to Ray Booysen, there is a bug in the code: Enum ToString with user friendly strings

You need to account for multiple attributes on the enum values.

public static string GetDescription<T>(this object enumerationValue)
            where T : struct
    {
        Type type = enumerationValue.GetType();
        if (!type.IsEnum)
        {
            throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
        }

        //Tries to find a DescriptionAttribute for a potential friendly name
        //for the enum
        MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
        if (memberInfo != null && memberInfo.Length > 0)
        {
            object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attrs != null && attrs.Length > 0 && attrs.Where(t => t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault() != null)
            {
                //Pull out the description value
                return ((DescriptionAttribute)attrs.Where(t=>t.GetType() == typeof(DescriptionAttribute)).FirstOrDefault()).Description;
            }
        }
        //If we have no description attribute, just return the ToString of the enum
        return enumerationValue.ToString();

JavaScript variable assignments from tuples

As an update to The Minister's answer, you can now do this with es2015:

function Tuple(...args) {
  args.forEach((val, idx) => 
    Object.defineProperty(this, "item"+idx, { get: () => val })
  )
}


var t = new Tuple("a", 123)
console.log(t.item0) // "a"
t.item0 = "b"
console.log(t.item0) // "a"

https://jsbin.com/fubaluwimo/edit?js,console

Spark SQL: apply aggregate functions to a list of columns

Another example of the same concept - but say - you have 2 different columns - and you want to apply different agg functions to each of them i.e

f.groupBy("col1").agg(sum("col2").alias("col2"), avg("col3").alias("col3"), ...)

Here is the way to achieve it - though I do not yet know how to add the alias in this case

See the example below - Using Maps

val Claim1 = StructType(Seq(StructField("pid", StringType, true),StructField("diag1", StringType, true),StructField("diag2", StringType, true), StructField("allowed", IntegerType, true), StructField("allowed1", IntegerType, true)))
val claimsData1 = Seq(("PID1", "diag1", "diag2", 100, 200), ("PID1", "diag2", "diag3", 300, 600), ("PID1", "diag1", "diag5", 340, 680), ("PID2", "diag3", "diag4", 245, 490), ("PID2", "diag2", "diag1", 124, 248))

val claimRDD1 = sc.parallelize(claimsData1)
val claimRDDRow1 = claimRDD1.map(p => Row(p._1, p._2, p._3, p._4, p._5))
val claimRDD2DF1 = sqlContext.createDataFrame(claimRDDRow1, Claim1)

val l = List("allowed", "allowed1")
val exprs = l.map((_ -> "sum")).toMap
claimRDD2DF1.groupBy("pid").agg(exprs) show false
val exprs = Map("allowed" -> "sum", "allowed1" -> "avg")

claimRDD2DF1.groupBy("pid").agg(exprs) show false

How to select the first element in the dropdown using jquery?

Ana alternative Solution for RSolgberg, which fires the 'onchange' event if present:

$("#target").val($("#target option:first").val());

How to make first option of <select > selected with jQuery?

Cocoa Touch: How To Change UIView's Border Color And Thickness?

@IBInspectable is working for me on iOS 9 , Swift 2.0

extension UIView {

@IBInspectable var borderWidth: CGFloat {
get {
        return layer.borderWidth
    }
    set(newValue) {
        layer.borderWidth = newValue
    }
}

@IBInspectable var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set(newValue) {
        layer.cornerRadius = newValue
    }
}

@IBInspectable var borderColor: UIColor? {
    get {
        if let color = layer.borderColor {
            return UIColor(CGColor: color)
        }
        return nil
    }
    set(newValue) {
        layer.borderColor = newValue?.CGColor
    }
}

jQuery hasAttr checking to see if there is an attribute on an element

You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:

$("#change_password").click(function() {
    var target = $(this).attr("rel");
    if($("#" + target).attr("disabled")) {
        $("#" + target).attr("disabled", false);
    } else {
        $("#" + target).attr("disabled", true);
    }
});

The "rel" attribute stores the id of the target input field.

Reload the page after ajax success

BrixenDK is right.

.ajaxStop() callback executed when all ajax call completed. This is a best place to put your handler.

$(document).ajaxStop(function(){
    window.location.reload();
});

How to increase Bootstrap Modal Width?

The easiest way can be inline style on modal-dialog div :

<div class="modal" id="myModal">
   <div class="modal-dialog" style="width:1250px;">
      <div class="modal-content">
            ...

        </div>
     </div>
 </div>

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

in my case, this error is raised due to sequence was not created..

CREATE SEQUENCE  J.SOME_SEQ  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE ;

How can I send an xml body using requests library?

Just send xml bytes directly:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests

xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text

Output

{
  "origin": "x.x.x.x",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "48",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Connection": "keep-alive",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
    "Host": "httpbin.org",
    "Content-Type": "application/xml"
  },
  "json": null,
  "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}

How can I execute a python script from an html button?

you could use text files to trasfer the data using PHP and reading the text file in python

SQLAlchemy IN clause

An alternative way is using raw SQL mode with SQLAlchemy, I use SQLAlchemy 0.9.8, python 2.7, MySQL 5.X, and MySQL-Python as connector, in this case, a tuple is needed. My code listed below:

id_list = [1, 2, 3, 4, 5] # in most case we have an integer list or set
s = text('SELECT id, content FROM myTable WHERE id IN :id_list')
conn = engine.connect() # get a mysql connection
rs = conn.execute(s, id_list=tuple(id_list)).fetchall()

Hope everything works for you.

Class vs. static method in JavaScript

First off, remember that JavaScript is primarily a prototypal language, rather than a class-based language1. Foo isn't a class, it's a function, which is an object. You can instantiate an object from that function using the new keyword which will allow you to create something similar to a class in a standard OOP language.

I'd suggest ignoring __proto__ most of the time because it has poor cross browser support, and instead focus on learning about how prototype works.

If you have an instance of an object created from a function2 and you access one of its members (methods, attributes, properties, constants etc) in any way, the access will flow down the prototype hierarchy until it either (a) finds the member, or (b) doesn't find another prototype.

The hierarchy starts on the object that was called, and then searches its prototype object. If the prototype object has a prototype, it repeats, if no prototype exists, undefined is returned.

For example:

foo = {bar: 'baz'};
console.log(foo.bar); // logs "baz"

foo = {};
console.log(foo.bar); // logs undefined

function Foo(){}
Foo.prototype = {bar: 'baz'};
f = new Foo();
console.log(f.bar);
// logs "baz" because the object f doesn't have an attribute "bar"
// so it checks the prototype
f.bar = 'buzz';
console.log( f.bar ); // logs "buzz" because f has an attribute "bar" set

It looks to me like you've at least somewhat understood these "basic" parts already, but I need to make them explicit just to be sure.

In JavaScript, everything is an object3.

everything is an object.

function Foo(){} doesn't just define a new function, it defines a new function object that can be accessed using Foo.

This is why you can access Foo's prototype with Foo.prototype.

What you can also do is set more functions on Foo:

Foo.talk = function () {
  alert('hello world!');
};

This new function can be accessed using:

Foo.talk();

I hope by now you're noticing a similarity between functions on a function object and a static method.

Think of f = new Foo(); as creating a class instance, Foo.prototype.bar = function(){...} as defining a shared method for the class, and Foo.baz = function(){...} as defining a public static method for the class.


ECMAScript 2015 introduced a variety of syntactic sugar for these sorts of declarations to make them simpler to implement while also being easier to read. The previous example can therefore be written as:

class Foo {
  bar() {...}

  static baz() {...}
}

which allows bar to be called as:

const f = new Foo()
f.bar()

and baz to be called as:

Foo.baz()

1: class was a "Future Reserved Word" in the ECMAScript 5 specification, but ES6 introduces the ability to define classes using the class keyword.

2: essentially a class instance created by a constructor, but there are many nuanced differences that I don't want to mislead you

3: primitive values—which include undefined, null, booleans, numbers, and strings—aren't technically objects because they're low-level language implementations. Booleans, numbers, and strings still interact with the prototype chain as though they were objects, so for the purposes of this answer, it's easier to consider them "objects" even though they're not quite.

Does swift have a trim method on String?

**Swift 5**

extension String {

    func trimAllSpace() -> String {
         return components(separatedBy: .whitespacesAndNewlines).joined()
    }
    
    func trimSpace() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
}

**Use:**
let result = " abc ".trimAllSpace()
// result == "abc"
let ex = " abc cd  ".trimSpace()
// ex == "abc cd"

How to get a value of an element by name instead of ID

you can also use the class name.

$(".yourclass").val();

Why is there no Constant feature in Java?

The C++ semantics of const are very different from Java final. If the designers had used const it would have been unnecessarily confusing.

The fact that const is a reserved word suggests that the designers had ideas for implementing const, but they have since decided against it; see this closed bug. The stated reasons include that adding support for C++ style const would cause compatibility problems.

Why can't I use the 'await' operator within the body of a lock statement?

This referes to http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx , http://winrtstoragehelper.codeplex.com/ , Windows 8 app store and .net 4.5

Here is my angle on this:

The async/await language feature makes many things fairly easy but it also introduces a scenario that was rarely encounter before it was so easy to use async calls: reentrance.

This is especially true for event handlers, because for many events you don't have any clue about whats happening after you return from the event handler. One thing that might actually happen is, that the async method you are awaiting in the first event handler, gets called from another event handler still on the same thread.

Here is a real scenario I came across in a windows 8 App store app: My app has two frames: coming into and leaving from a frame I want to load/safe some data to file/storage. OnNavigatedTo/From events are used for the saving and loading. The saving and loading is done by some async utility function (like http://winrtstoragehelper.codeplex.com/). When navigating from frame 1 to frame 2 or in the other direction, the async load and safe operations are called and awaited. The event handlers become async returning void => they cant be awaited.

However, the first file open operation (lets says: inside a save function) of the utility is async too and so the first await returns control to the framework, which sometime later calls the other utility (load) via the second event handler. The load now tries to open the same file and if the file is open by now for the save operation, fails with an ACCESSDENIED exception.

A minimum solution for me is to secure the file access via a using and an AsyncLock.

private static readonly AsyncLock m_lock = new AsyncLock();
...

using (await m_lock.LockAsync())
{
    file = await folder.GetFileAsync(fileName);
    IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read);
    using (Stream inStream = Task.Run(() => readStream.AsStreamForRead()).Result)
    {
        return (T)serializer.Deserialize(inStream);
    }
}

Please note that his lock basically locks down all file operation for the utility with just one lock, which is unnecessarily strong but works fine for my scenario.

Here is my test project: a windows 8 app store app with some test calls for the original version from http://winrtstoragehelper.codeplex.com/ and my modified version that uses the AsyncLock from Stephen Toub http://blogs.msdn.com/b/pfxteam/archive/2012/02/12/10266988.aspx.

May I also suggest this link: http://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx

Unable to merge dex

This hasn't been shared here yet so hopefully it can help someone.

Following this link solved the same issue for me.

To begin, I'll note that I did not have to set multiDexEnabled to true.

First I set dependencies in my pubspec.yaml to

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore: ^0.8.2 

and ran flutter packages get in my IDE's terminal.

Also I had to change the minimum target SDK version:

  1. Open android/app/build.gradle, then find the line that says minSdkVersion 16.
  2. Change that line to minSdkVersion 21.
  3. Save the file.

This alone may fix your problem; however I had to also do the following because some of my dependency versions were mismatched.

I had to open android/app/build.gradle, then add the following line as the last line in the file: apply plugin: 'com.google.gms.google-services'

Next, I had to open android/build.gradle, then inside the buildscript tag, add a new dependency:

buildscript {
   repositories {
       // ...
   }

   dependencies {
       // ...
       classpath 'com.google.gms:google-services:3.2.1'   // new
   }
}

After this my app finally ran on the android emulator.

The link has a more complete walkthrough if you get stuck.

Also, to note, I did not have to set multiDexEnabled to true.

Regular expression to match balanced parentheses

The regular expression using Ruby (version 1.9.3 or above):

/(?<match>\((?:\g<match>|[^()]++)*\))/

Demo on rubular

Run multiple python scripts concurrently

The most simple way in my opinion would be to use the PyCharm IDE and install the 'multirun' plugin. I tried alot of the solutions here but this one worked for me in the end!

How to use fetch in typescript

Actually, pretty much anywhere in typescript, passing a value to a function with a specified type will work as desired as long as the type being passed is compatible.

That being said, the following works...

 fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json())
      .then((res: Actor) => {
          // res is now an Actor
      });

I wanted to wrap all of my http calls in a reusable class - which means I needed some way for the client to process the response in its desired form. To support this, I accept a callback lambda as a parameter to my wrapper method. The lambda declaration accepts an any type as shown here...

callBack: (response: any) => void

But in use the caller can pass a lambda that specifies the desired return type. I modified my code from above like this...

fetch(`http://swapi.co/api/people/1/`)
  .then(res => res.json())
  .then(res => {
      if (callback) {
        callback(res);    // Client receives the response as desired type.  
      }
  });

So that a client can call it with a callback like...

(response: IApigeeResponse) => {
    // Process response as an IApigeeResponse
}

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

Just convert the text explicitly to string using str(). Worked for me.

How do you use variables in a simple PostgreSQL script?

Postgresql does not have bare variables, you could use a temporary table. variables are only available in code blocks or as a user-interface feature.

If you need a bare variable you could use a temporary table:

CREATE TEMP TABLE list AS VALUES ('foobar');

SELECT dbo.PubLists.*
FROM   dbo.PubLists,list
WHERE  Name = list.column1;

Pods stuck in Terminating status

You can use following command to delete the POD forcefully.

kubectl delete pod <PODNAME> --grace-period=0 --force --namespace <NAMESPACE>

What is correct media query for IPad Pro?

This worked for me

/* Portrait */
@media only screen 
  and (min-device-width: 834px) 
  and (max-device-width: 834px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 2) {

}

/* Landscape */
@media only screen 
  and (min-width: 1112px) 
  and (max-width: 1112px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 2)
 {

}

how to set textbox value in jquery

try

subtotal.value= 5 // some value

_x000D_
_x000D_
proc = async function(x,y) {_x000D_
  let url = "https://server.test-cors.org/server?id=346169&enable=true&status=200&credentials=false&methods=GET&" // some url working in snippet_x000D_
  _x000D_
  let r= await(await fetch(url+'&prodid=' + x + '&qbuys=' + y)).json(); // return json-object_x000D_
  console.log(r);_x000D_
  _x000D_
  subtotal.value= r.length; // example value from json_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<form name="yoh" method="get"> _x000D_
Product id: <input type="text" id="pid"  value=""><br/>_x000D_
_x000D_
Quantity to buy:<input type="text" id="qtytobuy"  value="" onkeyup="proc(pid.value, this.value);"></br>_x000D_
_x000D_
Subtotal:<input type="text" name="subtotal" id="subtotal"  value=""></br>_x000D_
<div id="compz"></div>_x000D_
_x000D_
</form>
_x000D_
_x000D_
_x000D_

iPhone - Get Position of UIView within entire UIWindow

Swift 3, with extension:

extension UIView{
    var globalPoint :CGPoint? {
        return self.superview?.convert(self.frame.origin, to: nil)
    }

    var globalFrame :CGRect? {
        return self.superview?.convert(self.frame, to: nil)
    }
}

How to bind a List to a ComboBox?

Try something like this:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

yourControl.DataBind();

How to instantiate a javascript class in another js file?

It depends on what environment you're running in. In a web browser you simply need to make sure that file1.js is loaded before file2.js:

<script src="file1.js"></script>
<script src="file2.js"></script>

In node.js, the recommended way is to make file1 a module then you can load it with the require function:

require('path/to/file1.js');

It's also possible to use node's module style in HTML using the require.js library.

Program to find largest and smallest among 5 numbers without using array

For example 5 consecutive numbers

int largestNumber;
int smallestNumber;
int number;
std::cin>>number;
largestNumber = number;
smallestNumber = number;
for (i=0 ; i<5; i++)
{
   std::cin>>number;
   if (number > largestNumber) 
   {
     largest = number;
   }
   if (numbers < smallestNumber) 
   {
     smallestNumber= number;
   }
}

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

the answers above were confusing to me. Here is what i did:

  • File ->new Image Asset
  • the first field "Asset type" must be launcher icons. browse to the file you want as icon, select it and android studio will show you in the same window what it will look like under different resolutions.

  • choose a different name for it, click next. Now the icon set for all those hdpi, xhdpi, mdpi will be in corresponding mipmap folders

  • finally, most importantly go to your manifest file and change "android:icon" to the name of your new icon image.

Get textarea text with javascript or Jquery

You could use val().

var value = $('#area1').val();
$('#VAL_DISPLAY').html(value);

Extracting date from a string in Python

If the date is given in a fixed form, you can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date:

import re
from datetime import datetime

match = re.search(r'\d{4}-\d{2}-\d{2}', text)
date = datetime.strptime(match.group(), '%Y-%m-%d').date()

Otherwise, if the date is given in an arbitrary form, you can't extract it easily.

Print array to a file

file_put_contents($file, print_r($array, true), FILE_APPEND)

Local dependency in package.json

Curious.....at least on Windows (my npm is 3.something) I needed to do:

"dependencies": {
 "body-parser": "^1.17.1",
 "module1": "../module1",
 "module2": "../module2",

When I did an npm install ../module1 --save it resulted in absolute paths and not relative per the documentation.

I messed around a little more and determined that ../xxx was sufficient.

Specifically, I have the local node modules checked out to say d:\build\module1, d:\build\module2 and my node project (application) in d:\build\nodeApp.

To 'install', I:

d:\build\module1> rmdir "./node_modules" /q /s && npm install
d:\build\module2> rmdir "./node_modules" /q /s && npm install
d:\build\nodeApp> rmdir "./node_modules" /q /s && npm install

module1's package.json has a dependency of "module2": "../module2"; module2 has no local dependency; nodeApp has dependencies "module1": "../module1" and "module2": "../module2".

Not sure if this only works for me since all 3 folders (module1, module2 and nodeApp) sit on that same level.......

Map with Key as String and Value as List in Groovy

Joseph forgot to add the value in his example with withDefault. Here is the code I ended up using:

Map map = [:].withDefault { key -> return [] }
listOfObjects.each { map.get(it.myKey).add(it.myValue) }

Export DataTable to Excel File

While not a .NET implementation, you may find that the plug-in TableTools may be highly effective depending on your audience. It relies upon flash which shouldn't be a problem for most cases of needing to actually work in-depth and then want to record tabular information.

The latest version appears to support copying to clipboard, into a CSV, ".XLS" (really just a tab-delimited file named .xls), to a PDF, or create a printer friendly page version with all rows displayed and the rest of your page's contents hidden.

I found the extension on the DataTables site here: http://datatables.net/extras/tabletools/

The download is available in the plug-ins (extras) page here: http://datatables.net/extras/

It supposedly is downloaded as a part of DataTables (hence the phrase "Extras included in the DataTables package") but I didn't find it in the download I have been using. Seems to work wonderfully!

running multiple bash commands with subprocess

>>> command = "echo a; echo b"
>>> shlex.split(command);
    ['echo', 'a; echo', 'b']

so, the problem is shlex module do not handle ";"

Faking an RS232 Serial Port

If you are developing for Windows, the com0com project might be, what you are looking for.

It provides pairs of virtual COM ports that are linked via a nullmodem connetion. You can then use your favorite terminal application or whatever you like to send data to one COM port and recieve from the other one.

EDIT:

As Thomas pointed out the project lacks of a signed driver, which is especially problematic on certain Windows version (e.g. Windows 7 x64).

There are a couple of unofficial com0com versions around that do contain a signed driver. One recent verion (3.0.0.0) can be downloaded e.g. from here.

Refer to a cell in another worksheet by referencing the current worksheet's name?

Here is how I made monthly page in similar manner as Fernando:

  1. I wrote manually on each page number of the month and named that place as ThisMonth. Note that you can do this only before you make copies of the sheet. After copying Excel doesn't allow you to use same name, but with sheet copy it does it still. This solution works also without naming.
  2. I added number of weeks in the month to location C12. Naming is fine also.
  3. I made five weeks on every page and on fifth week I made function

      =IF(C12=5,DATE(YEAR(B48),MONTH(B48),DAY(B48)+7),"")
    

    that empties fifth week if this month has only four weeks. C12 holds the number of weeks.

  4. ...
  5. I created annual Excel, so I had 12 sheets in it: one for each month. In this example name of the sheet is "Month". Note that this solutions works also with the ODS file standard except you need to change all spaces as "_" characters.
  6. I renamed first "Month" sheet as "Month (1)" so it follows the same naming principle. You could also name it as "Month1" if you wish, but "January" would require a bit more work.
  7. Insert following function on the first day field starting sheet #2:

     =INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!B15"))+INDIRECT(CONCATENATE("'Month (",ThisMonth-1,")'!C12"))*7
    

    So in another word, if you fill four or five weeks on the previous sheet, this calculates date correctly and continues from correct date.

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

If you have VS2013 installed and are getting this error, you may be invoking the wrong MSBuild. With VS2013, Microsoft now includes MSBuild as part of Visual Studio. See this Visual Studio blog posting for details.

In particular, note the new location of the binaries:

On 32-bit machines they can be found in: C:\Program Files\MSBuild\12.0\bin

On 64-bit machines the 32-bit tools will be under: C:\Program Files (x86)\MSBuild\12.0\bin

and the 64-bit tools under: C:\Program Files (x86)\MSBuild\12.0\bin\amd64

The MSBuild in %WINDIR%\Microsoft.NET\Framework\ doesn't seem to recognize the VS2013 (v120) platform toolset.

How to iterate over a TreeMap?

Assuming type TreeMap<String,Integer> :

for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
  String key = entry.getKey();
  Integer value = entry.getValue();

  System.out.println(key + " => " + value);
}

(key and Value types can be any class of course)

How to test android apps in a real device with Android Studio?

To test an android apps in a real device with Android Studio, You must keep two things in mind

  1. You should enable USB debugging option on your android phone.
  2. You must have driver installed on your computer.

Now , let me tell you how you can enable USB debugging on your android phone:

  1. Go to Settings on your android phone
  2. Scroll down to the bottom and click on About phone
  3. On this menu also scroll down to the bottom, you should see something Build number
  4. Click on Build number 7 times
  5. Now your Developer Option enables, once you done click on back button and you should see a new option on your android screen i.e. Developer Options
  6. Click On Developer Options
  7. Scroll down until you see USB Debugging
  8. Go ahead and click the check box next to the USB debugging
  9. Now your USB Debugging option enables.
  10. Connect your android device to your computer with the help of USB connector.

Now let me tell you how you can download the driver on your Windows PC:

  1. Your windows machine need a software called driver to communicate with your phone.
  2. Go To OEM USB Driver Website to install your appropriate driver
  3. Scroll down and select the driver appropriate for your device. Check the screen shoot
  4. Once you download it , you have to unzip your file
  5. After Installing Google USB Driver, close SDK Manager window, Connect your phone or tablet through USB cable to your laptop or PC.
  6. Now click on My Computer (Windows 7) (or) This PC(Windows 8.1).Select Manage.
  7. Select Device Manager –> Portable Devices –> Your Device Name
  8. Right Click on Your Device Name and Select Browse My Computer For Driver Software.
  9. Point it to C:\Users\YourUserName\AppData\Local\Android\sdk\extras\google\usb_driver. Hit Next and Finish.
  10. Now Hit Run Button after selecting Your Project in Project Explorer in Android studio. Choose your device and press OK.

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

How to find list of possible words from a letter matrix [Boggle Solver]

You could split the problem up into two pieces:

  1. Some kind of search algorithm that will enumerate possible strings in the grid.
  2. A way of testing whether a string is a valid word.

Ideally, (2) should also include a way of testing whether a string is a prefix of a valid word – this will allow you to prune your search and save a whole heap of time.

Adam Rosenfield's Trie is a solution to (2). It's elegant and probably what your algorithms specialist would prefer, but with modern languages and modern computers, we can be a bit lazier. Also, as Kent suggests, we can reduce our dictionary size by discarding words that have letters not present in the grid. Here's some python:

def make_lookups(grid, fn='dict.txt'):
    # Make set of valid characters.
    chars = set()
    for word in grid:
        chars.update(word)

    words = set(x.strip() for x in open(fn) if set(x.strip()) <= chars)
    prefixes = set()
    for w in words:
        for i in range(len(w)+1):
            prefixes.add(w[:i])

    return words, prefixes

Wow; constant-time prefix testing. It takes a couple of seconds to load the dictionary you linked, but only a couple :-) (notice that words <= prefixes)

Now, for part (1), I'm inclined to think in terms of graphs. So I'll build a dictionary that looks something like this:

graph = { (x, y):set([(x0,y0), (x1,y1), (x2,y2)]), }

i.e. graph[(x, y)] is the set of coordinates that you can reach from position (x, y). I'll also add a dummy node None which will connect to everything.

Building it's a bit clumsy, because there's 8 possible positions and you have to do bounds checking. Here's some correspondingly-clumsy python code:

def make_graph(grid):
    root = None
    graph = { root:set() }
    chardict = { root:'' }

    for i, row in enumerate(grid):
        for j, char in enumerate(row):
            chardict[(i, j)] = char
            node = (i, j)
            children = set()
            graph[node] = children
            graph[root].add(node)
            add_children(node, children, grid)

    return graph, chardict

def add_children(node, children, grid):
    x0, y0 = node
    for i in [-1,0,1]:
        x = x0 + i
        if not (0 <= x < len(grid)):
            continue
        for j in [-1,0,1]:
            y = y0 + j
            if not (0 <= y < len(grid[0])) or (i == j == 0):
                continue

            children.add((x,y))

This code also builds up a dictionary mapping (x,y) to the corresponding character. This lets me turn a list of positions into a word:

def to_word(chardict, pos_list):
    return ''.join(chardict[x] for x in pos_list)

Finally, we do a depth-first search. The basic procedure is:

  1. The search arrives at a particular node.
  2. Check if the path so far could be part of a word. If not, don't explore this branch any further.
  3. Check if the path so far is a word. If so, add to the list of results.
  4. Explore all children not part of the path so far.

Python:

def find_words(graph, chardict, position, prefix, results, words, prefixes):
    """ Arguments:
      graph :: mapping (x,y) to set of reachable positions
      chardict :: mapping (x,y) to character
      position :: current position (x,y) -- equals prefix[-1]
      prefix :: list of positions in current string
      results :: set of words found
      words :: set of valid words in the dictionary
      prefixes :: set of valid words or prefixes thereof
    """
    word = to_word(chardict, prefix)

    if word not in prefixes:
        return

    if word in words:
        results.add(word)

    for child in graph[position]:
        if child not in prefix:
            find_words(graph, chardict, child, prefix+[child], results, words, prefixes)

Run the code as:

grid = ['fxie', 'amlo', 'ewbx', 'astu']
g, c = make_graph(grid)
w, p = make_lookups(grid)
res = set()
find_words(g, c, None, [], res, w, p)

and inspect res to see the answers. Here's a list of words found for your example, sorted by size:

 ['a', 'b', 'e', 'f', 'i', 'l', 'm', 'o', 's', 't',
 'u', 'w', 'x', 'ae', 'am', 'as', 'aw', 'ax', 'bo',
 'bu', 'ea', 'el', 'em', 'es', 'fa', 'ie', 'io', 'li',
 'lo', 'ma', 'me', 'mi', 'oe', 'ox', 'sa', 'se', 'st',
 'tu', 'ut', 'wa', 'we', 'xi', 'aes', 'ame', 'ami',
 'ase', 'ast', 'awa', 'awe', 'awl', 'blo', 'but', 'elb',
 'elm', 'fae', 'fam', 'lei', 'lie', 'lim', 'lob', 'lox',
 'mae', 'maw', 'mew', 'mil', 'mix', 'oil', 'olm', 'saw',
 'sea', 'sew', 'swa', 'tub', 'tux', 'twa', 'wae', 'was',
 'wax', 'wem', 'ambo', 'amil', 'amli', 'asem', 'axil',
 'axle', 'bleo', 'boil', 'bole', 'east', 'fame', 'limb',
 'lime', 'mesa', 'mewl', 'mile', 'milo', 'oime', 'sawt',
 'seam', 'seax', 'semi', 'stub', 'swam', 'twae', 'twas',
 'wame', 'wase', 'wast', 'weam', 'west', 'amble', 'awest',
 'axile', 'embox', 'limbo', 'limes', 'swami', 'embole',
 'famble', 'semble', 'wamble']

The code takes (literally) a couple of seconds to load the dictionary, but the rest is instant on my machine.

Delete duplicate records from a SQL table without a primary key

DELETE FROM 'test' 
USING 'test' , 'test' as vtable
WHERE test.id>vtable.id and test.common_column=vtable.common_column  

Using this we can remove duplicate records

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

Convert an integer to an array of digits

Try this!


int num = 1234; 

String s = Integer.toString(num); 

int[] intArray = new int[s.length()]; 


for(int i=0; i<s.length(); i++){
    intArray[i] = Character.getNumericValue(s.charAt(i));
}

JavaScript DOM remove element

removeChild should be invoked on the parent, i.e.:

parent.removeChild(child);

In your example, you should be doing something like:

if (frameid) {
    frameid.parentNode.removeChild(frameid);
}

The default XML namespace of the project must be the MSBuild XML namespace

if the project is not a big ,

1- change the name of folder project

2- make a new project with the same project (before renaming)

3- add existing files from the old project to the new project (totally same , same folders , same names , ...)

4- open the the new project file (as xml ) and the old project

5- copy the new project file (xml content ) and paste it in the old project file

6- delete the old project

7- rename the old folder project to old name

Fast Bitmap Blur For Android SDK

Thanks @Yahel for the code. Posting the same method with alpha channel blurring support as it took me some time to make it work correctly so it may save someone's time:

/**
 * Stack Blur v1.0 from
 * http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
 * Java Author: Mario Klingemann <mario at quasimondo.com>
 * http://incubator.quasimondo.com
 * <p/>
 * created Feburary 29, 2004
 * Android port : Yahel Bouaziz <yahel at kayenko.com>
 * http://www.kayenko.com
 * ported april 5th, 2012
 * <p/>
 * This is a compromise between Gaussian Blur and Box blur
 * It creates much better looking blurs than Box Blur, but is
 * 7x faster than my Gaussian Blur implementation.
 * <p/>
 * I called it Stack Blur because this describes best how this
 * filter works internally: it creates a kind of moving stack
 * of colors whilst scanning through the image. Thereby it
 * just has to add one new block of color to the right side
 * of the stack and remove the leftmost color. The remaining
 * colors on the topmost layer of the stack are either added on
 * or reduced by one, depending on if they are on the right or
 * on the left side of the stack.
 * <p/>
 * If you are using this algorithm in your code please add
 * the following line:
 * Stack Blur Algorithm by Mario Klingemann <[email protected]>
 */

public static Bitmap fastblur(Bitmap sentBitmap, float scale, int radius) {

    int width = Math.round(sentBitmap.getWidth() * scale);
    int height = Math.round(sentBitmap.getHeight() * scale);
    sentBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);

    Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

    if (radius < 1) {
        return (null);
    }

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int[] pix = new int[w * h];
    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int a[] = new int[wh];
    int rsum, gsum, bsum, asum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][4];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum, aoutsum;
    int rinsum, ginsum, binsum, ainsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = ainsum = routsum = goutsum = boutsum = aoutsum = rsum = gsum = bsum = asum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            sir[3] = 0xff & (p >> 24);

            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            asum += sir[3] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];
            a[yi] = dv[asum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            sir[3] = 0xff & (p >> 24);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = ainsum = routsum = goutsum = boutsum = aoutsum = rsum = gsum = bsum = asum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];
            sir[3] = a[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;
            asum += a[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            pix[yi] = (dv[asum] << 24) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];


            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];
            sir[3] = a[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            yi += w;
        }
    }

    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.setPixels(pix, 0, w, 0, 0, w, h);

    return (bitmap);
}

What exactly is the difference between Web API and REST API in MVC?

I have been there, like so many of us. There are so many confusing words like Web API, REST, RESTful, HTTP, SOAP, WCF, Web Services... and many more around this topic. But I am going to give brief explanation of only those which you have asked.

REST

It is neither an API nor a framework. It is just an architectural concept. You can find more details here.

RESTful

I have not come across any formal definition of RESTful anywhere. I believe it is just another buzzword for APIs to say if they comply with REST specifications.

EDIT: There is another trending open source initiative OpenAPI Specification (OAS) (formerly known as Swagger) to standardise REST APIs.

Web API

It in an open source framework for writing HTTP APIs. These APIs can be RESTful or not. Most HTTP APIs we write are not RESTful. This framework implements HTTP protocol specification and hence you hear terms like URIs, request/response headers, caching, versioning, various content types(formats).

Note: I have not used the term Web Services deliberately because it is a confusing term to use. Some people use this as a generic concept, I preferred to call them HTTP APIs. There is an actual framework named 'Web Services' by Microsoft like Web API. However it implements another protocol called SOAP.