Programs & Examples On #Auto populate

Populate the data elements automatically as they are requested.

Disabling Chrome Autofill

I've found that adding this to a form prevents Chrome from using Autofill.

<div style="display: none;">
    <input type="text" id="PreventChromeAutocomplete" name="PreventChromeAutocomplete" autocomplete="address-level4" />
</div>

Found here. https://code.google.com/p/chromium/issues/detail?id=468153#hc41

Really disappointing that Chrome has decided that it knows better than the developer about when to Autocomplete. Has a real Microsoft feel to it.

How to add default signature in Outlook

Outlook adds the signature to the new unmodified messages (you should not modify the body prior to that) when you call MailItem.Display (which causes the message to be displayed on the screen) or when you access the MailItem.GetInspector property - you do not have to do anything with the returned Inspector object, but Outlook will populate the message body with the signature.

Once the signature is added, read the HTMLBody property and merge it with the HTML string that you are trying to set. Note that you cannot simply concatenate 2 HTML strings - the strings need to be merged. E.g. if you want to insert your string at the top of the HTML body, look for the "<body" substring, then find the next occurrence of ">" (this takes care of the <body> element with attributes), then insert your HTML string after that ">".

Outlook Object Model does not expose signatures at all.

On a general note, the name of the signature is stored in the account profile data accessible through the IOlkAccountManager Extended MAPI interface. Since that interface is Extended MAPI, it can only be accessed using C++ or Delphi. You can see the interface and its data in OutlookSpy if you click the IOlkAccountManager button.
Once you have the signature name, you can read the HTML file from the file system (keep in mind that the folder name (Signatures in English) is localized.
Also keep in mind that if the signature contains images, they must also be added to the message as attachments and the <img> tags in the signature/message body adjusted to point the src attribute to the attachments rather than a subfolder of the Signatures folder where the images are stored.
It will also be your responsibility to merge the HTML styles from the signature HTML file with the styles of the message itself.

If using Redemption is an option, you can use its RDOAccount object (accessible in any language, including VBA). New message signature name is stored in the 0x0016001F property, reply signature is in 0x0017001F. You can also use the RDOAccount.ReplySignature and NewSignature properties.
Redemption also exposes RDOSignature.ApplyTo method that takes a pointer to the RDOMail object and inserts the signature at the specified location correctly merging the images and the styles:

set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Drafts = Session.GetDefaultFolder(olFolderDrafts)
set   Msg = Drafts.Items.Add
Msg.To =   "[email protected]"
Msg.Subject  = "testing signatures"
Msg.HTMLBody = "<html><body>some <b>bold</b> message text</body></html>"
set Account = Session.Accounts.GetOrder(2).Item(1)   'first mail account
if  Not (Account  Is  Nothing)  Then
     set Signature = Account.NewMessageSignature
     if  Not (Signature  Is  Nothing)  Then
       Signature.ApplyTo Msg,  false   'apply at the bottom
     End If
End If
Msg.Send

EDIT: as of July 2017, MailItem.GetInspector in Outlook 2016 no longer inserts the signature. Only MailItem.Display does.

How to populate/instantiate a C# array with a single value?

Create a new array with a thousand true values:

var items = Enumerable.Repeat<bool>(true, 1000).ToArray();  // Or ToList(), etc.

Similarly, you can generate integer sequences:

var items = Enumerable.Range(0, 1000).ToArray();  // 0..999

Can a JSON value contain a multiline string

I believe it depends on what json interpreter you're using... in plain javascript you could use line terminators

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : "this is a very long line which is not easily readble. \
                  so i would like to write it in multiple lines. \
                  but, i do NOT require any new lines in the output."
    }
  }
}

how to install Lex and Yacc in Ubuntu?

Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:

sudo apt-get install bison flex

There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.

Where is Python language used?

Python is also great for scientific programs such as statistical models or physics sims. I've done monte-carlo programs and, using the VISUAL module, a 3D simulation of the Apollo mission.

Unit testing with mockito for constructors

I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach

Class First {

   private Second second;

   public First(int num, String str) {
     if(second== null)
     {
       //when junit runs, you get the mocked object(not null), hence don't 
       //initialize            
       second = new Second(str);
     }
     this.num = num;
   }

   ... // some other methods
}

And, for test:

class TestFirst{
    @InjectMock
    First first;//inject mock the real testable class
    @Mock
    Second second

    testMethod(){

        //now you can play around with any method of the Second class using its 
        //mocked object(second),like:
        when(second.getSomething(String.class)).thenReturn(null);
    }
}

How do I calculate someone's age based on a DateTime type birthday?

I think this problem can be solved with an easier way like this-

The class can be like-

using System;

namespace TSA
{
    class BirthDay
    {
        double ageDay;
        public BirthDay(int day, int month, int year)
        {
            DateTime birthDate = new DateTime(year, month, day);
            ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow
        }

        internal int GetAgeYear()
        {
            return (int)Math.Truncate(ageDay / 365);
        }

        internal int GetAgeMonth()
        {
            return (int)Math.Truncate((ageDay % 365) / 30);
        }
    }
}

And calls can be like-

BirthDay b = new BirthDay(1,12,1990);
int year = b.GetAgeYear();
int month = b.GetAgeMonth();

For vs. while in C programming?

They're all interchangeable; you could pick one type and use nothing but that forever, but usually one is more convenient for a given task. It's like saying "why have switch, you can just use a bunch of if statements" -- true, but if it's a common pattern to check a variable for a set of values, it's convenient and much easier to read if there's a language feature to do that

Remove numbers from string sql server

This one works for me

CREATE Function [dbo].[RemoveNumericCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin

    Declare @NumRange as varchar(50) = '%[0-9]%'
    While PatIndex(@NumRange, @Temp) > 0
        Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '')

    Return @Temp
End

and you can use it like so

SELECT dbo.[RemoveNumericCharacters](Name) FROM TARGET_TABLE

Drop view if exists

your exists syntax is wrong and you should seperate DDL with go like below

if exists(select 1 from sys.views where name='tst' and type='v')
drop view tst;
go

create view tst
as
select * from test

you also can check existence test, with object_id like below

if object_id('tst','v') is not null
drop view tst;
go

create view tst
as
select * from test

In SQL 2016,you can use below syntax to drop

Drop view  if exists dbo.tst

From SQL2016 CU1,you can do below

create or alter view vwTest
as
 select 1 as col;
go

Oracle - Insert New Row with Auto Incremental ID

This is a simple way to do it without any triggers or sequences:

insert into WORKQUEUE (ID, facilitycode, workaction, description)
  values ((select max(ID)+1 from WORKQUEUE), 'J', 'II', 'TESTVALUES')

It worked for me but would not work with an empty table, I guess.

How to change target build on Android project?

As Mike way says. Change target BEFORE doing anything in your project that requires a higher target like android:installLocation="auto".

How to use NSURLConnection to connect with SSL for an untrusted cert?

NSURLRequest has a private method called setAllowsAnyHTTPSCertificate:forHost:, which will do exactly what you'd like. You could define the allowsAnyHTTPSCertificateForHost: method on NSURLRequest via a category, and set it to return YES for the host that you'd like to override.

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

Datatables - Search Box outside datatable

$('#example').DataTable({
   "bProcessing": true,
   "bServerSide": true,
   "sAjaxSource": "../admin/ajax/loadtransajax.php",
   "fnServerParams": function (aoData) {
        // Initialize your variables here
        // I have assign the textbox value for "text_min_val"
        var min_val = $("#min").val();  //push to the aoData
        aoData.push({name: "text_min_val", value:min_val});
   },
   "fnCreatedRow": function (nRow, aData, iDataIndex) {
       $(nRow).attr('id', 'tr_' + aData[0]);
       $(nRow).attr('name', 'tr_' + aData[0]);
       $(nRow).attr('min', 'tr_' + aData[0]); 
       $(nRow).attr('max', 'tr_' + aData[0]); 
   }
});

In loadtransajax.php you may receive the get value:

if ($_GET['text_min_val']){
    $sWhere = "WHERE ("; 
    $sWhere .= " t_group_no LIKE '%" . mysql_real_escape_string($_GET['text_min_val']) . "%' ";
    $sWhere .= ')';
}

How to turn off magic quotes on shared hosting?

While I can't say why php_flag is giving you 500 Internal Server Errors, I will point out that the PHP manual has an example of detecting if magic quotes is on and stripping it from the superglobals at runtime. Unlike the others posted, this one is recursive and will correctly strip quotes from arrays:

Update: I noticed today that there's a new version of the following code on the PHP manual that uses references to the super-globals instead.

Old version:

<?php
if (get_magic_quotes_gpc()) {
    function stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);

        return $value;
    }

    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
?>

New version:

<?php
if (get_magic_quotes_gpc()) {
    $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
    while (list($key, $val) = each($process)) {
        foreach ($val as $k => $v) {
            unset($process[$key][$k]);
            if (is_array($v)) {
                $process[$key][stripslashes($k)] = $v;
                $process[] = &$process[$key][stripslashes($k)];
            } else {
                $process[$key][stripslashes($k)] = stripslashes($v);
            }
        }
    }
    unset($process);
}
?>

Download File Using jQuery

See here for a similar post on using jQuery to clear forms: Resetting a multi-stage form with jQuery

You may also be running into an issue where the values are being repopulated by the struts value stack. In other words, you submit your form, do whatever in the action class, but do not clear the related field values in the action class. In this scenario the form would appear to maintain the values you previously submitted. If you are persisting these in some way, just null each field value in your action class after persisting and prior to returning SUCCESS.

How do I remove a library from the arduino environment?

For others who are looking to remove a built-in library, the route is to get into PackageContents -> Java -> libraries.

BUT : IT MAKES NO SENSE TO ELIMINATE LIBRARIES inside the app, they don't take space, don't have any influence on performance, and if you don't know what you are doing, you can harm the program. I did it because Arduino told me about libraries to update, showing then a board I don't have, and when saying ok it wanted to install a lot of new dependencies - I just felt forced to something I don't want, so I deinstalled that board.

JavaScript: changing the value of onclick with or without jQuery

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

You also said:

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors

C# Reflection: How to get class reference from string?

Bit late for reply but this should do the trick

Type myType = Type.GetType("AssemblyQualifiedName");

your assembly qualified name should be like this

"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"

Get the data received in a Flask request

Here's an example of posting form data to add a user to a database. Check request.method == "POST" to check if the form was submitted. Use keys from request.form to get the form data. Render an HTML template with a <form> otherwise. The fields in the form should have name attributes that match the keys in request.form.

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/user/add", methods=["GET", "POST"])
def add_user():
    if request.method == "POST":
        user = User(
            username=request.form["username"],
            email=request.form["email"],
        )
        db.session.add(user)
        db.session.commit()
        return redirect(url_for("index"))

    return render_template("add_user.html")
<form method="post">
    <label for="username">Username</label>
    <input type="text" name="username" id="username">
    <label for="email">Email</label>
    <input type="email" name="email" id="email">
    <input type="submit">
</form>

Can you autoplay HTML5 videos on the iPad?

I want to start by saying by saying that I realize this question is old and already has an accepted answer; but, as an unfortunate internet user that used this question as a means to end only to be proven wrong shortly after (but not before I upset my client a little) I want to add my thoughts and suggestions.

While @DSG and @Giona are correct, and there is nothing wrong with their answers, there is a creative mechanism you can employ to "get around," so to speak, this limitation. That is not say that I'm condoning circumvention of this feature, quite the contrary, but just some mechanisms so that a user still "feels" as if a video or audio file is "auto playing."

The quick work around is hide a video tag somewhere on the mobile page, since I built a responsive site I only do this for smaller screens. The video tag (HTML and jQuery examples):

HTML

<video id="dummyVideo" src="" preload="none" width="1" height="2"></video>

jQuery

var $dummyVideo = $("<video />", {
  id: "dummyVideo",
  src: "",
  preload: "none",
  width: "1",
  height: "2"
});

With that hidden on the page, when a user "clicks" to watch a movie (still user interaction, there is no way to get around that requirement) instead of navigating to a secondary watch page I load the hidden video. This mainly works because the media tag isn't really used but instead promoted to a Quicktime instance so having a visible video element isn't necessary at all. In the handler for "click" (or "touchend" on mobile).

$(".movie-container").on("click", function() {
  var url = $(this).data("stream-url");
  $dummyVideo.attr("src", url);
  $dummyVideo.get(0).load(); // required if src changed after page load
  $dummyVideo.get(0).play();
});

And viola. As far as UX goes, a user clicks on a video to play and Quicktime opens playing the video they chose. This remains within the limitation that videos can only be played via user action so I'm not forcing data on anyone who isn't deciding to watch a video with this service. I discovered this when trying to figure out how exactly Youtube pulled this off with their mobile which is essentially some really nice Javascript page building and fancy element hiding like in the case of the video tag.

tl;dr Here is a somewhat "workaround" to try and create an "autoplay" UX feature on iOS devices without going above and beyond Apple's limitations and still having users decide if they want to watch a video (or audio most likey, though I've not tested) themselves without having one just loaded without their permission.

Also, to the person who commented that is from sleep.fm, this still unfortunately would not have been a solution to your issues which is time based audio play back.

I hope someone finds this information useful, it would have saved me a week of bad news delivery to a client that was adamant that they have this feature and I was glad to find a way to deliver it in the end.

EDIT

Further finding indicate the above workaround is for iPhone/iPod devices only. The iPad plays video in Safari before it's been full screened so you'll need some mechanism to resize the video on click before playing or else you'll end up with audio and no video.

Why does my Eclipse keep not responding?

I just restarted the adb (Android Debug Bridge) this way:

  1. adb kill-server
  2. adb start-server

and it works again!

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

ASP.NET MVC DropDownListFor with model of type List<string>

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

How to check undefined in Typescript

Late to the story but I think some details are overlooked?

if you use

if (uemail !== undefined) {
  //some function
}

You are, technically, comparing variable uemail with variable undefined and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true. But it overlooks the potential that a variable by the name of undefined may actually exist -however unlikely- and would therefore then not be of type undefined. In that case, the comparison will return false.

To be correct one would have to declare a constant of type undefined for example:

const _undefined: undefined

and then test by:

if (uemail === _undefined) {
  //some function
}

This test will return true as uemail now equals both value & type of _undefined as _undefined is now properly declared to be of type undefined.

Another way would be

if (typeof(uemail) === 'undefined') {
  //some function
}

In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.

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

I had issues including toolbar in a RelativeLayout, try with LinearLayout. If you want to overlay the toolbar, try with:

 <RelativeLayout>

    <LinearLayout>
      --INCLUDE tOOLBAR--
    </LinearLayout>

    <Button></Button>

 </RelativeLayout>

I don't understand why but it works for me.

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

On a Fedora 18 with Mongo 2.2.4 instance I was able to get around a similar error by disabling SELinux by calling setenforce 0 as root.

BTW, this was a corporate environment, not an Amazon EC2 instance, but the symptoms were similar.

Sequence contains no elements?

From "Fixing LINQ Error: Sequence contains no elements":

When you get the LINQ error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

This can also be caused by the following commands:

  • FirstAsync()
  • SingleAsync()
  • Last()
  • LastAsync()
  • Max()
  • Min()
  • Average()
  • Aggregate()

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Make sure you have a jdk setup. To do this, create a new project and then go to file -> project structure. From there you can add a new jdk. Once that is setup, go back to your gradle project and you should have a jdk to select in the 'Gradle JVM' field.

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

Error importing Seaborn module in Python

I had faced the same problem. Restarting the notebook solved my problem.

If that doesn't solve the problem, you can try this

pip install seaborn

Edit

As few people have posted in the comments, you can also use

python -m pip install seaborn

Plus, as per https://bugs.python.org/issue22295 it is a better way because in this case, you can specify which version of python (python3 or python2) to use for running pip

how to get login option for phpmyadmin in xampp

Can you set the password to the phpmyadmin here

http://localhost/security/index.php

Android. WebView and loadData

the answers above doesn't work in my case. You need to specify utf-8 in meta tag

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <!-- you content goes here -->
    </body>
</html>

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.

This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.


Performance difference

Let's first tackle "the elephant in the room" – that xpath is slower than css.

With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?

If there is a difference, it is in a fraction of a millisecond.

Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.

So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.


The measurements

There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.

The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:

enter image description here

Here's the test code (python):

from selenium import webdriver
import timeit


if __name__ == '__main__':

    xpath_locator = '//div[@class="button-section col-xs-12 row"]'
    css_locator = 'div.button-section.col-xs-12.row'

    repetitions = 1000

    driver = webdriver.Chrome()
    driver.get('https://www.browserstack.com/')

    css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)", 
                             number=repetitions, globals=globals())
    xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)', 
                             number=repetitions, globals=globals())

    driver.quit()

    print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, css_time, (css_time/repetitions)*1000))
    print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, xpath_time, (xpath_time/repetitions)*1000))

For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.

The locators are:

  • for xpath – "a div element having this exact class value, somewhere in the DOM";
  • the css is similar – "a div element with this class, somewhere in the DOM".

Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".

The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).

Here's the output:

css total time 1000 repeats: 8.84s, per find: 8.84ms

xpath total time for 1000 repeats: 8.52s, per find: 8.52ms

Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.


Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):

xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'

The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:

css total time 1000 repeats: 8.60s, per find: 8.60ms

xpath total time for 1000 repeats: 8.75s, per find: 8.75ms

Diff of 0.15ms.


As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.

They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?

The same code as above, with these changes in:

  • The url is now http://the-internet.herokuapp.com/tables; there are 2 tests.

  • The locators for the first one - "Finding Elements By ID and Class" - are:

css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"

And here is the outcome:

css total time 1000 repeats: 8.24s, per find: 8.24ms

xpath total time for 1000 repeats: 8.45s, per find: 8.45ms

Diff of 0.2 milliseconds.

The "Finding Elements By Traversing":

css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"

The result:

css total time 1000 repeats: 9.29s, per find: 9.29ms

xpath total time for 1000 repeats: 8.79s, per find: 8.79ms

This time it is 0.5 ms (in reverse, xpath turned out "faster" here).

So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.


So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.

Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.

Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"


The XPath advantage

With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.

Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4)); embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).

The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.

Outro ;)

Finally, again very subjective - which one to chose?

IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.

Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.

What is the difference between <html lang="en"> and <html lang="en-US">?

Well, the first question is easy. There are many ens (Englishes) but (mostly) only one US English. One would guess there are en-CN, en-GB, en-AU. Guess there might even be Austrian English but that's more yes you can than yes there is.

window.onload vs document.onload

window.onload however they are often the same thing. Similarly body.onload becomes window.onload in IE.

What is the difference between List and ArrayList?

There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList();

you can only call methods and reference members that are defined in the List interface. If you define it as:

ArrayList myList = new ArrayList();

you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.

Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).

That's called polymorphism. You can read up on it.

How do I create a Bash alias?

If you put blah="/usr/bin/blah" in your ~/.bashrc then you can use $blah in your login shell as a substitute for typing /usr/bin/blah

Fastest way to determine if record exists

SELECT COUNT(*) FROM products WHERE products.id = ?;

This is the cross relational database solution that works in all databases.

Least common multiple for 3 or more numbers

I just figured this out in Haskell:

lcm' :: Integral a => a -> a -> a
lcm' a b = a`div`(gcd a b) * b
lcm :: Integral a => [a] -> a
lcm (n:ns) = foldr lcm' n ns

I even took the time to write my own gcd function, only to find it in Prelude! Lots of learning for me today :D

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

Could not find an implementation of the query pattern

Hi easiest way to do this is to convert this IEnumerable into a Queryable

If it is a queryable, then performing queries becomes easy.

Please check this code:

var result = (from s in _ctx.ScannedDatas.AsQueryable()
                              where s.Data == scanData
                              select s.Id).FirstOrDefault();
                return "Match Found";

Make sure you include System.Linq. This way your error will be resolved.

Loop through files in a folder using VBA?

Dir function loses focus easily when I handle and process files from other folders.

I've gotten better results with the component FileSystemObject.

Full example is given here:

http://www.xl-central.com/list-files-fso.html

Don't forget to set a reference in the Visual Basic Editor to Microsoft Scripting Runtime (by using Tools > References)

Give it a try!

How to show text in combobox when no item selected?

Why not do it XAML?

<ComboBox x:Name="myComboBoxMenu" PlaceholderText="Hello"/>

PHP MySQL Query Where x = $variable

What you are doing right now is you are adding . on the string and not concatenating. It should be,

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '".$email."'");

or simply

$result = mysqli_query($con,"SELECT `note` FROM `glogin_users` WHERE email = '$email'");

Java string split with "." (dot)

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.


You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

How to ignore SSL certificate errors in Apache HttpClient 4.0

With fluent 4.5.2 i had to make the following modification to make it work.

try {
    TrustManager[] trustAllCerts = new TrustManager[] {
       new X509TrustManager() {
    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }
    public void checkClientTrusted(X509Certificate[] certs, String authType) {  }

    public void checkServerTrusted(X509Certificate[] certs, String authType) {  }
    }
    };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new SecureRandom());
    CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).setSslcontext(sc).build();

    String output = Executor.newInstance(httpClient).execute(Request.Get("https://127.0.0.1:3000/something")
                                      .connectTimeout(1000)
                                      .socketTimeout(1000)).returnContent().asString();
    } catch (Exception e) {
    }

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

Thats just the directories showing you where PHP was looking for your file. Make sure that cron1.php exists where you think it does. And make sure you know where dirname(__FILE__) and $_SERVER['DOCUMENT_ROOT'] are pointing where you'd expect.

This value can be adjusted in your php.ini file.

Getting Unexpected Token Export

There is no need to use Babel at this moment (JS has become very powerful) when you can simply use the default JavaScript module exports. Check full tutorial

Message.js

module.exports = 'Hello world';

app.js

var msg = require('./Messages.js');

console.log(msg); // Hello World

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

Can I scroll a ScrollView programmatically in Android?

Note: if you already in a thread, you have to make a new post thread, or it's not scroll new long height till the full end (for me). For ex:

void LogMe(final String s){
    runOnUiThread(new Runnable() {
        public void run() {
            connectionLog.setText(connectionLog.getText() + "\n" + s);
            final ScrollView sv = (ScrollView)connectLayout.findViewById(R.id.scrollView);
            sv.post(new Runnable() {
                public void run() {
                    sv.fullScroll(sv.FOCUS_DOWN);
                    /*
                    sv.scrollTo(0,sv.getBottom());
                    sv.scrollBy(0,sv.getHeight());*/
                }
            });
        }
    });
}

Android: Test Push Notification online (Google Cloud Messaging)

Postman is a good solution and so is php fiddle. However to avoid putting in the GCM URL and the header information every time, you can also use this nifty GCM Notification Test Tool

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

UPDATE: 2019-12-30

It seem that this tool is no longer working! [Request for update!]

UPDATE 2019-01-06: You can bypass X-Frame-Options in an <iframe> using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.

You can use it as follows:

  1. (Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:

    <script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
    
  2. Include the X-Frame-Bypass JS module:

    <script type="module" src="x-frame-bypass.js"></script>
    
  3. Insert the X-Frame-Bypass Custom Element:

    <iframe is="x-frame-bypass" src="https://example.org/"></iframe>
    

PG COPY error: invalid input syntax for integer

All in python (using psycopg2), create the empty table first then use copy_expert to load the csv into it. It should handle for empty values.

import psycopg2
conn = psycopg2.connect(host="hosturl", database="db_name", user="username", password="password")
cur = conn.cursor()
cur.execute("CREATE TABLE schema.destination_table ("
            "age integer, "
            "first_name varchar(20), "
            "last_name varchar(20)"
            ");")

with open(r'C:/tmp/people.csv', 'r') as f:
    next(f)  # Skip the header row. Or remove this line if csv has no header.
    conn.cursor.copy_expert("""COPY schema.destination_table FROM STDIN WITH (FORMAT CSV)""", f)

How does the stack work in assembly language?

(I've made a gist of all the code in this answer in case you want to play with it)

I have only ever did most basic things in asm during my CS101 course back in 2003. And I had never really "got it" how asm and stack work until I've realized that it's all basicaly like programming in C or C++ ... but without local variables, parameters and functions. Probably doesn't sound easy yet :) Let me show you (for x86 asm with Intel syntax).


1. What is the stack

Stack is usually a contiguous chunk of memory allocated for every thread before they start. You can store there whatever you want. In C++ terms (code snippet #1):

const int STACK_CAPACITY = 1000;
thread_local int stack[STACK_CAPACITY];

2. Stack's top and bottom

In principle, you could store values in random cells of stack array (snippet #2.1):

stack[333] = 123;
stack[517] = 456;
stack[555] = stack[333] + stack[517];

But imagine how hard would it be to remember which cells of stack are already in use and wich ones are "free". That's why we store new values on the stack next to each other.

One weird thing about (x86) asm's stack is that you add things there starting with the last index and move to lower indexes: stack[999], then stack[998] and so on (snippet #2.2):

stack[999] = 123;
stack[998] = 456;
stack[997] = stack[999] + stack[998];

And still (caution, you're gonna be confused now) the "official" name for stack[999] is bottom of the stack.
The last used cell (stack[997] in the example above) is called top of the stack (see Where the top of the stack is on x86).


3. Stack pointer (SP)

For the purpose of this discussion let's assume CPU registers are represented as global variables (see General-Purpose Registers).

int AX, BX, SP, BP, ...;
int main(){...}

There is special CPU register (SP) that tracks the top of the stack. SP is a pointer (holds a memory address like 0xAAAABBCC). But for the purposes of this post I'll use it as an array index (0, 1, 2, ...).

When a thread starts, SP == STACK_CAPACITY and then the program and OS modify it as needed. The rule is you can't write to stack cells beyond stack's top and any index less then SP is invalid and unsafe (because of system interrupts), so you first decrement SP and then write a value to the newly allocated cell.

When you want to push several values in the stack in a row, you can reserve space for all of them upfront (snippet #3):

SP -= 3;
stack[999] = 12;
stack[998] = 34;
stack[997] = stack[999] + stack[998];

Note. Now you can see why allocation on the stack is so fast - it's just a single register decrement.


4. Local variables

Let's take a look at this simplistic function (snippet #4.1):

int triple(int a) {
    int result = a * 3;
    return result;
}

and rewrite it without using of local variable (snippet #4.2):

int triple_noLocals(int a) {
    SP -= 1; // move pointer to unused cell, where we can store what we need
    stack[SP] = a * 3;
    return stack[SP];
}

and see how it is being called (snippet #4.3):

// SP == 1000
someVar = triple_noLocals(11);
// now SP == 999, but we don't need the value at stack[999] anymore
// and we will move the stack index back, so we can reuse this cell later
SP += 1; // SP == 1000 again

5. Push / pop

Addition of a new element on the top of the stack is such a frequent operation, that CPUs have a special instruction for that, push. We'll implent it like this (snippet 5.1):

void push(int value) {
    --SP;
    stack[SP] = value;
}

Likewise, taking the top element of the stack (snippet 5.2):

void pop(int& result) {
    result = stack[SP];
    ++SP; // note that `pop` decreases stack's size
}

Common usage pattern for push/pop is temporarily saving some value. Say, we have something useful in variable myVar and for some reason we need to do calculations which will overwrite it (snippet 5.3):

int myVar = ...;
push(myVar); // SP == 999
myVar += 10;
... // do something with new value in myVar
pop(myVar); // restore original value, SP == 1000

6. Function parameters

Now let's pass parameters using stack (snippet #6):

int triple_noL_noParams() { // `a` is at index 999, SP == 999
    SP -= 1; // SP == 998, stack[SP + 1] == a
    stack[SP] = stack[SP + 1] * 3;
    return stack[SP];
}

int main(){
    push(11); // SP == 999
    assert(triple(11) == triple_noL_noParams());
    SP += 2; // cleanup 1 local and 1 parameter
}

7. return statement

Let's return value in AX register (snippet #7):

void triple_noL_noP_noReturn() { // `a` at 998, SP == 998
    SP -= 1; // SP == 997

    stack[SP] = stack[SP + 1] * 3;
    AX = stack[SP];

    SP += 1; // finally we can cleanup locals right in the function body, SP == 998
}

void main(){
    ... // some code
    push(AX); // save AX in case there is something useful there, SP == 999
    push(11); // SP == 998
    triple_noL_noP_noReturn();
    assert(triple(11) == AX);
    SP += 1; // cleanup param
             // locals were cleaned up in the function body, so we don't need to do it here
    pop(AX); // restore AX
    ...
}

8. Stack base pointer (BP) (also known as frame pointer) and stack frame

Lets take more "advanced" function and rewrite it in our asm-like C++ (snippet #8.1):

int myAlgo(int a, int b) {
    int t1 = a * 3;
    int t2 = b * 3;
    return t1 - t2;
}

void myAlgo_noLPR() { // `a` at 997, `b` at 998, old AX at 999, SP == 997
    SP -= 2; // SP == 995

    stack[SP + 1] = stack[SP + 2] * 3; 
    stack[SP]     = stack[SP + 3] * 3;
    AX = stack[SP + 1] - stack[SP];

    SP += 2; // cleanup locals, SP == 997
}

int main(){
    push(AX); // SP == 999
    push(22); // SP == 998
    push(11); // SP == 997
    myAlgo_noLPR();
    assert(myAlgo(11, 22) == AX);
    SP += 2;
    pop(AX);
}

Now imagine we decided to introduce new local variable to store result there before returning, as we do in tripple (snippet #4.1). The body of the function will be (snippet #8.2):

SP -= 3; // SP == 994
stack[SP + 2] = stack[SP + 3] * 3; 
stack[SP + 1] = stack[SP + 4] * 3;
stack[SP]     = stack[SP + 2] - stack[SP + 1];
AX = stack[SP];
SP += 3;

You see, we had to update every single reference to function parameters and local variables. To avoid that, we need an anchor index, which doesn't change when the stack grows.

We will create the anchor right upon function entry (before we allocate space for locals) by saving current top (value of SP) into BP register. Snippet #8.3:

void myAlgo_noLPR_withAnchor() { // `a` at 997, `b` at 998, SP == 997
    push(BP);   // save old BP, SP == 996
    BP = SP;    // create anchor, stack[BP] == old value of BP, now BP == 996
    SP -= 2;    // SP == 994

    stack[BP - 1] = stack[BP + 1] * 3;
    stack[BP - 2] = stack[BP + 2] * 3;
    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP;    // cleanup locals, SP == 996
    pop(BP);    // SP == 997
}

The slice of stack, wich belongs to and is in full control of the function is called function's stack frame. E.g. myAlgo_noLPR_withAnchor's stack frame is stack[996 .. 994] (both idexes inclusive).
Frame starts at function's BP (after we've updated it inside function) and lasts until the next stack frame. So the parameters on the stack are part of the caller's stack frame (see note 8a).

Notes:
8a. Wikipedia says otherwise about parameters, but here I adhere to Intel software developer's manual, see vol. 1, section 6.2.4.1 Stack-Frame Base Pointer and Figure 6-2 in section 6.3.2 Far CALL and RET Operation. Function's parameters and stack frame are part of function's activation record (see The gen on function perilogues).
8b. positive offsets from BP point to function parameters and negative offsets point to local variables. That's pretty handy for debugging
8c. stack[BP] stores the address of the previous stack frame, stack[stack[BP]] stores pre-previous stack frame and so on. Following this chain, you can discover frames of all the functions in the programm, which didn't return yet. This is how debuggers show you call stack
8d. the first 3 instructions of myAlgo_noLPR_withAnchor, where we setup the frame (save old BP, update BP, reserve space for locals) are called function prologue


9. Calling conventions

In snippet 8.1 we've pushed parameters for myAlgo from right to left and returned result in AX. We could as well pass params left to right and return in BX. Or pass params in BX and CX and return in AX. Obviously, caller (main()) and called function must agree where and in which order all this stuff is stored.

Calling convention is a set of rules on how parameters are passed and result is returned.

In the code above we've used cdecl calling convention:

  • Parameters are passed on the stack, with the first argument at the lowest address on the stack at the time of the call (pushed last <...>). The caller is responsible for popping parameters back off the stack after the call.
  • the return value is placed in AX
  • EBP and ESP must be preserved by the callee (myAlgo_noLPR_withAnchor function in our case), such that the caller (main function) can rely on those registers not having been changed by a call.
  • All other registers (EAX, <...>) may be freely modified by the callee; if a caller wishes to preserve a value before and after the function call, it must save the value elsewhere (we do this with AX)

(Source: example "32-bit cdecl" from Stack Overflow Documentation; copyright 2016 by icktoofay and Peter Cordes ; licensed under CC BY-SA 3.0. An archive of the full Stack Overflow Documentation content can be found at archive.org, in which this example is indexed by topic ID 3261 and example ID 11196.)


10. Function calls

Now the most interesting part. Just like data, executable code is also stored in memory (completely unrelated to memory for stack) and every instruction has an address.
When not commanded otherwise, CPU executes instructions one after another, in the order they are stored in memory. But we can command CPU to "jump" to another location in memory and execute instructions from there on. In asm it can be any address, and in more high-level languages like C++ you can only jump to addresses marked by labels (there are workarounds but they are not pretty, to say the least).

Let's take this function (snippet #10.1):

int myAlgo_withCalls(int a, int b) {
    int t1 = triple(a);
    int t2 = triple(b);
    return t1 - t2;
}

And instead of calling tripple C++ way, do the following:

  1. copy tripple's code to the beginning of myAlgo body
  2. at myAlgo entry jump over tripple's code with goto
  3. when we need to execute tripple's code, save on the stack address of the code line just after tripple call, so we can return here later and continue execution (PUSH_ADDRESS macro below)
  4. jump to the address of the 1st line (tripple function) and execute it to the end (3. and 4. together are CALL macro)
  5. at the end of the tripple (after we've cleaned up locals), take return address from the top of the stack and jump there (RET macro)

Because there is no easy way to jump to particular code address in C++, we will use labels to mark places of jumps. I won't go into detail how macros below work, just believe me they do what I say they do (snippet #10.2):

// pushes the address of the code at label's location on the stack
// NOTE1: this gonna work only with 32-bit compiler (so that pointer is 32-bit and fits in int)
// NOTE2: __asm block is specific for Visual C++. In GCC use https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
#define PUSH_ADDRESS(labelName) {               \
    void* tmpPointer;                           \
    __asm{ mov [tmpPointer], offset labelName } \
    push(reinterpret_cast<int>(tmpPointer));    \
}

// why we need indirection, read https://stackoverflow.com/a/13301627/264047
#define TOKENPASTE(x, y) x ## y
#define TOKENPASTE2(x, y) TOKENPASTE(x, y)

// generates token (not a string) we will use as label name. 
// Example: LABEL_NAME(155) will generate token `lbl_155`
#define LABEL_NAME(num) TOKENPASTE2(lbl_, num)

#define CALL_IMPL(funcLabelName, callId)    \
    PUSH_ADDRESS(LABEL_NAME(callId));       \
    goto funcLabelName;                     \
    LABEL_NAME(callId) :

// saves return address on the stack and jumps to label `funcLabelName`
#define CALL(funcLabelName) CALL_IMPL(funcLabelName, __LINE__)

// takes address at the top of stack and jump there
#define RET() {                                         \
    int tmpInt;                                         \
    pop(tmpInt);                                        \
    void* tmpPointer = reinterpret_cast<void*>(tmpInt); \
    __asm{ jmp tmpPointer }                             \
}

void myAlgo_asm() {
    goto my_algo_start;

triple_label:
    push(BP);
    BP = SP;
    SP -= 1;

    // stack[BP] == old BP, stack[BP + 1] == return address
    stack[BP - 1] = stack[BP + 2] * 3;
    AX = stack[BP - 1];

    SP = BP;     
    pop(BP);
    RET();

my_algo_start:
    push(BP);   // SP == 995
    BP = SP;    // BP == 995; stack[BP] == old BP, 
                // stack[BP + 1] == dummy return address, 
                // `a` at [BP + 2], `b` at [BP + 3]
    SP -= 2;    // SP == 993

    push(AX);
    push(stack[BP + 2]);
    CALL(triple_label);
    stack[BP - 1] = AX;
    SP -= 1;
    pop(AX);

    push(AX);
    push(stack[BP + 3]);
    CALL(triple_label);
    stack[BP - 2] = AX;
    SP -= 1;
    pop(AX);

    AX = stack[BP - 1] - stack[BP - 2];

    SP = BP; // cleanup locals, SP == 997
    pop(BP);
}

int main() {
    push(AX);
    push(22);
    push(11);
    push(7777); // dummy value, so that offsets inside function are like we've pushed return address
    myAlgo_asm();
    assert(myAlgo_withCalls(11, 22) == AX);
    SP += 1; // pop dummy "return address"
    SP += 2;
    pop(AX);
}

Notes:
10a. because return address is stored on the stack, in principle we can change it. This is how stack smashing attack works
10b. the last 3 instructions at the "end" of triple_label (cleanup locals, restore old BP, return) are called function's epilogue


11. Assembly

Now let's look at real asm for myAlgo_withCalls. To do that in Visual Studio:

  • set build platform to x86 (not x86_64)
  • build type: Debug
  • set break point somewhere inside myAlgo_withCalls
  • run, and when execution stops at break point press Ctrl + Alt + D

One difference with our asm-like C++ is that asm's stack operate on bytes instead of ints. So to reserve space for one int, SP will be decremented by 4 bytes.
Here we go (snippet #11.1, line numbers in comments are from the gist):

;   114: int myAlgo_withCalls(int a, int b) {
 push        ebp        ; create stack frame 
 mov         ebp,esp  
; return address at (ebp + 4), `a` at (ebp + 8), `b` at (ebp + 12)
 
 sub         esp,0D8h   ; reserve space for locals. Compiler can reserve more bytes then needed. 0D8h is hexadecimal == 216 decimal 
 
 push        ebx        ; cdecl requires to save all these registers
 push        esi  
 push        edi  
 
 ; fill all the space for local variables (from (ebp-0D8h) to (ebp)) with value 0CCCCCCCCh repeated 36h times (36h * 4 == 0D8h)
 ; see https://stackoverflow.com/q/3818856/264047
 ; I guess that's for ease of debugging, so that stack is filled with recognizable values
 ; 0CCCCCCCCh in binary is 110011001100...
 lea         edi,[ebp-0D8h]     
 mov         ecx,36h    
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 
;   115:    int t1 = triple(a);
 mov         eax,dword ptr [ebp+8]   ; push parameter `a` on the stack
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4                   ; clean up param 
 mov         dword ptr [ebp-8],eax   ; copy result from eax to `t1`
 
;   116:    int t2 = triple(b);
 mov         eax,dword ptr [ebp+0Ch] ; push `b` (0Ch == 12)
 push        eax  
 
 call        triple (01A13E8h)  
 add         esp,4  
 mov         dword ptr [ebp-14h],eax ; t2 = eax
 
 mov         eax,dword ptr [ebp-8]   ; calculate and store result in eax
 sub         eax,dword ptr [ebp-14h]  

 pop         edi  ; restore registers
 pop         esi  
 pop         ebx  
 
 add         esp,0D8h  ; check we didn't mess up esp or ebp. this is only for debug builds
 cmp         ebp,esp  
 call        __RTC_CheckEsp (01A116Dh)  
 
 mov         esp,ebp  ; destroy frame
 pop         ebp  
 ret  

And asm for tripple (snippet #11.2):

 push        ebp  
 mov         ebp,esp  
 sub         esp,0CCh  
 push        ebx  
 push        esi  
 push        edi  
 lea         edi,[ebp-0CCh]  
 mov         ecx,33h  
 mov         eax,0CCCCCCCCh  
 rep stos    dword ptr es:[edi]  
 imul        eax,dword ptr [ebp+8],3  
 mov         dword ptr [ebp-8],eax  
 mov         eax,dword ptr [ebp-8]  
 pop         edi  
 pop         esi  
 pop         ebx  
 mov         esp,ebp  
 pop         ebp  
 ret  

Hope, after reading this post, assembly doesn't look as cryptic as before :)


Here are links from the post's body and some further reading:

Array Length in Java

In Java, your "actual" and "logical" size are the same. The run-time fills all array slots with default values upon allocation. So, your a contains 10.

Get file name from URL

Urls can have parameters in the end, this

 /**
 * Getting file name from url without extension
 * @param url string
 * @return file name
 */
public static String getFileName(String url) {
    String fileName;
    int slashIndex = url.lastIndexOf("/");
    int qIndex = url.lastIndexOf("?");
    if (qIndex > slashIndex) {//if has parameters
        fileName = url.substring(slashIndex + 1, qIndex);
    } else {
        fileName = url.substring(slashIndex + 1);
    }
    if (fileName.contains(".")) {
        fileName = fileName.substring(0, fileName.lastIndexOf("."));
    }

    return fileName;
}

Http Post request with content type application/x-www-form-urlencoded not working in Spring

The easiest thing to do is to set the content type of your ajax request to "application/json; charset=utf-8" and then let your API method consume JSON. Like this:

var basicInfo = JSON.stringify({
    firstName: playerProfile.firstName(),
    lastName: playerProfile.lastName(),
    gender: playerProfile.gender(),
    address: playerProfile.address(),
    country: playerProfile.country(),
    bio: playerProfile.bio()
});

$.ajax({
    url: "http://localhost:8080/social/profile/update",
    type: 'POST',
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    data: basicInfo,
    success: function(data) {
        // ...
    }
});


@RequestMapping(
    value = "/profile/update",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE,
    consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> UpdateUserProfile(
    @RequestBody User usersNewDetails,
    HttpServletRequest request,
    HttpServletResponse response
) {
    // ...
}

I guess the problem is that Spring Boot has issues submitting form data which is not JSON via ajax request.

Note: the default content type for ajax is "application/x-www-form-urlencoded".

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

getting the ng-object selected with ng-change

This is the cleanest way to get a value from an angular select options list (other than The Id or Text). Assuming you have a Product Select like this on your page :

<select ng-model="data.ProductId"
        ng-options="product.Id as product.Name for product in productsList"
        ng-change="onSelectChange()">
</select>

Then in Your Controller set the callback function like so:

    $scope.onSelectChange = function () {
        var filteredData = $scope.productsList.filter(function (response) {
            return response.Id === $scope.data.ProductId;
        })
        console.log(filteredData[0].ProductColor);
    }

Simply Explained: Since the ng-change event does not recognize the option items in the select, we are using the ngModel to filter out the selected Item from the options list loaded in the controller.

Furthermore, since the event is fired before the ngModel is really updated, you might get undesirable results, So a better way would be to add a timeout :

        $scope.onSelectChange = function () {
            $timeout(function () {
            var filteredData = $scope.productsList.filter(function (response) {
                return response.Id === $scope.data.ProductId;
            })
            console.log(filteredData[0].ProductColor);
            }, 100);
        };

Send file using POST from a Python script

Yes. You'd use the urllib2 module, and encode using the multipart/form-data content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:

user_agent = "image uploader"
default_message = "Image $current of $total"

import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re

def random_string (length):
    return ''.join (random.choice (string.letters) for ii in range (length + 1))

def encode_multipart_data (data, files):
    boundary = random_string (30)

    def get_content_type (filename):
        return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

    def encode_field (field_name):
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"' % field_name,
                '', str (data [field_name]))

    def encode_file (field_name):
        filename = files [field_name]
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
                'Content-Type: %s' % get_content_type(filename),
                '', open (filename, 'rb').read ())

    lines = []
    for name in data:
        lines.extend (encode_field (name))
    for name in files:
        lines.extend (encode_file (name))
    lines.extend (('--%s--' % boundary, ''))
    body = '\r\n'.join (lines)

    headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
               'content-length': str (len (body))}

    return body, headers

def send_post (url, data, files):
    req = urllib2.Request (url)
    connection = httplib.HTTPConnection (req.get_host ())
    connection.request ('POST', req.get_selector (),
                        *encode_multipart_data (data, files))
    response = connection.getresponse ()
    logging.debug ('response = %s', response.read ())
    logging.debug ('Code: %s %s', response.status, response.reason)

def make_upload_file (server, thread, delay = 15, message = None,
                      username = None, email = None, password = None):

    delay = max (int (delay or '0'), 15)

    def upload_file (path, current, total):
        assert isabs (path)
        assert isfile (path)

        logging.debug ('Uploading %r to %r', path, server)
        message_template = string.Template (message or default_message)

        data = {'MAX_FILE_SIZE': '3145728',
                'sub': '',
                'mode': 'regist',
                'com': message_template.safe_substitute (current = current, total = total),
                'resto': thread,
                'name': username or '',
                'email': email or '',
                'pwd': password or random_string (20),}
        files = {'upfile': path}

        send_post (server, data, files)

        logging.info ('Uploaded %r', path)
        rand_delay = random.randint (delay, delay + 5)
        logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
        time.sleep (rand_delay)

    return upload_file

def upload_directory (path, upload_file):
    assert isabs (path)
    assert isdir (path)

    matching_filenames = []
    file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

    for dirpath, dirnames, filenames in os.walk (path):
        for name in filenames:
            file_path = join (dirpath, name)
            logging.debug ('Testing file_path %r', file_path)
            if file_matcher.search (file_path):
                matching_filenames.append (file_path)
            else:
                logging.info ('Ignoring non-image file %r', path)

    total_count = len (matching_filenames)
    for index, file_path in enumerate (matching_filenames):
        upload_file (file_path, index + 1, total_count)

def run_upload (options, paths):
    upload_file = make_upload_file (**options)

    for arg in paths:
        path = abspath (arg)
        if isdir (path):
            upload_directory (path, upload_file)
        elif isfile (path):
            upload_file (path)
        else:
            logging.error ('No such path: %r' % path)

    logging.info ('Done!')

Android Google Maps API V2 Zoom to Current Location

youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 is the zoom level

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

Use this it should be helpful to you. Slightly modified xbakesx answer.

Intent intent = new Intent(this, LoginActivity.class);
if(Build.VERSION.SDK_INT >= 11) {
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
} else {
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
startActivity(intent);

How do you set autocommit in an SQL Server session?

I wanted a more permanent and quicker way. Because I tend to forget to add extra lines before writing my actual Update/Insert queries.

I did it by checking SET IMPLICIT_TRANSACTIONS check-box from Options. To navigate to Options Select Tools>Options>Query Execution>SQL Server>ANSI in your Microsoft SQL Server Management Studio.

Just make sure to execute commit or rollback after you are done executing your queries. Otherwise, the table you would have run the query will be locked for others.

How do you split a list into evenly sized chunks?

How do you split a list into evenly sized chunks?

"Evenly sized chunks", to me, implies that they are all the same length, or barring that option, at minimal variance in length. E.g. 5 baskets for 21 items could have the following results:

>>> import statistics
>>> statistics.variance([5,5,5,5,1]) 
3.2
>>> statistics.variance([5,4,4,4,4]) 
0.19999999999999998

A practical reason to prefer the latter result: if you were using these functions to distribute work, you've built-in the prospect of one likely finishing well before the others, so it would sit around doing nothing while the others continued working hard.

Critique of other answers here

When I originally wrote this answer, none of the other answers were evenly sized chunks - they all leave a runt chunk at the end, so they're not well balanced, and have a higher than necessary variance of lengths.

For example, the current top answer ends with:

[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]

Others, like list(grouper(3, range(7))), and chunk(range(7), 3) both return: [(0, 1, 2), (3, 4, 5), (6, None, None)]. The None's are just padding, and rather inelegant in my opinion. They are NOT evenly chunking the iterables.

Why can't we divide these better?

Cycle Solution

A high-level balanced solution using itertools.cycle, which is the way I might do it today. Here's the setup:

from itertools import cycle
items = range(10, 75)
number_of_baskets = 10

Now we need our lists into which to populate the elements:

baskets = [[] for _ in range(number_of_baskets)]

Finally, we zip the elements we're going to allocate together with a cycle of the baskets until we run out of elements, which, semantically, it exactly what we want:

for element, basket in zip(items, cycle(baskets)):
    basket.append(element)

Here's the result:

>>> from pprint import pprint
>>> pprint(baskets)
[[10, 20, 30, 40, 50, 60, 70],
 [11, 21, 31, 41, 51, 61, 71],
 [12, 22, 32, 42, 52, 62, 72],
 [13, 23, 33, 43, 53, 63, 73],
 [14, 24, 34, 44, 54, 64, 74],
 [15, 25, 35, 45, 55, 65],
 [16, 26, 36, 46, 56, 66],
 [17, 27, 37, 47, 57, 67],
 [18, 28, 38, 48, 58, 68],
 [19, 29, 39, 49, 59, 69]]

To productionize this solution, we write a function, and provide the type annotations:

from itertools import cycle
from typing import List, Any

def cycle_baskets(items: List[Any], maxbaskets: int) -> List[List[Any]]:
    baskets = [[] for _ in range(min(maxbaskets, len(items)))]
    for item, basket in zip(items, cycle(baskets)):
        basket.append(item)
    return baskets

In the above, we take our list of items, and the max number of baskets. We create a list of empty lists, in which to append each element, in a round-robin style.

Slices

Another elegant solution is to use slices - specifically the less-commonly used step argument to slices. i.e.:

start = 0
stop = None
step = number_of_baskets

first_basket = items[start:stop:step]

This is especially elegant in that slices don't care how long the data are - the result, our first basket, is only as long as it needs to be. We'll only need to increment the starting point for each basket.

In fact this could be a one-liner, but we'll go multiline for readability and to avoid an overlong line of code:

from typing import List, Any

def slice_baskets(items: List[Any], maxbaskets: int) -> List[List[Any]]:
    n_baskets = min(maxbaskets, len(items))
    return [items[i::n_baskets] for i in range(n_baskets)]

And islice from the itertools module will provide a lazily iterating approach, like that which was originally asked for in the question.

I don't expect most use-cases to benefit very much, as the original data is already fully materialized in a list, but for large datasets, it could save nearly half the memory usage.

from itertools import islice
from typing import List, Any, Generator
    
def yield_islice_baskets(items: List[Any], maxbaskets: int) -> Generator[List[Any], None, None]:
    n_baskets = min(maxbaskets, len(items))
    for i in range(n_baskets):
        yield islice(items, i, None, n_baskets)

View results with:

from pprint import pprint

items = list(range(10, 75))
pprint(cycle_baskets(items, 10))
pprint(slice_baskets(items, 10))
pprint([list(s) for s in yield_islice_baskets(items, 10)])

Updated prior solutions

Here's another balanced solution, adapted from a function I've used in production in the past, that uses the modulo operator:

def baskets_from(items, maxbaskets=25):
    baskets = [[] for _ in range(maxbaskets)]
    for i, item in enumerate(items):
        baskets[i % maxbaskets].append(item)
    return filter(None, baskets) 

And I created a generator that does the same if you put it into a list:

def iter_baskets_from(items, maxbaskets=3):
    '''generates evenly balanced baskets from indexable iterable'''
    item_count = len(items)
    baskets = min(item_count, maxbaskets)
    for x_i in range(baskets):
        yield [items[y_i] for y_i in range(x_i, item_count, baskets)]
    

And finally, since I see that all of the above functions return elements in a contiguous order (as they were given):

def iter_baskets_contiguous(items, maxbaskets=3, item_count=None):
    '''
    generates balanced baskets from iterable, contiguous contents
    provide item_count if providing a iterator that doesn't support len()
    '''
    item_count = item_count or len(items)
    baskets = min(item_count, maxbaskets)
    items = iter(items)
    floor = item_count // baskets 
    ceiling = floor + 1
    stepdown = item_count % baskets
    for x_i in range(baskets):
        length = ceiling if x_i < stepdown else floor
        yield [items.next() for _ in range(length)]

Output

To test them out:

print(baskets_from(range(6), 8))
print(list(iter_baskets_from(range(6), 8)))
print(list(iter_baskets_contiguous(range(6), 8)))
print(baskets_from(range(22), 8))
print(list(iter_baskets_from(range(22), 8)))
print(list(iter_baskets_contiguous(range(22), 8)))
print(baskets_from('ABCDEFG', 3))
print(list(iter_baskets_from('ABCDEFG', 3)))
print(list(iter_baskets_contiguous('ABCDEFG', 3)))
print(baskets_from(range(26), 5))
print(list(iter_baskets_from(range(26), 5)))
print(list(iter_baskets_contiguous(range(26), 5)))

Which prints out:

[[0], [1], [2], [3], [4], [5]]
[[0], [1], [2], [3], [4], [5]]
[[0], [1], [2], [3], [4], [5]]
[[0, 8, 16], [1, 9, 17], [2, 10, 18], [3, 11, 19], [4, 12, 20], [5, 13, 21], [6, 14], [7, 15]]
[[0, 8, 16], [1, 9, 17], [2, 10, 18], [3, 11, 19], [4, 12, 20], [5, 13, 21], [6, 14], [7, 15]]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19], [20, 21]]
[['A', 'D', 'G'], ['B', 'E'], ['C', 'F']]
[['A', 'D', 'G'], ['B', 'E'], ['C', 'F']]
[['A', 'B', 'C'], ['D', 'E'], ['F', 'G']]
[[0, 5, 10, 15, 20, 25], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]]
[[0, 5, 10, 15, 20, 25], [1, 6, 11, 16, 21], [2, 7, 12, 17, 22], [3, 8, 13, 18, 23], [4, 9, 14, 19, 24]]
[[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]

Notice that the contiguous generator provide chunks in the same length patterns as the other two, but the items are all in order, and they are as evenly divided as one may divide a list of discrete elements.

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

How do I change a TCP socket to be non-blocking?

The best method for setting a socket as non-blocking in C is to use ioctl. An example where an accepted socket is set to non-blocking is following:

long on = 1L;
unsigned int len;
struct sockaddr_storage remoteAddress;
len = sizeof(remoteAddress);
int socket = accept(listenSocket, (struct sockaddr *)&remoteAddress, &len)
if (ioctl(socket, (int)FIONBIO, (char *)&on))
{
    printf("ioctl FIONBIO call failed\n");
}

How to add images in select list?

With countries, languages or currency you may use emojis.

Works with pretty much every browser/OS that supports the use of emojis.

_x000D_
_x000D_
select {_x000D_
 height: 50px;_x000D_
 line-height: 50px;_x000D_
 font-size: 12pt;_x000D_
}
_x000D_
<select name="countries">_x000D_
    <option value="NL">&emsp;Netherlands</option>_x000D_
    <option value="DE">&emsp;Germany</option>_x000D_
    <option value="FR">&emsp;France</option>_x000D_
    <option value="ES">&emsp;Spain</option>_x000D_
</select>_x000D_
_x000D_
<br /><br />_x000D_
_x000D_
<select name="currency">_x000D_
    <option value="EUR">&emsp;€&emsp;EUR&emsp;</option>_x000D_
    <option value="GBP">&emsp;£&emsp;GBP&emsp;</option>_x000D_
    <option value="USD">&emsp;$&emsp;USD&emsp;</option>_x000D_
    <option value="YEN">&emsp;¥&emsp;YEN&emsp;</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

Encrypt Password in Configuration Files?

See what is available in Jetty for storing password (or hashes) in configuration files, and consider if the OBF encoding might be useful for you. Then see in the source how it is done.

http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html

How can I create a dynamically sized array of structs?

In C++, use a vector. It's like an array but you can easily add and remove elements and it will take care of allocating and deallocating memory for you.

I know the title of the question says C, but you tagged your question with C and C++...

Checking from shell script if a directory contains files

Take care with directories with a lot of files! It could take a some time to evaluate the ls command.

IMO the best solution is the one that uses

find /some/dir/ -maxdepth 0 -empty

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.

More information on the answer can be found here

Linked Info Summary

Enable TLS 1.2 at the system (SCHANNEL) level:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001

(equivalent keys are probably also available for other TLS versions)

Tell .NET Framework to use the system TLS versions:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001

This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.

Why do people say that Ruby is slow?

Joel on Software - Ruby Performance Revisited quite well explains it. Might be outdated though...

I would recommend to just stick with it as you're used to Ruby on Rails,
if you ever meet a performance issue you might reconsider to use a different language and framework.

In that case I would really suggest C# with ASP.NET MVC 2, works very well for CRUD apps.

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

REST Over HTTPS Should be a secure method as long as API provider implements authorization a server end. In a case of web application as well what we do is accessing a web application via HTTPS and some authentication/authorization, traditionally web applications did not have security issues then Restful API would also counter security issues without problem !

Remove insignificant trailing zeros from a number?

After reading all of the answers - and comments - I ended up with this:

function isFloat(n) {
    let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n)) : n;
    return number;
}

I know using eval can be harmful somehow but this helped me a lot.

So:

isFloat(1.234000);     // = 1.234;
isFloat(1.234001);     // = 1.234001
isFloat(1.2340010000); // = 1.234001

If you want to limit the decimal places, use toFixed() as others pointed out.

let number = (Number(n) === n && n % 1 !== 0) ? eval(parseFloat(n).toFixed(3)) : n;

That's it.

SQL Server: use CASE with LIKE

SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname, 
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname

How to encode a URL in Swift

Adding to Bryan Chen's answer above:

Just incase anyone else is getting something similar with Alamofire:

error: Alamofire was compiled with optimization - stepping may behave oddly; variables may not be available.

It's not a very descriptive error. I was getting that error when constructing a URL for google geo services. I was appending a street address to the end of the URL WITHOUT encoding the street address itself first. I was able to fix it using Bryan Chen's solution:

var streetAdress = "123 fake street, new york, ny"
var escapedStreetAddress = streetAddress.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
let url = "\(self.baseUrl)&address=\(escapedAddress!)"

That fixed it for me! It didnt like that the address had spaces and commas, etc.

Hope this helps someone else!

Getting value from a cell from a gridview on RowDataBound event

Just use a loop to check your cell in a gridview for example:

for (int i = 0; i < GridView2.Rows.Count; i++)
{
    string vr;
    vr = GridView2.Rows[i].Cells[4].Text; // here you go vr = the value of the cel
    if (vr  == "0") // you can check for anything
    {
        GridView2.Rows[i].Cells[4].Text = "Done";
        // you can format this cell 
    }
}

Angular 5 - Copy to clipboard

I know this has already been highly voted in here by now, but I'd rather go for a custom directive approach and rely on the ClipboardEvent as @jockeisorby suggested, while also making sure the listener is correctly removed (same function needs to be provided for both the add and remove event listeners)

stackblitz demo

import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";

@Directive({ selector: '[copy-clipboard]' })
export class CopyClipboardDirective {

  @Input("copy-clipboard")
  public payload: string;

  @Output("copied")
  public copied: EventEmitter<string> = new EventEmitter<string>();

  @HostListener("click", ["$event"])
  public onClick(event: MouseEvent): void {

    event.preventDefault();
    if (!this.payload)
      return;

    let listener = (e: ClipboardEvent) => {
      let clipboard = e.clipboardData || window["clipboardData"];
      clipboard.setData("text", this.payload.toString());
      e.preventDefault();

      this.copied.emit(this.payload);
    };

    document.addEventListener("copy", listener, false)
    document.execCommand("copy");
    document.removeEventListener("copy", listener, false);
  }
}

and then use it as such

<a role="button" [copy-clipboard]="'some stuff'" (copied)="notify($event)">
  <i class="fa fa-clipboard"></i>
  Copy
</a>

public notify(payload: string) {
   // Might want to notify the user that something has been pushed to the clipboard
   console.info(`'${payload}' has been copied to clipboard`);
}

Note: notice the window["clipboardData"] is needed for IE as it does not understand e.clipboardData

Unit testing click event in Angular

Events can be tested using the async/fakeAsync functions provided by '@angular/core/testing', since any event in the browser is asynchronous and pushed to the event loop/queue.

Below is a very basic example to test the click event using fakeAsync.

The fakeAsync function enables a linear coding style by running the test body in a special fakeAsync test zone.

Here I am testing a method that is invoked by the click event.

it('should', fakeAsync( () => {
    fixture.detectChanges();
    spyOn(componentInstance, 'method name'); //method attached to the click.
    let btn = fixture.debugElement.query(By.css('button'));
    btn.triggerEventHandler('click', null);
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(componentInstance.methodName).toHaveBeenCalled();
}));

Below is what Angular docs have to say:

The principle advantage of fakeAsync over async is that the test appears to be synchronous. There is no then(...) to disrupt the visible flow of control. The promise-returning fixture.whenStable is gone, replaced by tick()

There are limitations. For example, you cannot make an XHR call from within a fakeAsync

How to launch jQuery Fancybox on page load?

why isn't this one of the answers yet?:

$("#manual2").click(function() {
    $.fancybox([
        'http://farm5.static.flickr.com/4044/4286199901_33844563eb.jpg',
        'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
        {
            'href'  : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
            'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
        }
    ], {
        'padding'           : 0,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        'type'              : 'image',
        'changeFade'        : 0
    });
});

now just trigger your link!!

got this from the Fancybox homepage

null terminating a string

From the comp.lang.c FAQ: http://c-faq.com/null/varieties.html

In essence: NULL (the preprocessor macro for the null pointer) is not the same as NUL (the null character).

Changing image size in Markdown

The sheer <img ... width="50%"> said above, did work on my Github Readme.md document.

However my real issue was, that the image was inside a table cell, just compressing the text in the beside cell. So the other way was to set columns width in Markdown tables, but the solutions did not really seem enough markdownish for my morning.

At last I solved both problems by simply forcing the beside text cell with as much "& nbsp;" as I needed.

I hope this helps. Bye and thanks everybody.

What is the use of ObservableCollection in .net?

From Pro C# 5.0 and the .NET 4.5 Framework

The ObservableCollection<T> class is very useful in that it has the ability to inform external objects when its contents have changed in some way (as you might guess, working with ReadOnlyObservableCollection<T> is very similar, but read-only in nature). In many ways, working with the ObservableCollection<T> is identical to working with List<T>, given that both of these classes implement the same core interfaces. What makes the ObservableCollection<T> class unique is that this class supports an event named CollectionChanged. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified. Like any event, CollectionChanged is defined in terms of a delegate, which in this case is NotifyCollectionChangedEventHandler. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs as the second. Consider the following Main() method, which populates an observable collection containing Person objects and wires up the CollectionChanged event:

class Program
{
   static void Main(string[] args)
   {
     // Make a collection to observe and add a few Person objects.
     ObservableCollection<Person> people = new ObservableCollection<Person>()
     {
        new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
        new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
     };
     // Wire up the CollectionChanged event.
     people.CollectionChanged += people_CollectionChanged;
     // Now add a new item.
     people.Add(new Person("Fred", "Smith", 32));

     // Remove an item.
     people.RemoveAt(0);

     Console.ReadLine();
   }
   static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
   {
       // What was the action that caused the event?
        Console.WriteLine("Action for this event: {0}", e.Action);

        // They removed something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
        {
            Console.WriteLine("Here are the OLD items:");
            foreach (Person p in e.OldItems)
            {
                Console.WriteLine(p.ToString());
            }
            Console.WriteLine();
        }

        // They added something. 
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            // Now show the NEW items that were inserted.
            Console.WriteLine("Here are the NEW items:");
            foreach (Person p in e.NewItems)
            {
                Console.WriteLine(p.ToString());
            }
        }
   }
}

The incoming NotifyCollectionChangedEventArgs parameter defines two important properties, OldItems and NewItems, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when items are added, removed, relocated, or reset. To discover which of these actions triggered the event, you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be tested against any of the following members of the NotifyCollectionChangedAction enumeration:

public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}

Members of System.Collections.ObjectModel

how to destroy bootstrap modal window completely?

$('#myModal').on('hidden.bs.modal', function () {
      $(this).data('bs.modal', null).remove();
});

//Just add .remove(); 
//Bootstrap v3.0.3

Batch script to find and replace a string in text file within a minute for files up to 12 MB

Give this a shot:

@echo off
setlocal

call :FindReplace "findstr" "replacestr" input.txt

exit /b 

:FindReplace <findstr> <replstr> <file>
set tmp="%temp%\tmp.txt"
If not exist %temp%\_.vbs call :MakeReplace
for /f "tokens=*" %%a in ('dir "%3" /s /b /a-d /on') do (
  for /f "usebackq" %%b in (`Findstr /mic:"%~1" "%%a"`) do (
    echo(&Echo Replacing "%~1" with "%~2" in file %%~nxa
    <%%a cscript //nologo %temp%\_.vbs "%~1" "%~2">%tmp%
    if exist %tmp% move /Y %tmp% "%%~dpnxa">nul
  )
)
del %temp%\_.vbs
exit /b

:MakeReplace
>%temp%\_.vbs echo with Wscript
>>%temp%\_.vbs echo set args=.arguments
>>%temp%\_.vbs echo .StdOut.Write _
>>%temp%\_.vbs echo Replace(.StdIn.ReadAll,args(0),args(1),1,-1,1)
>>%temp%\_.vbs echo end with

Retrieve CPU usage and memory usage of a single process on Linux?

ps command (should not use):

top command (should use):

Use top to get CPU usage in real time(current short interval):

top -b -n 2 -d 0.2 -p 6962 | tail -1 | awk '{print $9}'

will echo like: 78.6

Append an int to a std::string

You are casting ClientID to char* causing the function to assume its a null terinated char array, which it is not.

from cplusplus.com :

string& append ( const char * s ); Appends a copy of the string formed by the null-terminated character sequence (C string) pointed by s. The length of this character sequence is determined by the first ocurrence of a null character (as determined by traits.length(s)).

Finding median of list in Python

def midme(list1):

    list1.sort()
    if len(list1)%2>0:
            x = list1[int((len(list1)/2))]
    else:
            x = ((list1[int((len(list1)/2))-1])+(list1[int(((len(list1)/2)))]))/2
    return x


midme([4,5,1,7,2])

Pyinstaller setting icons don't change

I know this is old and whatnot (and not exactly sure if it's a question), but after searching, I had success with this command for --onefile:

pyinstaller.exe --onefile --windowed --icon=app.ico app.py

Google led me to this page while I was searching for an answer on how to set an icon for my .exe, so maybe it will help someone else.

The information here was found at this site: https://mborgerson.com/creating-an-executable-from-a-python-script

Decorators with parameters?

In case both the function and the decorator have to take arguments you can follow the below approach.

For example there is a decorator named decorator1 which takes an argument

@decorator1(5)
def func1(arg1, arg2):
    print (arg1, arg2)

func1(1, 2)

Now if the decorator1 argument has to be dynamic, or passed while calling the function,

def func1(arg1, arg2):
    print (arg1, arg2)


a = 1
b = 2
seconds = 10

decorator1(seconds)(func1)(a, b)

In the above code

  • seconds is the argument for decorator1
  • a, b are the arguments of func1

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Here is another way to reproduce this error in Python2.7 with numpy:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate(a,b)   #note the lack of tuple format for a and b
print(c) 

The np.concatenate method produces an error:

TypeError: only length-1 arrays can be converted to Python scalars

If you read the documentation around numpy.concatenate, then you see it expects a tuple of numpy array objects. So surrounding the variables with parens fixed it:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.concatenate((a,b))  #surround a and b with parens, packaging them as a tuple
print(c) 

Then it prints:

[1 2 3 4 5 6]

What's going on here?

That error is a case of bubble-up implementation - it is caused by duck-typing philosophy of python. This is a cryptic low-level error python guts puke up when it receives some unexpected variable types, tries to run off and do something, gets part way through, the pukes, attempts remedial action, fails, then tells you that "you can't reformulate the subspace responders when the wind blows from the east on Tuesday".

In more sensible languages like C++ or Java, it would have told you: "you can't use a TypeA where TypeB was expected". But Python does it's best to soldier on, does something undefined, fails, and then hands you back an unhelpful error. The fact we have to be discussing this is one of the reasons I don't like Python, or its duck-typing philosophy.

How to determine if object is in array

Use something like this:

function containsObject(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i] === obj) {
            return true;
        }
    }

    return false;
}

In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
    var x;
    for (x in list) {
        if (list.hasOwnProperty(x) && list[x] === obj) {
            return true;
        }
    }

    return false;
}

This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

How does strcmp() work?

This is how I implemented my strcmp: it works like this: it compares first letter of the two strings, if it is identical, it continues to the next letter. If not, it returns the corresponding value. It is very simple and easy to understand: #include

//function declaration:
int strcmp(char string1[], char string2[]);

int main()
{
    char string1[]=" The San Antonio spurs";
    char string2[]=" will be champins again!";
    //calling the function- strcmp
    printf("\n number returned by the strcmp function: %d", strcmp(string1, string2));
    getch();
    return(0);
}

/**This function calculates the dictionary value of the string and compares it to another string.
it returns a number bigger than 0 if the first string is bigger than the second
it returns a number smaller than 0 if the second string is bigger than the first
input: string1, string2
output: value- can be 1, 0 or -1 according to the case*/
int strcmp(char string1[], char string2[])
{
    int i=0;
    int value=2;    //this initialization value could be any number but the numbers that can be      returned by the function
    while(value==2)
    {
        if (string1[i]>string2[i])
        {
            value=1;
        }
        else if (string1[i]<string2[i])
        {
            value=-1;
        }
        else
        {
            i++;
        }
    }
    return(value);
}

Wildcards in jQuery selectors

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

Padding is invalid and cannot be removed?

Make sure that the keys you use to encrypt and decrypt are the same. The padding method even if not explicitly set should still allow for proper decryption/encryption (if not set they will be the same). However if you for some reason are using a different set of keys for decryption than used for encryption you will get this error:

Padding is invalid and cannot be removed

If you are using some algorithm to dynamically generate keys that will not work. They need to be the same for both encryption and decryption. One common way is to have the caller provide the keys in the constructor of the encryption methods class, to prevent the encryption/decryption process having any hand in creation of these items. It focuses on the task at hand (encrypting and decrypting data) and requires the iv and key to be supplied by the caller.

How to redirect output of systemd service to a file

Assume logs are already put to stdout/stderr, and have systemd unit's log in /var/log/syslog

journalctl -u unitxxx.service

Jun 30 13:51:46 host unitxxx[1437]: time="2018-06-30T11:51:46Z" level=info msg="127.0.0.1
Jun 30 15:02:15 host unitxxx[1437]: time="2018-06-30T13:02:15Z" level=info msg="127.0.0.1
Jun 30 15:33:02 host unitxxx[1437]: time="2018-06-30T13:33:02Z" level=info msg="127.0.0.1
Jun 30 15:56:31 host unitxxx[1437]: time="2018-06-30T13:56:31Z" level=info msg="127.0.0.1

Config rsyslog (System Logging Service)

# Create directory for log file
mkdir /var/log/unitxxx

# Then add config file /etc/rsyslog.d/unitxxx.conf

if $programname == 'unitxxx' then /var/log/unitxxx/unitxxx.log
& stop

Restart rsyslog

systemctl restart rsyslog.service

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

I know this is old but this answer still applies to newer Core releases.

If by chance your DbContext implementation is in a different project than your startup project and you run ef migrations, you'll see this error because the command will not be able to invoke the application's startup code leaving your database provider without a configuration. To fix it, you have to let ef migrations know where they're at.

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

Both -s and -p are optionals that default to the current folder.

PHP header redirect 301 - what are the implications?

Make sure you die() after your redirection, and make sure you do your redirect AS SOON AS POSSIBLE while your script executes. It makes sure that no more database queries (if some) are not wasted for nothing. That's the one tip I can give you

For search engines, 301 is the best response code

What are the best JVM settings for Eclipse?

Here's what I use (though I have them in the shortcut instead of the settings file):

eclipse.exe -showlocation -vm "C:\Java\jdk1.6.0_07\bin\javaw.exe" -vmargs -Xms256M -Xmx768M -XX:+UseParallelGC -XX:MaxPermSize=128M

Kill some processes by .exe file name

public void EndTask(string taskname)
{
      string processName = taskname.Replace(".exe", "");

      foreach (Process process in Process.GetProcessesByName(processName))
      {
          process.Kill();
      }
}

//EndTask("notepad");

Summary: no matter if the name contains .exe, the process will end. You don't need to "leave off .exe from process name", It works 100%.

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Convert a Unicode string to an escaped ASCII string

This goes back and forth to and from the \uXXXX format.

class Program {
    static void Main( string[] args ) {
        string unicodeString = "This function contains a unicode character pi (\u03a0)";

        Console.WriteLine( unicodeString );

        string encoded = EncodeNonAsciiCharacters(unicodeString);
        Console.WriteLine( encoded );

        string decoded = DecodeEncodedNonAsciiCharacters( encoded );
        Console.WriteLine( decoded );
    }

    static string EncodeNonAsciiCharacters( string value ) {
        StringBuilder sb = new StringBuilder();
        foreach( char c in value ) {
            if( c > 127 ) {
                // This character is too big for ASCII
                string encodedValue = "\\u" + ((int) c).ToString( "x4" );
                sb.Append( encodedValue );
            }
            else {
                sb.Append( c );
            }
        }
        return sb.ToString();
    }

    static string DecodeEncodedNonAsciiCharacters( string value ) {
        return Regex.Replace(
            value,
            @"\\u(?<Value>[a-zA-Z0-9]{4})",
            m => {
                return ((char) int.Parse( m.Groups["Value"].Value, NumberStyles.HexNumber )).ToString();
            } );
    }
}

Outputs:

This function contains a unicode character pi (p)

This function contains a unicode character pi (\u03a0)

This function contains a unicode character pi (p)

Formatting numbers (decimal places, thousands separators, etc) with CSS

If it helps...

I use the PHP function number_format() and the Narrow No-break Space (&#8239;). It is often used as an unambiguous thousands separator.

echo number_format(200000, 0, "", "&#8239;");

Because IE8 has some problems to render the Narrow No-break Space, I changed it for a SPAN

echo "<span class='number'>".number_format(200000, 0, "", "<span></span>")."</span>";
.number SPAN{
    padding: 0 1px; 
}

Uninstalling an MSI file from the command line without using msiexec

I would try the following syntax - it works for me.

msiexec /x filename.msi /q 

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.


Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

In [1]: class HeavyDuty(object):
   ...:     def __init__(self):
   ...:         import time
   ...:         time.sleep(2)  # <- Spends a lot of time here
   ...:     
   ...:     def do_work(self, arg1, arg2):
   ...:         print("Called with %r and %r" % (arg1, arg2))
   ...:  

here is some code that uses two instances of the HeavyDuty class:

In [2]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(13, 17)
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(23, 29)
   ...:    


Now, here is a test case for the heavy_work function:

In [3]: from unittest.mock import patch, call
   ...: def test_heavy_work():
   ...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
   ...:     
   ...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
   ...:         heavy_work()
   ...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)
   ...:  

We are mocking the HeavyDuty class with MockHeavyDuty. To assert method calls coming from every HeavyDuty instance we have to refer to MockHeavyDuty.return_value.assert_has_calls, instead of MockHeavyDuty.assert_has_calls. In addition, in the list of expected_calls we have to specify which method name we are interested in asserting calls for. So our list is made of calls to call.do_work, as opposed to simply call.

Exercising the test case shows us it is successful:

In [4]: print(test_heavy_work())
None


If we modify the heavy_work function, the test fails and produces a helpful error message:

In [5]: def heavy_work():
   ...:     hd1 = HeavyDuty()
   ...:     hd1.do_work(113, 117)  # <- call args are different
   ...:     hd2 = HeavyDuty()
   ...:     hd2.do_work(123, 129)  # <- call args are different
   ...:     

In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)

AssertionError: Calls not found.
Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]


Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

In [7]: def work_function(arg1, arg2):
   ...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
   ...: def test_work_function():
   ...:     expected_calls = [call(13, 17), call(23, 29)]    
   ...:     with patch('__main__.work_function') as mock_work_function:
   ...:         work_function(13, 17)
   ...:         work_function(23, 29)
   ...:         mock_work_function.assert_has_calls(expected_calls)
   ...:    

In [9]: print(test_work_function())
None


There are two main differences. The first one is that when mocking a function we setup our expected calls using call, instead of using call.some_method. The second one is that we call assert_has_calls on mock_work_function, instead of on mock_work_function.return_value.

How do I return clean JSON from a WCF Service?

This is accomplished in web.config for your webservice. Set the bindingBehavior to <webHttp> and you will see the clean JSON. The extra "[d]" is set by the default behavior which you need to overwrite.

See in addition this blogpost: http://blog.clauskonrad.net/2010/11/how-to-expose-json-endpoint-from-wcf.html

json_encode is returning NULL?

few day ago I have the SAME problem with 1 table.

Firstly try:

echo json_encode($rows);
echo json_last_error();  // returns 5 ?

If last line returns 5, problem is with your data. I know, your tables are in UTF-8, but not entered data. For example the input was in txt file, but created on Win machine with stupid encoding (in my case Win-1250 = CP1250) and this data has been entered into the DB.

Solution? Look for new data (excel, web page), edit source txt file via PSPad (or whatever else), change encoding to UTF-8, delete all rows and now put data from original. Save. Enter into DB.

You can also only change encoding to utf-8 and then change all rows manually (give cols with special chars - desc, ...). Good for slaves...

ng-model for `<input type="file"/>` (with directive DEMO)

This is an addendum to @endy-tjahjono's solution.

I ended up not being able to get the value of uploadme from the scope. Even though uploadme in the HTML was visibly updated by the directive, I could still not access its value by $scope.uploadme. I was able to set its value from the scope, though. Mysterious, right..?

As it turned out, a child scope was created by the directive, and the child scope had its own uploadme.

The solution was to use an object rather than a primitive to hold the value of uploadme.

In the controller I have:

$scope.uploadme = {};
$scope.uploadme.src = "";

and in the HTML:

 <input type="file" fileread="uploadme.src"/>
 <input type="text" ng-model="uploadme.src"/>

There are no changes to the directive.

Now, it all works like expected. I can grab the value of uploadme.src from my controller using $scope.uploadme.

Javascript : array.length returns undefined

Objects don't have a .length property.

A simple solution if you know you don't have to worry about hasOwnProperty checks, would be to do this:

Object.keys(data).length;

If you have to support IE 8 or lower, you'll have to use a loop, instead:

var length= 0;
for(var key in data) {
    if(data.hasOwnProperty(key)){
        length++;
    }
}

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

Why do people hate SQL cursors so much?

Cursors tend to be used by beginning SQL developers in places where set-based operations would be better. Particularly when people learn SQL after learning a traditional programming language, the "iterate over these records" mentality tends to lead people to use cursors inappropriately.

Most serious SQL books include a chapter enjoining the use of cursors; well-written ones make it clear that cursors have their place but shouldn't be used for set-based operations.

There are obviously situations where cursors are the correct choice, or at least A correct choice.

How to commit to remote git repository

All You have to do is git push origin master, where origin is the default name (alias) of Your remote repository and master is the remote branch You want to push Your changes to.

You may also want to check these out:

  1. http://gitimmersion.com/
  2. http://progit.org/book/

Unzipping files in Python

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!

Single selection in RecyclerView

This is how the Adapter class looks like :

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewHolder>{

Context context;
ArrayList<RouteDetailsFromFirestore> routeDetailsFromFirestoreArrayList_;
public int  lastSelectedPosition=-1;


public MyRecyclerViewAdapter(Context context, ArrayList<RouteDetailsFromFirestore> routeDetailsFromFirestoreArrayList)
{
    this.context = context;
    this.routeDetailsFromFirestoreArrayList_ = routeDetailsFromFirestoreArrayList;
}

@NonNull
@Override
public MyRecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
{
    // LayoutInflater layoutInflater = LayoutInflater.from(mainActivity_.getBaseContext());
    LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
    View view = layoutInflater.inflate(R.layout.route_details, viewGroup, false);
    return new MyRecyclerViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final MyRecyclerViewHolder myRecyclerViewHolder, final int i) {

    /* This is the part where the appropriate checking and unchecking of radio button happens appropriately */
    myRecyclerViewHolder.mRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b) {
                if (lastSelectedPosition != -1) {
     /* Getting the reference to the previously checked radio button and then unchecking it.lastSelectedPosition has the index of the previously selected radioButton */  
                    //RadioButton rb = (RadioButton) ((MainActivity) context).linearLayoutManager.getChildAt(lastSelectedPosition).findViewById(R.id.rbRadioButton);
                    RadioButton rb = (RadioButton) ((MainActivity) myRecyclerViewHolder.mRadioButton.getContext()).linearLayoutManager.getChildAt(lastSelectedPosition).findViewById(R.id.rbRadioButton);
                    rb.setChecked(false);
                }
                    lastSelectedPosition = i;
                    /* Checking the currently selected radio button */
                    myRecyclerViewHolder.mRadioButton.setChecked(true);
                }
        }
    });
}

@Override
public int getItemCount() {
    return routeDetailsFromFirestoreArrayList_.size();
}
} // End of Adapter Class

Inside MainActivity.java we call the ctor of Adapter class like this. The context passed is of MainActivity to the Adapter ctor :

myRecyclerViewAdapter = new MyRecyclerViewAdapter(MainActivity.this, routeDetailsList);

Parse date without timezone javascript

The Date object itself will contain timezone anyway, and the returned result is the effect of converting it to string in a default way. I.e. you cannot create a date object without timezone. But what you can do is mimic the behavior of Date object by creating your own one. This is, however, better to be handed over to libraries like moment.js.

How to send image to PHP file using Ajax?

Here is code that will upload multiple images at once, into a specific folder!

The HTML:

<form method="post" enctype="multipart/form-data" id="image_upload_form" action="submit_image.php">
<input type="file" name="images" id="images" multiple accept="image/x-png, image/gif, image/jpeg, image/jpg" />
<button type="submit" id="btn">Upload Files!</button>
</form>
<div id="response"></div>
<ul id="image-list">

</ul>

The PHP:

<?php
$errors = $_FILES["images"]["error"];
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
    $name = $_FILES["images"]["name"][$key];
    //$ext = pathinfo($name, PATHINFO_EXTENSION);
    $name = explode("_", $name);
    $imagename='';
    foreach($name as $letter){
        $imagename .= $letter;
    }

    move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "images/uploads/" .  $imagename);

}
}


echo "<h2>Successfully Uploaded Images</h2>";

And finally, the JavaSCript/Ajax:

(function () {
var input = document.getElementById("images"), 
    formdata = false;

function showUploadedItem (source) {
    var list = document.getElementById("image-list"),
        li   = document.createElement("li"),
        img  = document.createElement("img");
    img.src = source;
    li.appendChild(img);
    list.appendChild(li);
}   

if (window.FormData) {
    formdata = new FormData();
    document.getElementById("btn").style.display = "none";
}

input.addEventListener("change", function (evt) {
    document.getElementById("response").innerHTML = "Uploading . . ."
    var i = 0, len = this.files.length, img, reader, file;

    for ( ; i < len; i++ ) {
        file = this.files[i];

        if (!!file.type.match(/image.*/)) {
            if ( window.FileReader ) {
                reader = new FileReader();
                reader.onloadend = function (e) { 
                    showUploadedItem(e.target.result, file.fileName);
                };
                reader.readAsDataURL(file);
            }
            if (formdata) {
                formdata.append("images[]", file);
            }
        }   
    }

    if (formdata) {
        $.ajax({
            url: "submit_image.php",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function (res) {
                document.getElementById("response").innerHTML = res;
            }
        });
    }
}, false);
}());

Hope this helps

Creating a segue programmatically

For controllers that are in the storyboard.

jhilgert00 is this what you were looking for?

-(IBAction)nav_goHome:(id)sender {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];

}

OR...

[self performSegueWithIdentifier:@"loginMainSegue" sender:self];

Function is not defined - uncaught referenceerror

You must write that function body outside the ready();

because ready is used to call a function or to bind a function with binding id like this.

$(document).ready(function() {
    $("Some id/class name").click(function(){
        alert("i'm in");
    });
});

but you can't do this if you are calling "showAmount" function onchange/onclick event

$(document).ready(function() {
    function showAmount(value){
        alert(value);
    }

});

You have to write "showAmount" outside the ready();

function showAmount(value){
    alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
    alert("will display on page load")
});

UTF-8 all the way through

The top answer is excellent. Here is what I had to on a regular debian/php/mysql setup:

// storage
// debian. apparently already utf-8

// retrieval
// the mysql database was stored in utf-8, 
// but apparently php was requesting iso. this worked: 
// ***notice "utf8", without dash, this is a mysql encoding***
mysql_set_charset('utf8');

// delivery
// php.ini did not have a default charset, 
// (it was commented out, shared host) and
// no http encoding was specified in the apache headers.
// this made apache send out a utf-8 header
// (and perhaps made php actually send out utf-8)
// ***notice "utf-8", with dash, this is a php encoding***
ini_set('default_charset','utf-8');

// submission
// this worked in all major browsers once apache
// was sending out the utf-8 header. i didnt add
// the accept-charset attribute.

// processing
// changed a few commands in php, like substr,
// to mb_substr

that was all !

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

CSS selector (id contains part of text)

<div id='element_123_wrapper_text'>My sample DIV</div>

The Operator ^ - Match elements that starts with given value

div[id^="element_123"] {

}

The Operator $ - Match elements that ends with given value

div[id$="wrapper_text"] {

}

The Operator * - Match elements that have an attribute containing a given value

div[id*="wrapper_text"] {

}

Where are Docker images stored on the host machine?

Use docker info command to display system-wide information and the location may vary.

Depending on the storage driver in use, additional information can be shown, such as pool name, data file, metadata file, data space used, total data space, metadata space used, and total metadata space.

The data file is where the images are stored and the metadata file is where the meta data regarding those images are stored. When run for the first time Docker allocates a certain amount of data space and meta data space from the space available on the volume where /var/lib/docker is mounted.

Here is the example on Ubuntu (check Root Dir):

$ docker info
...
Server Version: 18.06.1-ce
Storage Driver: aufs
 Root Dir: /var/snap/docker/common/var-lib-docker/aufs
...
Docker Root Dir: /var/snap/docker/common/var-lib-docker
...

And here is the example on Travis CI (see Docker Root Dir):

$ docker info
Server Version: 17.09.0-ce
Storage Driver: overlay2
 Backing Filesystem: extfs
...
Docker Root Dir: /var/lib/docker
...

You can use --format parameter to extract that information into a single file, e.g.

$ docker info --format '{{.DriverStatus}}'
[[Root Dir /var/snap/docker/common/var-lib-docker/aufs] [Backing Filesystem extfs] [Dirs 265] [Dirperm1 Supported true]]

or:

$ docker info --format '{{json .DriverStatus}}'
[["Root Dir","/var/snap/docker/common/var-lib-docker/aufs"],["Backing Filesystem","extfs"],["Dirs","265"],["Dirperm1 Supported","true"]]

What is difference between Axios and Fetch?

Fetch and Axios are very similar in functionality, but for more backwards compatibility Axios seems to work better (fetch doesn't work in IE 11 for example, check this post)

Also, if you work with JSON requests, the following are some differences I stumbled upon with.

Fetch JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify({
                property_one: value_one,
                property_two: value_two
            })
        };
let response = await fetch(url, options);
let responseOK = response && response.ok;
if (responseOK) {
    let data = await response.json();
    // do something with data
}

Axios JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            url: url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data: {
                property_one: value_one,
                property_two: value_two
            }
        };
let response = await axios(options);
let responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
    let data = await response.data;
    // do something with data
}

So:

  • Fetch's body = Axios' data
  • Fetch's body has to be stringified, Axios' data contains the object
  • Fetch has no url in request object, Axios has url in request object
  • Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
  • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
  • To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.

Hope this helps.

MySQL, Concatenate two columns

$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');

Finding all possible permutations of a given string in python

Here's a simple and straightforward recursive implementation;

def stringPermutations(s):
    if len(s) < 2:
        yield s
        return
    for pos in range(0, len(s)):
        char = s[pos]
        permForRemaining = list(stringPermutations(s[0:pos] + s[pos+1:]))
        for perm in permForRemaining:
            yield char + perm

Does functional programming replace GoF design patterns?

I would say that when you have a language like Lisp with its support for macros, then you can build you own domain-specific abstractions, abstractions which often are much better than the general idiom solutions.

How do I install command line MySQL client on mac?

If you have already installed MySQL from the disk image (dmg) from http://dev.mysql.com/downloads/), open a terminal, run:

echo 'export PATH=/usr/local/mysql/bin:$PATH' >> ~/.bash_profile

then, reload .bash_profile by running following command:

 . ~/.bash_profile

You can now use mysql to connect to any mysql server:

mysql -h xxx.xxx.xxx.xxx -u username -p

Credit & Reference: http://www.gigoblog.com/2011/03/13/add-mysql-to-terminal-shell-in-mac-os-x/

Button text toggle in jquery

You can also use math function to do this

var i = 0;
$('#button').on('click', function() {
    if (i++ % 2 == 0) {
        $(this).val("Push me!");
    } else {
        $(this).val("Don't push me!");
    }
});

DEMO

Is < faster than <=?

Assuming we're talking about internal integer types, there's no possible way one could be faster than the other. They're obviously semantically identical. They both ask the compiler to do precisely the same thing. Only a horribly broken compiler would generate inferior code for one of these.

If there was some platform where < was faster than <= for simple integer types, the compiler should always convert <= to < for constants. Any compiler that didn't would just be a bad compiler (for that platform).

Blue and Purple Default links, how to remove?

<a href="https://www." style="color: inherit;"target="_blank">

For CSS inline style, this worked best for me.

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

Try adding the drive letter:

include_path='.;c:\xampplite\php\pear\PEAR'

also verify that PEAR.php is actually there, it might be in \php\ instead:

include_path='.;c:\xampplite\php'

How to convert a Map to List in Java?

List<Value> list = new ArrayList<Value>(map.values());

assuming:

Map<Key,Value> map;

How to trigger a file download when clicking an HTML button or JavaScript

For me ading button instead of anchor text works really well.

<a href="file.doc"><button>Download!</button></a>

It might not be ok by most rules, but it looks pretty good.

How can I create a simple message box in Python?

You can use pyautogui or pymsgbox:

import pyautogui
pyautogui.alert("This is a message box",title="Hello World")

Using pymsgbox is the same as using pyautogui:

import pymsgbox
pymsgbox.alert("This is a message box",title="Hello World")

How to validate a file upload field using Javascript/jquery

In Firefox at least, the DOM inspector is telling me that the File input elements have a property called files. You should be able to check its length.

document.getElementById('myFileInput').files.length

The import com.google.android.gms cannot be resolved

I checked off Google API as project build target.

That is irrelevant, as that is for Maps V1, and you are trying to use Maps V2.

I included .jar file for maps by right-clicking on my project, went to build path and added external archive locating it in my SDK: android-sdk-windows\add-ons\addon_google_apis_google_inc_8\libs\maps

This is doubly wrong.

First, never manually modify the build path in an Android project. If you are doing that, at best, you will crash at runtime, because the JAR you think you put in your project (via the manual build path change) is not in your APK. For an ordinary third-party JAR, put it in the libs/ directory of your project, which will add it to your build path automatically and add its contents to your APK file.

However, Maps V2 is not a JAR. It is an Android library project that contains a JAR. You need the whole library project.

You need to import the android-sdk-windows\add-ons\addon_google_apis_google_inc_8 project into Eclipse, then add it to your app as a reference to an Android library project.

How to disable Django's CSRF validation?

@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.

Python pip install fails: invalid command egg_info

Looks like the default easy_install is broken in its current location:

$ which easy_install /usr/bin/easy_install

A way to overcome this is to use the easy_install in site packages. For example:

$ sudo python /Library/Python/2.7/site-packages/easy_install.py boto

Add object to ArrayList at specified index

If that's the case then why don't you consider using a regular Array, initialize the capacity and put objects at the index you want.

Object[] list = new Object[10];

list[0] = object1;
list[2] = object3;
list[1] = object2;

Check if process returns 0 with batch file

ERRORLEVEL will contain the return code of the last command. Sadly you can only check >= for it.

Note specifically this line in the MSDN documentation for the If statement:

errorlevel Number

Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than Number.

So to check for 0 you need to think outside the box:

IF ERRORLEVEL 1 GOTO errorHandling
REM no error here, errolevel == 0
:errorHandling

Or if you want to code error handling first:

IF NOT ERRORLEVEL 1 GOTO no_error
REM errorhandling, errorlevel >= 1
:no_error

Further information about BAT programming: http://www.ericphelps.com/batch/ Or more specific for Windows cmd: MSDN using batch files

Downloading jQuery UI CSS from Google's CDN

The Google AJAX Libraries API, which includes jQuery UI (currently v1.10.3), also includes popular themes as per the jQuery UI blog:

Google Ajax Libraries API (CDN)

One DbContext per web request... why?

What I like about it is that it aligns the unit-of-work (as the user sees it - i.e. a page submit) with the unit-of-work in the ORM sense.

Therefore, you can make the entire page submission transactional, which you could not do if you were exposing CRUD methods with each creating a new context.

Rolling or sliding window iterator?

This seems tailor-made for a collections.deque since you essentially have a FIFO (add to one end, remove from the other). However, even if you use a list you shouldn't be slicing twice; instead, you should probably just pop(0) from the list and append() the new item.

Here is an optimized deque-based implementation patterned after your original:

from collections import deque

def window(seq, n=2):
    it = iter(seq)
    win = deque((next(it, None) for _ in xrange(n)), maxlen=n)
    yield win
    append = win.append
    for e in it:
        append(e)
        yield win

In my tests it handily beats everything else posted here most of the time, though pillmuncher's tee version beats it for large iterables and small windows. On larger windows, the deque pulls ahead again in raw speed.

Access to individual items in the deque may be faster or slower than with lists or tuples. (Items near the beginning are faster, or items near the end if you use a negative index.) I put a sum(w) in the body of my loop; this plays to the deque's strength (iterating from one item to the next is fast, so this loop ran a a full 20% faster than the next fastest method, pillmuncher's). When I changed it to individually look up and add items in a window of ten, the tables turned and the tee method was 20% faster. I was able to recover some speed by using negative indexes for the last five terms in the addition, but tee was still a little faster. Overall I would estimate that either one is plenty fast for most uses and if you need a little more performance, profile and pick the one that works best.

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Here is simple sample from android developer.

Basically, you can write a file in the internal storage like this :

String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

How to fix Subversion lock error

We had the same repeating problem. It's a disaster. What can you do if cleanup and unlock does not help because there is no existing lock?

  1. Search the hidden .svn folder in your directory structure. It contains a wc.db file which is an sql lite file.
  2. Open it with an sql client, e.g. DBeaver. Add an sql lite connection to the dbeaver by selecting the wc.db file.
  3. Open the WC_LOCK table. You can see one or more rows that contains the URL which was mentioned in the phantom lock error window.
  4. Delete these rows from the table.
  5. Try to update your project from the repo.
  6. If you use more than 1 repo in 1 project (externals) another phantom lock may appear during the update. In this case repeat the process with that folder.

How do you convert a DataTable into a generic list?

If you're using .NET 3.5, you can use DataTableExtensions.AsEnumerable (an extension method) and then if you really need a List<DataRow> instead of just IEnumerable<DataRow> you can call Enumerable.ToList:

IEnumerable<DataRow> sequence = dt.AsEnumerable();

or

using System.Linq;
...
List<DataRow> list = dt.AsEnumerable().ToList();

What's the difference between RANK() and DENSE_RANK() functions in oracle?

select empno
       ,salary
       ,row_number() over(order by salary desc) as Serial
       ,Rank() over(order by salary desc) as rank
       ,dense_rank() over(order by salary desc) as denseRank
from emp ;

Row_number() -> Used for generating serial number

Dense_rank() will give continuous rank but rank will skip rank in case of clash of rank.

How to make a great R reproducible example

I wonder if an http://old.r-fiddle.org/ link could be a very neat way of sharing a problem. It receives a unique ID like and one could even think about embedding it in SO.

Filtering array of objects with lodash based on property value

_x000D_
_x000D_
let myArr = [_x000D_
    { name: "john", age: 23 },_x000D_
    { name: "john", age: 43 },_x000D_
    { name: "jim", age: 101 },_x000D_
    { name: "bob", age: 67 },_x000D_
];_x000D_
_x000D_
// this will return old object (myArr) with items named 'john'_x000D_
let list = _.filter(myArr, item => item.name === 'jhon');_x000D_
_x000D_
//  this will return new object referenc (new Object) with items named 'john' _x000D_
let list = _.map(myArr, item => item.name === 'jhon').filter(item => item.name);
_x000D_
_x000D_
_x000D_

Is there a Sleep/Pause/Wait function in JavaScript?

You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout to kick off a function after a delay:

setTimeout(function(){alert("hi")}, 1000);

Depending on your needs, setInterval might be useful, too.

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

How can I access "static" class variables within class methods in Python?

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

How can I specify a branch/tag when adding a Git submodule?

git submodule add -b develop --name branch-name -- https://branch.git

Page unload event in asp.net

With AutoEventWireup which is turned on by default on a page you can just add methods prepended with **Page_***event* and have ASP.NET connect to the events for you.

In the case of Unload the method signature is:

protected void Page_Unload(object sender, EventArgs e)

For details see the MSDN article.

Check if list contains element that contains a string and get that element

You could use Linq's FirstOrDefault extension method:

string element = myList.FirstOrDefault(s => s.Contains(myString));

This will return the fist element that contains the substring myString, or null if no such element is found.

If all you need is the index, use the List<T> class's FindIndex method:

int index = myList.FindIndex(s => s.Contains(myString));

This will return the the index of fist element that contains the substring myString, or -1 if no such element is found.

What is the correct format to use for Date/Time in an XML file

I always use the ISO 8601 format (e.g. 2008-10-31T15:07:38.6875000-05:00) -- date.ToString("o"). It is the XSD date format as well. That is the preferred format and a Standard Date and Time Format string, although you can use a manual format string if necessary if you don't want the 'T' between the date and time: date.ToString("yyyy-MM-dd HH:mm:ss");

EDIT: If you are using a generated class from an XSD or Web Service, you can just assign the DateTime instance directly to the class property. If you are writing XML text, then use the above.

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

How to show uncommitted changes in Git and some Git diffs in detail

You have already staged the changes (presumably by running git add), so in order to get their diff, you need to run:

git diff --cached

(A plain git diff will only show unstaged changes.)

For example: Example git diff cached use

How to make an embedded video not autoplay

Try replacing your movie param line with

<param name="movie" value="untitled_skin.swf&autoStart=false">

How to pass macro definition from "make" command line arguments (-D) to C source code?

Find the C file and Makefile implementation in below to meet your requirements

foo.c

 main ()
    {
        int a = MAKE_DEFINE;
        printf ("MAKE_DEFINE value:%d\n", a);
    }

Makefile

all:
    gcc -DMAKE_DEFINE=11 foo.c

Android marshmallow request permission?

There is a good library that can be used in case permissions need to be asked when permission is needed by a background service. Although a limitation of library is that it can not be used to just determine whether permissions are currently given to the app or not. It always asks the user if app doesn't already have them.

Do give it a try as it makes life simpler: Android Permissions

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

When we use the slf4j api jar, we need any of the logger implementations like log4j. On my system, we have the complete set and it works fine.

1. slf4j-api-1.5.6.jar
2. slf4j-log4j12-1.5.6.jar
3. **log4j-1.2.15.jar**

Random record from MongoDB

My PHP/MongoDB sort/order by RANDOM solution. Hope this helps anyone.

Note: I have numeric ID's within my MongoDB collection that refer to a MySQL database record.

First I create an array with 10 randomly generated numbers

    $randomNumbers = [];
    for($i = 0; $i < 10; $i++){
        $randomNumbers[] = rand(0,1000);
    }

In my aggregation I use the $addField pipeline operator combined with $arrayElemAt and $mod (modulus). The modulus operator will give me a number from 0 - 9 which I then use to pick a number from the array with random generated numbers.

    $aggregate[] = [
        '$addFields' => [
            'random_sort' => [ '$arrayElemAt' => [ $randomNumbers, [ '$mod' => [ '$my_numeric_mysql_id', 10 ] ] ] ],
        ],
    ];

After that you can use the sort Pipeline.

    $aggregate[] = [
        '$sort' => [
            'random_sort' => 1
        ]
    ];

g++ ld: symbol(s) not found for architecture x86_64

I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:

gcc -o exec main.o add.o

But my program is a C++ program. Using the g++ compiler solved my issue:

g++ -o exec main.o add.o

I was always under the impression that gcc could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.

What do raw.githubusercontent.com URLs represent?

The raw.githubusercontent.com domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.

The URL in your question references the install file in the master branch of the Homebrew/install repository. The rest of that command just retrieves the file and runs ruby on its contents.

jQuery datepicker, onSelect won't work

datePicker's onSelect equivalent is the dateSelected event.

$(function() {
    $('.date-pick').datePicker( {
        selectWeek: true,
        inline: true,
        startDate: '01/01/2000',
        firstDay: 1,
    }).bind('dateSelected', function(e, selectedDate, $td) {
        alert(selectedDate);
    });
});

This page has a good example showing the dateSelected event and other events being bound.

How to clear the interpreter console?

Use idle. It has many handy features. Ctrl+F6, for example, resets the console. Closing and opening the console are good ways to clear it.

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I solved this problem removing DbproviderFactory in the section system.data of the file machine.config, there was some dirty data when I installed fbclient.dll.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config

  <system.data>
    <!-- <DbProviderFactories><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=4.10.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/><add name="FirebirdClient Data Provider" invariant="FirebirdSql.Data.FirebirdClient" description=".NET Framework Data Provider for Firebird" type="FirebirdSql.Data.FirebirdClient.FirebirdClientFactory, FirebirdSql.Data.FirebirdClient, Version=6.4.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c"/> -->
  </system.data>

What's the best practice to "git clone" into an existing folder?

This is the Best of all methods i came across

Clone just the repository's .git folder (excluding files as they are already in existing-dir) into an empty temporary directory

  1. git clone --no-checkout repo-path-to-clone existing-dir/existing-dir.tmp //might want --no-hardlinks for cloning local repo

Move the .git folder to the directory with the files. This makes existing-dir a git repo.

  1. mv existing-dir/existing-dir.tmp/.git existing-dir/

Delete the temporary directory

  1. rmdir existing-dir/existing-dir.tmp

  2. cd existing-dir

Git thinks all files are deleted, this reverts the state of the repo to HEAD.

WARNING: any local changes to the files will be lost.

  1. git reset --mixed HEAD

pod install -bash: pod: command not found

so I also had the same problem. This is probably happening because your computer has an older version of ruby. So you need to first update your ruby. Mine worked for ruby 2.6.3 version.I got this solution from sStackOverflow,

You need to first open terminal and put this code

curl -L https://get.rvm.io | bash -s stable

Then put this command

rvm install ruby-2.6

This would install the ruby for you if it hasn' t been installed.After this just update the ruby to the new version

rvm use ruby-2.6.3

After this just make ruby 2.6.3 your default

rvm --default use 2.6.3

This would possibly fix your issue. You can now put the command

sudo gem install cocoapods

And the command

pod setup

I hope this was useful

Run php script as daemon process

I was looking for a simple solution without having to install additional stuff and compatible with common hostings that allow SSH access.

I've ended up with this setup for my chat server:

-rwxr-xr-x  1 crazypoems psacln   309 ene 30 14:01 checkChatServerRunning.sh
-rw-r--r--  1 crazypoems psacln  3018 ene 30 13:12 class.chathandler.php
-rw-r--r--  1 crazypoems psacln    29 ene 30 14:05 cron.log
-rw-r--r--  1 crazypoems psacln  2560 ene 29 08:04 index.php
-rw-r--r--  1 crazypoems psacln  2672 ene 30 13:29 php-socket.php
-rwxr-xr-x  1 crazypoems psacln   310 ene 30 14:04 restartChatServer.sh
-rwxr-xr-x  1 crazypoems psacln   122 ene 30 13:28 startChatServer.sh
-rwxr-xr-x  1 crazypoems psacln   224 ene 30 13:56 stopChatServer.sh

And the scripts:

startChatServer.sh

#!/bin/bash
nohup /opt/plesk/php/5.6/bin/php -q /var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php > /dev/null &

stopChatServer.sh

#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID
else
  echo "not running"
fi

restartChatServer.sh

#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID
else
  echo "not running"
fi
echo "Starting again"
/var/www/vhosts/crazypoems.org/httpdocs/chat/startChatServer.sh

And last but not least, I have put this last script on a cron job, to check if the "chat server is running", and if not, to start it:

Cron job every minute

-bash-4.1$ crontab -l
*       *       *       *       * /var/www/vhosts/crazypoems.org/httpdocs/chat/checkChatServerRunning.sh > /var/www/vhosts/crazypoems.org/httpdocs/chat/cron.log

checkChatServerRunning.sh

#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "Chat server running on $PID"
else
  echo "Not running, going to start it"
  /var/www/vhosts/crazypoems.org/httpdocs/chat/startChatServer.sh
fi

So with this setup:

  • I manually can control the service with the scripts when needed (eg: maintenance)
  • The cron job will start the server on reboot, or on crash

Convert hex color value ( #ffffff ) to integer value

Integer.parseInt(myString.replaceFirst("#", ""), 16) 

convert NSDictionary to NSString

You can call [aDictionary description], or anywhere you would need a format string, just use %@ to stand in for the dictionary:

[NSString stringWithFormat:@"my dictionary is %@", aDictionary];

or

NSLog(@"My dictionary is %@", aDictionary);

Unable to create migrations after upgrading to ASP.NET Core 2.0

Manzur Alahi is right! I'm trying to learn Rider by JetBrains and I had the same error when I was trying to use dotnet-ef migrations add ... in Cmd, PowerShell, etc. but when I used Visual Studio IDE I didn't have problem.

I fixed the error with:

dotnet ef migrations add InitialMigration --project "Domain.Entities" --startup-project "WebApi"

and this to update the database

dotnet ef database update --project "Domain.Entities" --startup-project "WebApi"

just like Manzur Alahi said.

ngOnInit not being called when Injectable class is Instantiated

Lifecycle hooks, like OnInit() work with Directives and Components. They do not work with other types, like a service in your case. From docs:

A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.

How can I pass a parameter to a setTimeout() callback?

I know it's old but I wanted to add my (preferred) flavour to this.

I think a pretty readable way to achieve this is to pass the topicId to a function, which in turn uses the argument to reference the topic ID internally. This value won't change even if topicId in the outside will be changed shortly after.

var topicId = xmlhttp.responseText;
var fDelayed = function(tid) {
  return function() {
    postinsql(tid);
  };
}
setTimeout(fDelayed(topicId),4000);

or short:

var topicId = xmlhttp.responseText;
setTimeout(function(tid) {
  return function() { postinsql(tid); };
}(topicId), 4000);

MVC Calling a view from a different controller

I'm not really sure if I got your question right. Maybe something like

public class CommentsController : Controller
{
    [HttpPost]
    public ActionResult WriteComment(CommentModel comment)
    {
        // Do the basic model validation and other stuff
        try
        {
            if (ModelState.IsValid )
            {
                 // Insert the model to database like:
                 db.Comments.Add(comment);
                 db.SaveChanges();

                 // Pass the comment's article id to the read action
                 return RedirectToAction("Read", "Articles", new {id = comment.ArticleID});
            }
        }
        catch ( Exception e )
        {
             throw e;
        }
        // Something went wrong
        return View(comment);

    }
}


public class ArticlesController : Controller
{
    // id is the id of the article
    public ActionResult Read(int id)
    {
        // Get the article from database by id
        var model = db.Articles.Find(id);
        // Return the view
        return View(model);
    }
}

Floating point comparison functions for C#

static class FloatUtil {

    static bool IsEqual(float a, float b, float tolerance = 0.001f) {
      return Math.Abs(a - b) < tolerance;
    }

    static bool IsGreater(float a, float b) {
      return a > b;
    }

    static bool IsLess(float a, float b) {
      return a < b;
    }
}

The value of tolerance that is passed into IsEqual is something that the client could decide.

IsEqual(1.002, 1.001);          -->   False
IsEqual(1.002, 1.001, 0.01);    -->   True

Edit In Place Content Editing

You should put the form inside each node and use ng-show and ng-hide to enable and disable editing, respectively. Something like this:

<li>
  <span ng-hide="editing" ng-click="editing = true">{{bday.name}} | {{bday.date}}</span>
  <form ng-show="editing" ng-submit="editing = false">
    <label>Name:</label>
    <input type="text" ng-model="bday.name" placeholder="Name" ng-required/>
    <label>Date:</label>
    <input type="date" ng-model="bday.date" placeholder="Date" ng-required/>
    <br/>
    <button class="btn" type="submit">Save</button>
   </form>
 </li>

The key points here are:

  • I've changed controls ng-model to the local scope
  • Added ng-show to form so we can show it while editing
  • Added a span with a ng-hide to hide the content while editing
  • Added a ng-click, that could be in any other element, that toggles editing to true
  • Changed ng-submit to toggle editing to false

Here is your updated Plunker.

Python Key Error=0 - Can't find Dict error in code

The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []
  self.adj[u].append(edge)
.
.

What is the most compatible way to install python modules on a Mac?

Regarding which python version to use, Mac OS usually ships an old version of python. It's a good idea to upgrade to a newer version. You can download a .dmg from http://www.python.org/download/ . If you do that, remember to update the path. You can find the exact commands here http://farmdev.com/thoughts/66/python-3-0-on-mac-os-x-alongside-2-6-2-5-etc-/

Add days Oracle SQL

It's Simple.You can use

select (sysdate+2) as new_date from dual;

This will add two days from current date.

What is a callback in java

A callback is some code that you pass to a given method, so that it can be called at a later time.

In Java one obvious example is java.util.Comparator. You do not usually use a Comparator directly; rather, you pass it to some code that calls the Comparator at a later time:

Example:

class CodedString implements Comparable<CodedString> {
    private int code;
    private String text;

    ...

    @Override
    public boolean equals() {
        // member-wise equality
    }

    @Override
    public int hashCode() {
        // member-wise equality 
    }

    @Override
    public boolean compareTo(CodedString cs) {
        // Compare using "code" first, then
        // "text" if both codes are equal.
    }
}

...

public void sortCodedStringsByText(List<CodedString> codedStrings) {
    Comparator<CodedString> comparatorByText = new Comparator<CodedString>() {
        @Override
        public int compare(CodedString cs1, CodedString cs2) {
            // Compare cs1 and cs2 using just the "text" field
        }
    }

    // Here we pass the comparatorByText callback to Collections.sort(...)
    // Collections.sort(...) will then call this callback whenever it
    // needs to compare two items from the list being sorted.
    // As a result, we will get the list sorted by just the "text" field.
    // If we do not pass a callback, Collections.sort will use the default
    // comparison for the class (first by "code", then by "text").
    Collections.sort(codedStrings, comparatorByText);
}

How to block until an event is fired in c#

You can use ManualResetEvent. Reset the event before you fire secondary thread and then use the WaitOne() method to block the current thread. You can then have secondary thread set the ManualResetEvent which would cause the main thread to continue. Something like this:

ManualResetEvent oSignalEvent = new ManualResetEvent(false);

void SecondThread(){
    //DoStuff
    oSignalEvent.Set();
}

void Main(){
    //DoStuff
    //Call second thread
    System.Threading.Thread oSecondThread = new System.Threading.Thread(SecondThread);
    oSecondThread.Start();

    oSignalEvent.WaitOne(); //This thread will block here until the reset event is sent.
    oSignalEvent.Reset();
    //Do more stuff
}

How to generate a Makefile with source in sub-directories using just one makefile

Here is my solution, inspired from Beta's answer. It's simpler than the other proposed solutions

I have a project with several C files, stored in many subdirectories. For example:

src/lib.c
src/aa/a1.c
src/aa/a2.c
src/bb/b1.c
src/cc/c1.c

Here is my Makefile (in the src/ directory):

# make       -> compile the shared library "libfoo.so"
# make clean -> remove the library file and all object files (.o)
# make all   -> clean and compile
SONAME  = libfoo.so
SRC     = lib.c   \
          aa/a1.c \
          aa/a2.c \
          bb/b1.c \
          cc/c1.c
# compilation options
CFLAGS  = -O2 -g -W -Wall -Wno-unused-parameter -Wbad-function-cast -fPIC
# linking options
LDFLAGS = -shared -Wl,-soname,$(SONAME)

# how to compile individual object files
OBJS    = $(SRC:.c=.o)
.c.o:
    $(CC) $(CFLAGS) -c $< -o $@

.PHONY: all clean

# library compilation
$(SONAME): $(OBJS) $(SRC)
    $(CC) $(OBJS) $(LDFLAGS) -o $(SONAME)

# cleaning rule
clean:
    rm -f $(OBJS) $(SONAME) *~

# additional rule
all: clean lib

This example works fine for a shared library, and it should be very easy to adapt for any compilation process.

Principal Component Analysis (PCA) in Python

In addition to all the other answers, here is some code to plot the biplot using sklearn and matplotlib.

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
import pandas as pd
from sklearn.preprocessing import StandardScaler

iris = datasets.load_iris()
X = iris.data
y = iris.target
#In general a good idea is to scale the data
scaler = StandardScaler()
scaler.fit(X)
X=scaler.transform(X)    

pca = PCA()
x_new = pca.fit_transform(X)

def myplot(score,coeff,labels=None):
    xs = score[:,0]
    ys = score[:,1]
    n = coeff.shape[0]
    scalex = 1.0/(xs.max() - xs.min())
    scaley = 1.0/(ys.max() - ys.min())
    plt.scatter(xs * scalex,ys * scaley, c = y)
    for i in range(n):
        plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)
        if labels is None:
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
        else:
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("PC{}".format(1))
plt.ylabel("PC{}".format(2))
plt.grid()

#Call the function. Use only the 2 PCs.
myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :]))
plt.show()

enter image description here

Good tutorial for using HTML5 History API (Pushstate?)

You may want to take a look at this jQuery plugin. They have lots of examples on their site. http://www.asual.com/jquery/address/

Set TextView text from html-formatted string resource in XML

  String termsOfCondition="<font color=#cc0029>Terms of Use </font>";
  String commma="<font color=#000000>, </font>";
  String privacyPolicy="<font color=#cc0029>Privacy Policy </font>";
  Spanned text=Html.fromHtml("I am of legal age and I have read, understood, agreed and accepted the "+termsOfCondition+commma+privacyPolicy);
        secondCheckBox.setText(text);

Java System.out.print formatting

Just use \t to space it.

Example:

System.out.println(monthlyInterest + "\t")

//as far as the two 0 in front of it just use a if else statement. ex: 
x = x+1;
if (x < 10){
    System.out.println("00" +x);
}
else if( x < 100){
    System.out.println("0" +x);
}
else{
    System.out.println(x);
}

There are other ways to do it, but this is the simplest.

How do I escape ampersands in XML so they are rendered as entities in HTML?

<xsl:text disable-output-escaping="yes">&amp;&nbsp;</xsl:text> will do the trick.

Store List to session

I found in a class file outside the scope of the Page, the above way (which I always have used) didn't work.
I found a workaround in this "context" as follows:

HttpContext.Current.Session.Add("currentUser", appUser);

and

(AppUser) HttpContext.Current.Session["currentUser"]

Otherwise the compiler was expecting a string when I pointed the object at the session object.

How to reference a .css file on a razor view?

layout works the same as an master page. any css reference that layout has, any child pages will have.

Scott Gu has an excellent explanation here