Programs & Examples On #Mercurial subrepos

Questions related to the subrepository feature in the Mercurial distributed version control system.

Use Expect in a Bash script to provide a password to an SSH command

Use the helper tool fd0ssh (from hxtools, not pmt). It works without having to expect a particular prompt from the ssh program.

How to use Macro argument as string literal?

Use the preprocessor # operator:

#define CALL_DO_SOMETHING(VAR) do_something(#VAR, VAR);

Selecting multiple columns with linq query and lambda expression

Not sure what you table structure is like but see below.

public NamePriceModel[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts
                .Where(x => x.Status == 1)
                .Select(x => new NamePriceModel { 
                    Name = x.Name, 
                    Id = x.Id, 
                    Price = x.Price
                })
                .OrderBy(x => x.Id)
                .ToArray();
         }
     }
     catch
     {
         return null;
     }
 }

This would return an array of type anonymous with the members you require.

Update:

Create a new class.

public class NamePriceModel 
{
    public string Name {get; set;}
    public decimal? Price {get; set;}
    public int Id {get; set;}
}

I've modified the query above to return this as well and you should change your method from returning string[] to returning NamePriceModel[].

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

Also - please note that you may have transparency set even if you don't actually have any transparency in your images. If you're using photoshop, 'save for web' and de-select 'transparency' or just convert your image to a .jpg. iTunes Connect seems to reject transparencies as well.

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

<root>
    <level value="ALL" />
    <appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />
</logger>

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

Check if string ends with one of the strings from a list

I just came across this, while looking for something else.

I would recommend to go with the methods in the os package. This is because you can make it more general, compensating for any weird case.

You can do something like:

import os

the_file = 'aaaa/bbbb/ccc.ddd'

extensions_list = ['ddd', 'eee', 'fff']

if os.path.splitext(the_file)[-1] in extensions_list:
    # Do your thing.

ASP.NET MVC: What is the purpose of @section?

You want to use sections when you want a bit of code/content to render in a placeholder that has been defined in a layout page.

In the specific example you linked, he has defined the RenderSection in the _Layout.cshtml. Any view that uses that layout can define an @section of the same name as defined in Layout, and it will replace the RenderSection call in the layout.

Perhaps you're wondering how we know Index.cshtml uses that layout? This is due to a bit of MVC/Razor convention. If you look at the dialog where he is adding the view, the box "Use layout or master page" is checked, and just below that it says "Leave empty if it is set in a Razor _viewstart file". It isn't shown, but inside that _ViewStart.cshtml file is code like:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

The way viewstarts work is that any cshtml file within the same directory or child directories will run the ViewStart before it runs itself.

Which is what tells us that Index.cshtml uses Shared/_Layout.cshtml.

Loop through JSON in EJS

JSON.stringify(data).length return string length not Object length, you can use Object.keys.

<% for(var i=0; i < Object.keys(data).length ; i++) {%>

https://stackoverflow.com/a/14379528/3224296

Call a Class From another class

If your class2 looks like this having static members

public class2
{
    static int var = 1;

    public static void myMethod()
    {
      // some code

    }
}

Then you can simply call them like

class2.myMethod();
class2.var = 1;

If you want to access non-static members then you would have to instantiate an object.

class2 object = new class2();
object.myMethod();  // non static method
object.var = 1;     // non static variable

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

How to mock a final class with mockito

Please look at JMockit. It has extensive documentation with a lot of examples. Here you have an example solution of your problem (to simplify I've added constructor to Seasons to inject mocked RainOnTrees instance):

package jmockitexample;

import mockit.Mocked;
import mockit.Verifications;
import mockit.integration.junit4.JMockit;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMockit.class)
public class SeasonsTest {

    @Test
    public void shouldStartRain(@Mocked final RainOnTrees rain) {
        Seasons seasons = new Seasons(rain);

        seasons.findSeasonAndRain();

        new Verifications() {{
            rain.startRain();
        }};
    }

    public final class RainOnTrees {
        public void startRain() {
            // some code here
        }

    }

    public class Seasons {

        private final RainOnTrees rain;

        public Seasons(RainOnTrees rain) {
            this.rain = rain;
        }

        public void findSeasonAndRain() {
            rain.startRain();
        }

    }
}

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

How do I add comments to package.json for npm install?

Here's my take on comments within package.json / bower.json:

I have file package.json.js that contains a script that exports the actual package.json. Running the script overwrites the old package.json and tells me what changes it made, perfect to help you keep track of automatic changes npm made. That way I can even programmatically define what packages I want to use.

The latest Grunt task is here: https://gist.github.com/MarZab/72fa6b85bc9e71de5991

jQuery changing font family and font size

Full working solution :

HTML:

<form id="myform">
    <button>erase</button>
    <select id="fs"> 
        <option value="Arial">Arial</option>
        <option value="Verdana ">Verdana </option>
        <option value="Impact ">Impact </option>
        <option value="Comic Sans MS">Comic Sans MS</option>
    </select>

    <select id="size">
        <option value="7">7</option>
        <option value="10">10</option>
        <option value="20">20</option>
        <option value="30">30</option>
    </select>
</form>

<br/>

<textarea class="changeMe">Text into textarea</textarea>
<div id="container" class="changeMe">
    <div id="float">
        <p>
            Text into container
        </p>
    </div>
</div>

jQuery:

$("#fs").change(function() {
    //alert($(this).val());
    $('.changeMe').css("font-family", $(this).val());

});

$("#size").change(function() {
    $('.changeMe').css("font-size", $(this).val() + "px");
});

Fiddle here: http://jsfiddle.net/AaT9b/

Handle Guzzle exception and get HTTP body

While the answers above are good they will not catch network errors. As Mark mentioned, BadResponseException is just a super class for ClientException and ServerException. But RequestException is also a super class of BadResponseException. RequestException will be thrown for not only 400 and 500 errors but network errors and infinite redirects too. So let's say you request the page below but your network is playing up and your catch is only expecting a BadResponseException. Well your application will throw an error.

It's better in this case to expect RequestException and check for a response.

try {
  $client->get('http://123123123.com')
} catch (RequestException $e) {

  // If there are network errors, we need to ensure the application doesn't crash.
  // if $e->hasResponse is not null we can attempt to get the message
  // Otherwise, we'll just pass a network unavailable message.
  if ($e->hasResponse()) {
    $exception = (string) $e->getResponse()->getBody();
    $exception = json_decode($exception);
    return new JsonResponse($exception, $e->getCode());
  } else {
    return new JsonResponse($e->getMessage(), 503);
  }

}

Is it possible to access an SQLite database from JavaScript?

Up to date answer

My fork of sql.js has now be merged into the original version, on kriken's repo.

The good documentation is also available on the original repo.

Original answer (outdated)

You should use the newer version of sql.js. It is a port of sqlite 3.8, has a good documentation and is actively maintained (by me). It supports prepared statements, and BLOB data type.

Set NOW() as Default Value for datetime datatype?

`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

Can be used to update the timestamp on update.

ant build.xml file doesn't exist

may be you can specify where the buildfile is located and then invoke desired action.

Eg: ant -file {BuildfileLocation/build.xml} -v

Moment.js: Date between dates

You can use one of the moment plugin -> moment-range to deal with date range:

var startDate = new Date(2013, 1, 12)
  , endDate   = new Date(2013, 1, 15)
  , date  = new Date(2013, 2, 15)
  , range = moment().range(startDate, endDate);

range.contains(date); // false

How to trim whitespace from a Bash variable?

var="  a b  "
echo "$(set -f; echo $var)"

>a b

Where is jarsigner?

For me the solution was in setting the global variable path to the JDK. See here: https://appopus.wordpress.com/2012/07/11/how-to-install-jdk-java-development-kit-and-jarsigner-on-windows/

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

How do I build an import library (.lib) AND a DLL in Visual C++?

you also should specify def name in the project settings here:

Configuration > Properties/Input/Advanced/Module > Definition File

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

How to index into a dictionary?

If you need an ordered dictionary, you can use odict.

PostgreSQL unnest() with element number

Try:

select v.*, row_number() over (partition by id order by elem) rn from
(select
    id,
    unnest(string_to_array(elements, ',')) AS elem
 from myTable) v

Website screenshots

There are many open source projects that can generate screenshots. For example PhantomJS, webkit2png etc

The big problem with these projects is that they are based on older browser technology and have problems rendering many sites, especially sites that use webfonts, flexbox, svg and various other additions to the HTML5 and CSS spec over the last couple of months/years.

I've tried a few of the third party services, and most are based on PhantomJS, meaning they also produce poor quality screenshots. The best third party service for generating website screenshots is urlbox.io. It is a paid service, although there is a free 7-day trial to test it out without committing to any paid plan.

Here is a link to the documentation, and below are simple steps to get it working in PHP with composer.

// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots

// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');

// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';

// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'

// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
<img src="$urlboxUrl" />

For e.g. here's a full height screenshot of this very page:

https://api.urlbox.io/v1/ca482d7e-9417-4569-90fe-80f7c5e1c781/8f1666d1f4195b1cb84ffa5f992ee18992a2b35e/png?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F757675%2Fwebsite-screenshots-using-php%2F43652083%2343652083&full_page=true

full page screenshot of stackoverflow.com question powered by urlbox.io

Error parsing yaml file: mapping values are not allowed here

Change

application:climate-change

to

application: climate-change

The space after the colon is mandatory in yaml if you want a key-value pair. (See http://www.yaml.org/spec/1.2/spec.html#id2759963)

How to keep :active css style after clicking an element

If you want to keep your links to look like they are :active class, you should define :visited class same as :active so if you have a links in .example then you do something like this:

a.example:active, a.example:visited {
/* Put your active state style code here */ }

The Link visited Pseudo Class is used to select visited links as says the name.

How do I enable saving of filled-in fields on a PDF form?

Preview in OS X seems to be able to do this out of the box. Adobe Reader shows the doc as "data typed can't be saved" but Preview was able to save my changes without hassle.

Copy Notepad++ text with formatting?

Select the text.

Right Click.

Plugin Commands -> Copy Text with Syntax Highlighting

Paste it into Word or whatever.

Is there a way to force npm to generate package-lock.json?

This is answered in the comments; package-lock.json is a feature in npm v5 and higher. npm shrinkwrap is how you create a lockfile in all versions of npm.

How to connect Robomongo to MongoDB

I was able to connect Robomongo to a remote instance of MongoDB running on Mongo Labs using the connection string as follows:

  1. Download the latest version of Robomongo. I downloaded 0.9 RC6 from here.

  2. From the connection string, populate the server address and port numbers as follows.

    Connection settings

  3. Populate DB name and username and password as follows under the authentication tab.

    Authentication settings

  4. Test the connection.

    Test connection

    Enter image description here

Listing all extras of an Intent

You could use for (String key : keys) { Object o = get(key); to return an Object, call getClass().getName() on it to get the type, and then do a set of if name.equals("String") type things to work out which method you should actually be calling, in order to get the value?

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

Putting text in top left corner of matplotlib plot

You can use text.

text(x, y, s, fontsize=12)

text coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:

The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords (0,0 is lower-left and 1,1 is upper-right). The example below places text in the center of the axes::

text(0.5, 0.5,'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)

To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text.

EDIT: here you have an example:

In [17]: from pylab import figure, text, scatter, show
In [18]: f = figure()
In [19]: ax = f.add_subplot(111)
In [20]: scatter([3,5,2,6,8],[5,3,2,1,5])
Out[20]: <matplotlib.collections.CircleCollection object at 0x0000000007439A90>
In [21]: text(0.1, 0.9,'matplotlib', ha='center', va='center', transform=ax.transAxes)
Out[21]: <matplotlib.text.Text object at 0x0000000007415B38>
In [22]:

enter image description here

The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha='left' is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.

Execute a large SQL script (with GO commands)

The "GO" batch separator keyword is actually used by SQL Management Studio itself, so that it knows where to terminate the batches it is sending to the server, and it is not passed to SQL server. You can even change the keyword in Management Studio, should you so desire.

Pass parameters in setInterval function

You can pass the parameter(s) as a property of the function object, not as a parameter:

var f = this.someFunction;  //use 'this' if called from class
f.parameter1 = obj;
f.parameter2 = this;
f.parameter3 = whatever;
setInterval(f, 1000);

Then in your function someFunction, you will have access to the parameters. This is particularly useful inside classes where the scope goes to the global space automatically and you lose references to the class that called setInterval to begin with. With this approach, "parameter2" in "someFunction", in the example above, will have the right scope.

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)

Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.

For subdomains (like www.example.com) you can use CNAME records pointing to your-app-name.herokuapp.com. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)

Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com is an HTTP redirect to www.example.com.

Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.

Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):

@   IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.

Remember @ here is a shorthand for the root domain (example.com). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.

See also:

Remarks:

  • Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.

  • Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.

Generic Property in C#

public class MyProp<T>
{
...
}

public class ClassThatUsesMyProp
{
public MyProp<String> SomeProperty { get; set; }
}

Can you hide the controls of a YouTube embed without enabling autoplay?

You can hide the "Watch Later" Button by using "Youtube-nocookie" (this will not hide the share Button)

Adding controls=0 will also remove the video control bar at the bottom of the screen and using modestbranding=1 will remove the youtube logo at bottom right of the screen

However using them both doesn't works as expected (it only hides the video control bar)

<iframe width="100%" height="100%" src="https://www.youtube-nocookie.com/embed/fNb-DTEb43M?controls=0" frameborder="0" allowfullscreen></iframe>

How to determine whether a Pandas Column contains a particular value

You can also use pandas.Series.isin although it's a little bit longer than 'a' in s.values:

In [2]: s = pd.Series(list('abc'))

In [3]: s
Out[3]: 
0    a
1    b
2    c
dtype: object

In [3]: s.isin(['a'])
Out[3]: 
0    True
1    False
2    False
dtype: bool

In [4]: s[s.isin(['a'])].empty
Out[4]: False

In [5]: s[s.isin(['z'])].empty
Out[5]: True

But this approach can be more flexible if you need to match multiple values at once for a DataFrame (see DataFrame.isin)

>>> df = DataFrame({'A': [1, 2, 3], 'B': [1, 4, 7]})
>>> df.isin({'A': [1, 3], 'B': [4, 7, 12]})
       A      B
0   True  False  # Note that B didn't match 1 here.
1  False   True
2   True   True

Xampp-mysql - "Table doesn't exist in engine" #1932

For me I removed whole data folder from xampp\mysql\ and pasted data folder of previous one here which solved my problem...

How to perform mouseover function in Selenium WebDriver using Java?

Its not really possible to perform a 'mouse hover' action, instead you need to chain all of the actions that you want to achieve in one go. So move to the element that reveals the others, then during the same chain, move to the now revealed element and click on it.

When using Action Chains you have to remember to 'do it like a user would'.

Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).moveToElement(webdriver.findElement(By.xpath("/expression-here"))).click().build().perform();

How to read/process command line arguments?

I recommend looking at docopt as a simple alternative to these others.

docopt is a new project that works by parsing your --help usage message rather than requiring you to implement everything yourself. You just have to put your usage message in the POSIX format.

How to run regasm.exe from command line other than Visual Studio command prompt?

You don't need the directory on your path. You could put it on your path, but you don't NEED to do that.
If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg:

c:\Windows\Microsoft.NET\Framework\v2.0.50727\regasm.exe   MyAssembly.dll

How to parse XML in Bash?

Command-line tools that can be called from shell scripts include:

  • 4xpath - command-line wrapper around Python's 4Suite package

  • XMLStarlet

  • xpath - command-line wrapper around Perl's XPath library

    sudo apt-get install libxml-xpath-perl
    
  • Xidel - Works with URLs as well as files. Also works with JSON

I also use xmllint and xsltproc with little XSL transform scripts to do XML processing from the command line or in shell scripts.

Is it possible to decompile a compiled .pyc file into a .py file?

Install using pip install pycompyle6

pycompyle6 filename.pyc

Python - Dimension of Data Frame

df.shape, where df is your DataFrame.

Python matplotlib multiple bars

I know that this is about matplotlib, but using pandas and seaborn can save you a lot of time:

df = pd.DataFrame(zip(x*3, ["y"]*3+["z"]*3+["k"]*3, y+z+k), columns=["time", "kind", "data"])
plt.figure(figsize=(10, 6))
sns.barplot(x="time", hue="kind", y="data", data=df)
plt.show()

enter image description here

How to stop "setInterval"

Store the return of setInterval in a variable, and use it later to clear the interval.

var timer = null;
$("textarea").blur(function(){
    timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
    if(timer){
       window.clearInterval(timer);
       timer = null
    }
});

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

I've been trying to do this in Jupyter Lab so thought it might be useful to post the answer here. You can find the shortcuts in settings and also add your own, where a full list of the possible shortcuts can be found here.

For example, I added my own shortcut to run all cells. In Jupyter Lab, under Settings > Advanced Settings, select Keyboard Shortcuts, then add the following code to 'User Overrides':

{
    "notebook:run-all-cells": {
      "command": "notebook:run-all-cells",
      "keys": [
        "Shift Backspace"
      ],
      "selector": ".jp-Notebook.jp-mod-editMode"
    }
}

Here, Shift + Backspace will run all cells in the notebook.

How can I combine hashes in Perl?

Quick Answer (TL;DR)


    %hash1 = (%hash1, %hash2)

    ## or else ...

    @hash1{keys %hash2} = values %hash2;

    ## or with references ...

    $hash_ref1 = { %$hash_ref1, %$hash_ref2 };

Overview

  • Context: Perl 5.x
  • Problem: The user wishes to merge two hashes1 into a single variable

Solution

  • use the syntax above for simple variables
  • use Hash::Merge for complex nested variables

Pitfalls

See also


Footnotes

1 * (aka associative-array, aka dictionary)

Python - converting a string of numbers into a list of int

it should work

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11'
example_list = [int(k) for k in example_string.split(',')]

MSIE and addEventListener Problem in Javascript?

Using <meta http-equiv="X-UA-Compatible" content="IE=9">, IE9+ does support addEventListener by removing the "on" in the event name, like this:

 var btn1 = document.getElementById('btn1');
 btn1.addEventListener('mousedown', function() {
   console.log('mousedown');
 });

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

I know this has already been answered a long time ago, but I made an extension method to hopefully help other people that come to this question.

Code:

public static class WebRequestExtensions
{
    public static WebResponse GetResponseWithoutException(this WebRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        try
        {
            return request.GetResponse();
        }
        catch (WebException e)
        {
            if (e.Response == null)
            {
                throw;
            }

            return e.Response;
        }
    }
}

Usage:

var request = (HttpWebRequest)WebRequest.CreateHttp("http://invalidurl.com");

//... (initialize more fields)

using (var response = (HttpWebResponse)request.GetResponseWithoutException())
{
    Console.WriteLine("I got Http Status Code: {0}", response.StatusCode);
}

How to set Sqlite3 to be case insensitive when string comparing?

You can use COLLATE NOCASE in your SELECT query:

SELECT * FROM ... WHERE name = 'someone' COLLATE NOCASE

Additionaly, in SQLite, you can indicate that a column should be case insensitive when you create the table by specifying collate nocase in the column definition (the other options are binary (the default) and rtrim; see here). You can specify collate nocase when you create an index as well. For example:

create table Test
(
  Text_Value  text collate nocase
);

insert into Test values ('A');
insert into Test values ('b');
insert into Test values ('C');

create index Test_Text_Value_Index
  on Test (Text_Value collate nocase);

Expressions involving Test.Text_Value should now be case insensitive. For example:

sqlite> select Text_Value from Test where Text_Value = 'B';
Text_Value      
----------------
b               

sqlite> select Text_Value from Test order by Text_Value;
Text_Value      
----------------
A               
b               
C    

sqlite> select Text_Value from Test order by Text_Value desc;
Text_Value      
----------------
C               
b               
A               

The optimiser can also potentially make use of the index for case-insensitive searching and matching on the column. You can check this using the explain SQL command, e.g.:

sqlite> explain select Text_Value from Test where Text_Value = 'b';
addr              opcode          p1          p2          p3                               
----------------  --------------  ----------  ----------  ---------------------------------
0                 Goto            0           16                                           
1                 Integer         0           0                                            
2                 OpenRead        1           3           keyinfo(1,NOCASE)                
3                 SetNumColumns   1           2                                            
4                 String8         0           0           b                                
5                 IsNull          -1          14                                           
6                 MakeRecord      1           0           a                                
7                 MemStore        0           0                                            
8                 MoveGe          1           14                                           
9                 MemLoad         0           0                                            
10                IdxGE           1           14          +                                
11                Column          1           0                                            
12                Callback        1           0                                            
13                Next            1           9                                            
14                Close           1           0                                            
15                Halt            0           0                                            
16                Transaction     0           0                                            
17                VerifyCookie    0           4                                            
18                Goto            0           1                                            
19                Noop            0           0                                            

Where's javax.servlet?

If you've got the Java EE JDK with Glassfish, it's in glassfish3/glassfish/modules/javax.servlet-api.jar.

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

Accessing a Dictionary.Keys Key through a numeric index

Visual Studio's UserVoice gives a link to generic OrderedDictionary implementation by dotmore.

But if you only need to get key/value pairs by index and don't need to get values by keys, you may use one simple trick. Declare some generic class (I called it ListArray) as follows:

class ListArray<T> : List<T[]> { }

You may also declare it with constructors:

class ListArray<T> : List<T[]>
{
    public ListArray() : base() { }
    public ListArray(int capacity) : base(capacity) { }
}

For example, you read some key/value pairs from a file and just want to store them in the order they were read so to get them later by index:

ListArray<string> settingsRead = new ListArray<string>();
using (var sr = new StreamReader(myFile))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
        string[] keyValueStrings = line.Split(separator);
        for (int i = 0; i < keyValueStrings.Length; i++)
            keyValueStrings[i] = keyValueStrings[i].Trim();
        settingsRead.Add(keyValueStrings);
    }
}
// Later you get your key/value strings simply by index
string[] myKeyValueStrings = settingsRead[index];

As you may have noticed, you can have not necessarily just pairs of key/value in your ListArray. The item arrays may be of any length, like in jagged array.

How to find the .NET framework version of a Visual Studio project?

  • VB

Project Properties -> Compiler Tab -> Advanced Compile Options button

  • C#

Project Properties -> Application Tab

Remove all whitespaces from NSString

Easy task using stringByReplacingOccurrencesOfString

NSString *search = [searchbar.text stringByReplacingOccurrencesOfString:@" " withString:@""];

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

PDF Blob - Pop up window not showing content

I have been struggling for days finally the solution which worked for me is given below. I had to make the window.print() for PDF in new window needs to work.

 var xhr = new XMLHttpRequest();
      xhr.open('GET', pdfUrl, true);
      xhr.responseType = 'blob';

      xhr.onload = function(e) {
        if (this['status'] == 200) {          
          var blob = new Blob([this['response']], {type: 'application/pdf'});
          var url = URL.createObjectURL(blob);
          var printWindow = window.open(url, '', 'width=800,height=500');
          printWindow.print()
        }
      };

      xhr.send();

Some notes on loading PDF & printing in a new window.

  • Loading pdf in a new window via an iframe will work, but the print will not work if url is an external url.
  • Browser pop ups must be allowed, then only it will work.
  • If you try to load iframe from external url and try window.print() you will get empty print or elements which excludes iframe. But you can trigger print manually, which will work.

How to resize an image to a specific size in OpenCV?

You can use cvResize. Or better use c++ interface (eg cv::Mat instead of IplImage and cv::imread instead of cvLoadImage) and then use cv::resize which handles memory allocation and deallocation itself.

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

As already mentioned, compiling the app in x64 gives you far more available memory.

But in the case one must build an app in x86, there is a way to raise the memory limit from 1,2GB to 4GB (which is the actual limit for 32 bit processes):

In the VC/bin folder of the Visual Studio installation directory, there must be an editbin.exe file. So in my default installation I find it under

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\editbin.exe

In order to make the program work, maybe you must execute vcvars32.bat in the same directory first. Then a

editbin /LARGEADDRESSAWARE <your compiled exe file>

is enough to let your program use 4GB RAM. <your compiled exe file> is the exe, which VS generated while compiling your project.

If you want to automate this behavior every time you compile your project, use the following Post-Build event for the executed project:

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

Sidenote: The same can be done with the devenv.exe to let Visual Studio also use 4GB RAM instead of 1.2GB (but first backup the old devenv.exe).

Working with $scope.$emit and $scope.$on

Scope(s) can be used to propagate, dispatch event to the scope children or parent.

$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.

example index.html:

<div ng-app="appExample" ng-controller="EventCtrl">
      Root(Parent) scope count: {{count}}
  <div>
      <button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
      <button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>

      Childrent scope count: {{count}} 
  </div>
</div>

example app.js:

angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
  $scope.count = 0;
  $scope.$on('MyEvent', function() {
    $scope.count++;
  });
}]);

Here u can test code: http://jsfiddle.net/zp6v0rut/41/

How can I hide/show a div when a button is clicked?

Task can be made simple javascript without jQuery etc.

<script type="text/javascript">
function showhide() {
document.getElementById("wizard").className = (document.getElementById("wizard").className=="swMain") ? swHide : swMain;
}
</script>

This function is simple if statement that looks if wizard has class swMain and change class to swHide and else if it's not swMain then change to swMain. This code doesn't support multiple class attributes but in this case it is just enough.

Now you have to make css class named swHide that has display: none

Then add on to the button onclick="showhide()"

So easy it is.

Getting Textarea Value with jQuery

you have id="#message"... should be id="message"

http://jsfiddle.net/q5EXG/1/

NodeJS w/Express Error: Cannot GET /

You typically want to render templates like this:

app.get('/', function(req, res){
  res.render('index.ejs');
});

However you can also deliver static content - to do so use:

app.use(express.static(__dirname + '/public'));

Now everything in the /public directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm in the public folder if will be available by visiting /default.htm

Take a look through the express API and Connect Static middleware docs for more info.

How to get week number in Python?

A lot of answers have been given, but id like to add to them.

If you need the week to display as a year/week style (ex. 1953 - week 53 of 2019, 2001 - week 1 of 2020 etc.), you can do this:

import datetime

year = datetime.datetime.now()
week_num = datetime.date(year.year, year.month, year.day).strftime("%V")
long_week_num = str(year.year)[0:2] + str(week_num)

It will take the current year and week, and long_week_num in the day of writing this will be:

>>> 2006

Android: ProgressDialog.show() crashes with getApplicationContext

A dialog is always created and displayed as a part of an Activity. You need to pass in an Activity context instead of the Application context.

http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog

How do I disable a jquery-ui draggable?

The following is what this would look like inside of .draggable({});

$("#yourDraggable").draggable({
    revert: "invalid" ,
    start: function(){ 
        $(this).css("opacity",0.3);
    },
    stop: function(){ 
        $(this).draggable( 'disable' )
    },
    opacity: 0.7,
    helper: function () { 
        $copy = $(this).clone(); 
        $copy.css({
            "list-style":"none",
            "width":$(this).outerWidth()
        }); 
        return $copy; 
    },
    appendTo: 'body',
    scroll: false
});

HTML Button : Navigate to Other Page - Different Approaches

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

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

How can I start PostgreSQL on Windows?

I found using

net start postgres_service_name

the only reliable way to operate Postgres on Windows

What is IllegalStateException?

Illegal State Exception is an Unchecked exception.

It indicate that method has been invoked at wrong time.

example:

Thread t = new Thread();
t.start();
//
//
t.start();

output:

Runtime Excpetion: IllegalThreadStateException

We cant start the Thread again, it will throw IllegalStateException.

Fastest way to convert Image to Byte array

There is a RawFormat property of Image parameter which returns the file format of the image. You might try the following:

// extension method
public static byte[] imageToByteArray(this System.Drawing.Image image)
{
    using(var ms = new MemoryStream())
    {
        image.Save(ms, image.RawFormat);
        return ms.ToArray();
    }
}

How large is a DWORD with 32- and 64-bit code?

No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Other type of format :

$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';

curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Find number of decimal places in decimal value regardless of culture

Since none of the answers supplied were good enough for the magic number "-0.01f" converted to decimal.. i.e: GetDecimal((decimal)-0.01f);
I can only assume a colossal mind-fart virus attacked everyone 3 years ago :)
Here is what seems to be a working implementation to this evil and monstrous problem, the very complicated problem of counting the decimal places after the point - no strings, no cultures, no need to count the bits and no need to read math forums.. just simple 3rd grade math.

public static class MathDecimals
{
    public static int GetDecimalPlaces(decimal n)
    {
        n = Math.Abs(n); //make sure it is positive.
        n -= (int)n;     //remove the integer part of the number.
        var decimalPlaces = 0;
        while (n > 0)
        {
            decimalPlaces++;
            n *= 10;
            n -= (int)n;
        }
        return decimalPlaces;
    }
}

private static void Main(string[] args)
{
    Console.WriteLine(1/3m); //this is 0.3333333333333333333333333333
    Console.WriteLine(1/3f); //this is 0.3333333

    Console.WriteLine(MathDecimals.GetDecimalPlaces(0.0m));                  //0
    Console.WriteLine(MathDecimals.GetDecimalPlaces(1/3m));                  //28
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)(1 / 3f)));     //7
    Console.WriteLine(MathDecimals.GetDecimalPlaces(-1.123m));               //3
    Console.WriteLine(MathDecimals.GetDecimalPlaces(43.12345m));             //5
    Console.WriteLine(MathDecimals.GetDecimalPlaces(0));                     //0
    Console.WriteLine(MathDecimals.GetDecimalPlaces(0.01m));                 //2
    Console.WriteLine(MathDecimals.GetDecimalPlaces(-0.001m));               //3
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)-0.00000001f)); //8
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)0.0001234f));   //7
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)0.01f));        //2
    Console.WriteLine(MathDecimals.GetDecimalPlaces((decimal)-0.01f));       //2
}

Select distinct values from a large DataTable column

Method 1:

   DataView view = new DataView(table);
   DataTable distinctValues = view.ToTable(true, "id");

Method 2: You will have to create a class matching your datatable column names and then you can use the following extension method to convert Datatable to List

    public static List<T> ToList<T>(this DataTable table) where T : new()
    {
        List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        List<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }

    private static T CreateItemFromRow<T>(DataRow row, List<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            if (row.Table.Columns.Contains(property.Name))
            {
                if (row[property.Name] != DBNull.Value)
                    property.SetValue(item, row[property.Name], null);
            }
        }
        return item;
    }

and then you can get distinct from list using

      YourList.Select(x => x.Id).Distinct();

Please note that this will return you complete Records and not just ids.

HTML table with fixed headers and a fixed column?

The jQuery DataTables plug-in is one excellent way to achieve excel-like fixed column(s) and headers.

Note the examples section of the site and the "extras".
http://datatables.net/examples/
http://datatables.net/extras/

The "Extras" section has tools for fixed columns and fixed headers.

Fixed Columns
http://datatables.net/extras/fixedcolumns/
(I believe the example on this page is the one most appropriate for your question.)

Fixed Header
http://datatables.net/extras/fixedheader/
(Includes an example with a full page spreadsheet style layout: http://datatables.net/release-datatables/extras/FixedHeader/top_bottom_left_right.html)

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

Java, Shifting Elements in an Array

Another variation if you have the array data as a Java-List

    listOfStuff.add( 
            0, 
            listOfStuff.remove(listOfStuff.size() - 1) );

Just sharing another option I ran across for this, but I think the answer from @Murat Mustafin is the way to go with a list

Iterate a certain number of times without storing the iteration number anywhere

This will print 'hello' 3 times without storing i...

[print('hello') for i in range(3)]

exception in initializer error in java when using Netbeans

Wherever there is errors or exceptions in static blocks, this exception will be thrown. To get the cause of this exception simply use Throwable.getCause() to know what is wrong.

C# Creating an array of arrays

This loops vertically but might work for you.

int rtn = 0;    
foreach(int[] L in lists){
    for(int i = 0; i<L.Length;i++){
          rtn = L[i];
      //Do something with rtn
    }
}

Multiple GitHub Accounts & SSH Config

I recently had to do this and had to sift through all these answers and their comments to eventually piece the information together, so I'll put it all here, in one post, for your convenience:


Step 1: ssh keys
Create any keypairs you'll need. In this example I've named me default/original 'id_rsa' (which is the default) and my new one 'id_rsa-work':

ssh-keygen -t rsa -C "[email protected]"


Step 2: ssh config
Set up multiple ssh profiles by creating/modifying ~/.ssh/config. Note the slightly differing 'Host' values:

# Default GitHub
Host github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa

# Work GitHub
Host work.github.com
    HostName github.com
    PreferredAuthentications publickey
    IdentityFile ~/.ssh/id_rsa_work


Step 3: ssh-add
You may or may not have to do this. To check, list identity fingerprints by running:

$ ssh-add -l
2048 1f:1a:b8:69:cd:e3:ee:68:e1:c4:da:d8:96:7c:d0:6f stefano (RSA)
2048 6d:65:b9:3b:ff:9c:5a:54:1c:2f:6a:f7:44:03:84:3f [email protected] (RSA)

If your entries aren't there then run:

ssh-add ~/.ssh/id_rsa_work


Step 4: test
To test you've done this all correctly, I suggest the following quick check:

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

$ ssh -T [email protected]
Hi stefano! You've successfully authenticated, but GitHub does not provide shell access.

Note that you'll have to change the hostname (github / work.github) depending on what key/identity you'd like to use. But now you should be good to go! :)

How do I check whether an array contains a string in TypeScript?

do like this:

departments: string[]=[];
if(this.departments.indexOf(this.departmentName.trim()) >-1 ){
            return;
    }

Setting dropdownlist selecteditem programmatically

Safety check to only select if an item is matched.

//try to find item in list.  
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;

How to use _CRT_SECURE_NO_WARNINGS

Add by

Configuration Properties>>C/C++>>Preporocessor>>Preprocessor Definitions>> _CRT_SECURE_NO_WARNINGS

screenshot of the relevant config interface

target input by type and name (selector)

You want a multiple attribute selector

$("input[type='checkbox'][name='ProductCode']").each(function(){ ...

or

$("input:checkbox[name='ProductCode']").each(function(){ ...

It would be better to use a CSS class to identify those that you want to select however as a lot of the modern browsers implement the document.getElementsByClassName method which will be used to select elements and be much faster than selecting by the name attribute

How do I check if file exists in jQuery or pure JavaScript?

What you'd have to do is send a request to the server for it to do the check, and then send back the result to you.

What type of server are you trying to communicate with? You may need to write a small service to respond to the request.

How to get the first and last date of the current year?

To get the first and the last day of the year, one can use the CONCAT function. The resulting value may be cast to any type.

CONCAT(YEAR(Getdate()),'-01-01') FirstOfYear,
CONCAT(YEAR(GETDATE()),'-12-31') LastOfYear

How to remove duplicate white spaces in string using Java?

String str = "   Text    with    multiple    spaces    ";
str = org.apache.commons.lang3.StringUtils.normalizeSpace(str);
// str = "Text with multiple spaces"

How to make a 3D scatter plot in Python?

Use the following code it worked for me:

# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]

# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

plt.show()

while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.

Bootstrap datepicker disabling past dates without current date

var date = new Date();
date.setDate(date.getDate()-1);

$('#date').datepicker({ 
    startDate: date
});

How to use mouseover and mouseout in Angular 6

<div (mouseenter)="changeText=true" (mouseout)="changeText=false">
  <span *ngIf="!changeText">Hide</span>
  <span *ngIf="changeText">Show</span>
</div>

and if you want to use in *ngFor then assign the object value of hover data and then check its id and show hover info/icon or anything like that:-

 <div (mouseenter)="hoverCard(d)" (mouseleave)="hoverCard(null)" *ngFor="let d of data" class="col-lg-3 col-md-4 col-sm-6 mt-4">
   <a *ngIf="hoverData && hoverData.id == d.id" class="text-right"><i class="fas fa-edit"></i>Hover Text</a>
    Normal Text
  </div>

in TS File

  hoverData!:Data|null;

  hoverCard(d: Data|null){
    this.hoverData = sCatg;
  }

Choosing the default value of an Enum type without having to change values

An enum's default is whatever enumeration equates to zero. I don't believe this is changeable by attribute or other means.

(MSDN says: "The default value of an enum E is the value produced by the expression (E)0.")

Difference between a class and a module

+-----------------------------------------------------------------------------+
¦               ¦ class                     ¦ module                          ¦
¦---------------+---------------------------+---------------------------------¦
¦ instantiation ¦ can be instantiated       ¦ can *not* be instantiated       ¦
¦---------------+---------------------------+---------------------------------¦
¦ usage         ¦ object creation           ¦ mixin facility. provide         ¦
¦               ¦                           ¦   a namespace.                  ¦
¦---------------+---------------------------+---------------------------------¦
¦ superclass    ¦ module                    ¦ object                          ¦
¦---------------+---------------------------+---------------------------------¦
¦ methods       ¦ class methods and         ¦ module methods and              ¦
¦               ¦   instance methods        ¦   instance methods              ¦
¦---------------+---------------------------+---------------------------------¦
¦ inheritance   ¦ inherits behaviour and can¦ No inheritance                  ¦
¦               ¦   be base for inheritance ¦                                 ¦
¦---------------+---------------------------+---------------------------------¦
¦ inclusion     ¦ cannot be included        ¦ can be included in classes and  ¦
¦               ¦                           ¦   modules by using the include  ¦
¦               ¦                           ¦   command (includes all         ¦
¦               ¦                           ¦   instance methods as instance  ¦
¦               ¦                           ¦   methods in a class/module)    ¦
¦---------------+---------------------------+---------------------------------¦
¦ extension     ¦ can not extend with       ¦ module can extend instance by   ¦
¦               ¦   extend command          ¦   using extend command (extends ¦
¦               ¦   (only with inheritance) ¦   given instance with singleton ¦
¦               ¦                           ¦   methods from module)          ¦
+-----------------------------------------------------------------------------+

Change a Django form field to a hidden field

an option that worked for me, define the field in the original form as:

forms.CharField(widget = forms.HiddenInput(), required = False)

then when you override it in the new Class it will keep it's place.

Swift programmatically navigate to another view controller/scene

OperationQueue.main.addOperation {
   let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
   let newViewController = storyBoard.instantiateViewController(withIdentifier: "Storyboard ID") as! NewViewController
   self.present(newViewController, animated: true, completion: nil)
}

It worked for me when I put the code inside of the OperationQueue.main.addOperation, that will execute in the main thread for me.

How to change the Text color of Menu item in Android?

The short answer is YES. lucky you!
To do so, you need to override some styles of the Android default styles :

First, look at the definition of the themes in Android :

<style name="Theme.IconMenu">
<!-- Menu/item attributes -->
<item name="android:itemTextAppearance">@android:style/TextAppearance.Widget.IconMenu.Item</item>
<item name="android:itemBackground">@android:drawable/menu_selector</item>
<item name="android:itemIconDisabledAlpha">?android:attr/disabledAlpha</item>
<item name="android:horizontalDivider">@android:drawable/divider_horizontal_bright</item>
<item name="android:verticalDivider">@android:drawable/divider_vertical_bright</item>
<item name="android:windowAnimationStyle">@android:style/Animation.OptionsPanel</item>
<item name="android:moreIcon">@android:drawable/ic_menu_more</item>
<item name="android:background">@null</item>
</style>

So, the appearance of the text in the menu is in @android:style/TextAppearance.Widget.IconMenu.Item
Now, in the definition of the styles :

<style name="TextAppearance.Widget.IconMenu.Item" parent="TextAppearance.Small">
<item name="android:textColor">?textColorPrimaryInverse</item>
</style>

So now we have the name of the color in question, if you look in the color folder of the resources of the system :

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@android:color/bright_foreground_light_disabled" /> 
<item android:state_window_focused="false" android:color="@android:color/bright_foreground_light" /> 
<item android:state_pressed="true" android:color="@android:color/bright_foreground_light" /> 
<item android:state_selected="true" android:color="@android:color/bright_foreground_light" /> 
<item android:color="@android:color/bright_foreground_light" /> 
<!--  not selected --> 
</selector>

Finally, here is what you need to do :

Override "TextAppearance.Widget.IconMenu.Item" and create your own style. Then link it to your own selector to make it the way you want. Hope this helps you. Good luck!

Sum one number to every element in a list (or array) in Python

try this. (I modified the example on the purpose of making it non trivial)

import operator
import numpy as np

n=10
a = list(range(n))
a1 = [1]*len(a)
an = np.array(a)

operator.add is almost more than two times faster

%timeit map(operator.add, a, a1)

than adding with numpy

%timeit an+1

Update OpenSSL on OS X with Homebrew

I had this issue and found that the installation of the newer openssl did actually work, but my PATH was setup incorrectly for it -- my $PATH had the ports path placed before my brew path so it always found the older version of openssl.

The fix for me was to put the path to brew (/usr/local/bin) at the front of my $PATH.

To find out where you're loading openssl from, run which openssl and note the output. It will be the location of the version your system is using when you run openssl. Its going to be somewhere other than the brewpath of "/usr/local/bin". Change your $PATH, close that terminal tab and open a new one, and run which openssl. You should see a different path now, probably under /usr/local/bin. Now run openssl version and you should see the new version you installed "OpenSSL 1.0.1e 11 Feb 2013".

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

Calling Oracle stored procedure from C#?

This Code works well for me calling oracle stored procedure

Add references by right clicking on your project name in solution explorer >Add Reference >.Net then Add namespaces.

using System.Data.OracleClient;
using System.Data;

then paste this code in event Handler

        string str = "User ID=username;Password=password;Data Source=Test";
        OracleConnection conn = new OracleConnection(str);
        OracleCommand cmd = new OracleCommand("stored_procedure_name", conn);
        cmd.CommandType = CommandType.StoredProcedure;
        --Ad parameter list--
        cmd.Parameters.Add("parameter_name", "varchar2").Value = value;
        ....
        conn.Open();
        cmd.ExecuteNonQuery();

And its Done...Happy Coding with C#

Create an empty data.frame

If you already have an existent data frame, let's say df that has the columns you want, then you can just create an empty data frame by removing all the rows:

empty_df = df[FALSE,]

Notice that df still contains the data, but empty_df doesn't.

I found this question looking for how to create a new instance with empty rows, so I think it might be helpful for some people.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.

You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

How to print a float with 2 decimal places in Java?

To print a float up to 2 decimal places in Java:

    float f = (float)11/3;
    System.out.print(String.format("%.2f",f));

OUTPUT: 3.67

> use %.3f for up to three decimal places.

Android ListView selected item stay highlighted

To hold the color of listview item when you press it, include the following line in your listview item layout:

android:background="@drawable/bg_key"

Then define bg_key.xml in drawable folder like this:

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
        android:state_selected="true"
        android:drawable="@color/pressed_color"/>
    <item
        android:drawable="@color/default_color" />
</selector>

Finally, include this in your ListView onClickListener:

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
        view.setSelected(true);
        ... // Anything
    }
});

This way, only one item will be color-selected at any time. You can define your color values in res/values/colors.xml with something like this:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="pressed_color">#4d90fe</color>
    <color name="default_color">#ffffff</color>
</resources>

Eclipse, regular expression search and replace

For someone who needs an explanation and an example of how to use a regxp in Eclipse. Here is my example illustrating the problem.

enter image description here

I want to rename

/download.mp4^lecture_id=271

to

/271.mp4

And there can be multiple of these.

Here is how it should be done.

enter image description here

Then hit find/replace button

How to get the next auto-increment id in mysql

In PHP you can try this:

$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;

OR

$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];

How to determine if Javascript array contains an object with an attribute that equals a given value?

Testing for array elements:

JS Offers array functions which allow you to achieve this relatively easily. They are the following:

  1. Array.prototype.filter: Takes a callback function which is a test, the array is then iterated over with is callback and filtered according to this callback. A new filtered array is returned.
  2. Array.prototype.some: Takes a callback function which is a test, the array is then iterated over with is callback and if any element passes the test, the boolean true is returned. Otherwise false is returned

The specifics are best explained via an example:

Example:

_x000D_
_x000D_
vendors = [_x000D_
    {_x000D_
      Name: 'Magenic',_x000D_
      ID: 'ABC'_x000D_
     },_x000D_
    {_x000D_
      Name: 'Microsoft',_x000D_
      ID: 'DEF'_x000D_
    } //and so on goes array... _x000D_
];_x000D_
_x000D_
// filter returns a new array, we instantly check if the length _x000D_
// is longer than zero of this newly created array_x000D_
if (vendors.filter(company => company.Name === 'Magenic').length ) {_x000D_
  console.log('I contain Magenic');_x000D_
}_x000D_
_x000D_
// some would be a better option then filter since it directly returns a boolean_x000D_
if (vendors.some(company => company.Name === 'Magenic')) {_x000D_
  console.log('I also contain Magenic');_x000D_
}
_x000D_
_x000D_
_x000D_

Browser support:

These 2 function are ES6 function, not all browsers might support them. To overcome this you can use a polyfill. Here is the polyfill for Array.prototype.some (from MDN):

_x000D_
_x000D_
if (!Array.prototype.some) {_x000D_
  Array.prototype.some = function(fun, thisArg) {_x000D_
    'use strict';_x000D_
_x000D_
    if (this == null) {_x000D_
      throw new TypeError('Array.prototype.some called on null or undefined');_x000D_
    }_x000D_
_x000D_
    if (typeof fun !== 'function') {_x000D_
      throw new TypeError();_x000D_
    }_x000D_
_x000D_
    var t = Object(this);_x000D_
    var len = t.length >>> 0;_x000D_
_x000D_
    for (var i = 0; i < len; i++) {_x000D_
      if (i in t && fun.call(thisArg, t[i], i, t)) {_x000D_
        return true;_x000D_
      }_x000D_
    }_x000D_
_x000D_
    return false;_x000D_
  };_x000D_
}
_x000D_
_x000D_
_x000D_

facebook: permanent Page Access Token?

In addition to mentioned methods it is worth mentioning that for server-to-server applications, you can also use this form of permanent access token: app_id|app_secret This type of access token is called App Token. It can generally be used to call Graph API and query for public nodes within your application back-end. It is mentioned here: https://developers.facebook.com/docs/facebook-login/access-tokens

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

You can use --add-modules=java.xml.bind JVM option to add xml bind module to JVM run-time environment.

Eg: java --add-modules=java.xml.bind XmlTestClass

Jersey Exception : SEVERE: A message body reader for Java class

just put this

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

HttpClient - A task was cancelled?

in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception

My solution is

catch (Exception ex)
            {
                if (ex.InnerException is TimeoutException)
                {
                    ex = ex.InnerException;
                }
                else if (ex is TaskCanceledException)
                {
                    if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                    {
                        ex = new TimeoutException("Timeout occurred");
                    }
                }                
                Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);
            }

add controls vertically instead of horizontally using flow layout

I hope what you are trying to achieve is like this. For this please use Box layout.

package com.kcing.kailas.sample.client;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

public class Testing extends JFrame {

    private JPanel jContentPane = null;

    public Testing() {
        super();
        initialize();
    }

    private void initialize() {
        this.setSize(300, 200);
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
    }

    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(null);

            JPanel panel = new JPanel();

            panel.setBounds(61, 11, 81, 140);
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            jContentPane.add(panel);

            JCheckBox c1 = new JCheckBox("Check1");
            panel.add(c1);
            c1 = new JCheckBox("Check2");
            panel.add(c1);
            c1 = new JCheckBox("Check3");
            panel.add(c1);
            c1 = new JCheckBox("Check4");
            panel.add(c1);
        }
        return jContentPane;
    }

    public static void main(String[] args) throws Exception {
        Testing frame = new Testing();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
}

how to force maven to update local repo

Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.

Press CTRL+Shift+A to open up the Actions menu. Type Maven and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line

How to get the integer value of day of week

int day = (int)DateTime.Now.DayOfWeek;

First day of the week: Sunday (with a value of zero)

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put the line $this->db->order_by("course_name","desc"); at top of your query. Like

$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();

jQuery UI - Draggable is not a function?

I went through both your question and a another duplicate.
In the end, the following answer helped me sorting things out:
uncaught-typeerror-draggable-is-not-a-function

To get rid of :

$(".draggable").draggable is not a function anymore

I had to put links to Javascript libraries above the script tag I expected to be working.

My code:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" />

<script>
    $(function(){
        $("#container-speed").draggable();
    });
</script>

<div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="rowbackground"style="width: 600px; height: 400px; margin: 0 auto">
                <div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
                <div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
            </div>
        </div>
    </div>
</div>

Easy way to dismiss keyboard?

Quick tip on how to dismiss the keyboard in iOS when a user touches anywhere on the screen outside of the UITextField or keyboard. Considering how much real estate the iOS keyboard can take up, it makes sense to have an easy and intuitive way for your users to dismiss the keyboard.

Here's a link

Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

I had a hard time making this work too, the solution for me was to use both hyui and konstantin answers,

class ExampleTask extends AsyncTask<String, String, String> {

// Your onPreExecute method.

@Override
protected String doInBackground(String... params) {
    // Your code.
    if (condition_is_true) {
        this.publishProgress("Show the dialog");
    }
    return "Result";
}

@Override
protected void onProgressUpdate(String... values) {

    super.onProgressUpdate(values);
    YourActivity.this.runOnUiThread(new Runnable() {
       public void run() {
           alertDialog.show();
       }
     });
 }

}

Change image source in code behind - Wpf

The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.

You simply want to pass the actual path to the UriSource:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

How to check if a string contains a specific text

Do mean to check if $a is a non-empty string? So that it contains just any text? Then the following will work.

If $a contains a string, you can use the following:

if (!empty($a)) {      // Means: if not empty
    ...
}

If you also need to confirm that $a is actually a string, use:

if (is_string($a) && !empty($a)) {      // Means: if $a is a string and not empty
    ...
}

How to choose the id generation strategy when using JPA and Hibernate

Basically, you have two major choices:

  • You can generate the identifier yourself, in which case you can use an assigned identifier.
  • You can use the @GeneratedValue annotation and Hibernate will assign the identifier for you.

For the generated identifiers you have two options:

  • UUID identifiers.
  • Numerical identifiers.

For numerical identifiers you have three options:

  • IDENTITY
  • SEQUENCE
  • TABLE

IDENTITY is only a good choice when you cannot use SEQUENCE (e.g. MySQL) because it disables JDBC batch updates.

SEQUENCE is the preferred option, especially when used with an identifier optimizer like pooled or pooled-lo.

TABLE is to be avoided since it uses a separate transaction to fetch the identifier and row-level locks which scales poorly.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Context envContext = (Context)initContext.lookup("java:comp/env");

not:Context envContext = (Context)initContext.lookup("java:/comp/env");

How to exclude 0 from MIN formula Excel

if all your value are positive, you can do -max(-n)

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

In my case Github was down.

Maybe also check https://www.githubstatus.com/

You can subscribe to notifications per email and text to know when you can push your changes again.

How to properly upgrade node using nvm

Node.JS to install a new version.

Step 1 : NVM Install

npm i -g nvm

Step 2 : NODE Newest version install

nvm install *.*.*(NodeVersion)

Step 3 : Selected Node Version

nvm use *.*.*(NodeVersion)

Finish

How to resolve 'unrecognized selector sent to instance'?

How are you importing ClassA into your AppDelegate Class? Did you include the .h file in the main project? I had this problem for a while because I didn't copy the header file into the main project as well as the normal #include "ClassA.h."

Copying, or creating the .h solved it for me.

Cannot use mkdir in home directory: permission denied (Linux Lubuntu)

As @kirbyfan64sos notes in a comment, /home is NOT your home directory (a.k.a. home folder):

The fact that /home is an absolute, literal path that has no user-specific component provides a clue.

While /home happens to be the parent directory of all user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is /Users.

What all Unix platforms DO have in common are the following ways to navigate to / refer to your home directory:

  • Using cd with NO argument changes to your home dir., i.e., makes your home dir. the working directory.
    • e.g.: cd # changes to home dir; e.g., '/home/jdoe'
  • Unquoted ~ by itself / unquoted ~/ at the start of a path string represents your home dir. / a path starting at your home dir.; this is referred to as tilde expansion (see man bash)
    • e.g.: echo ~ # outputs, e.g., '/home/jdoe'
  • $HOME - as part of either unquoted or preferably a double-quoted string - refers to your home dir. HOME is a predefined, user-specific environment variable:
    • e.g.: cd "$HOME/tmp" # changes to your personal folder for temp. files

Thus, to create the desired folder, you could use:

mkdir "$HOME/bin"  # same as: mkdir ~/bin

Note that most locations outside your home dir. require superuser (root user) privileges in order to create files or directories - that's why you ran into the Permission denied error.

How to open a new tab in GNOME Terminal from command line?

For open multiple tabs in same terminal window you can go with following solution.

Example script:

pwd='/Users/pallavi/Documents/containers/platform241/etisalatwallet/api-server-tomcat-7/bin'
pwdlog='/Users/pallavi/Documents/containers/platform241/etisalatwallet/api-server-tomcat-7/logs'
pwd1='/Users/pallavi/Documents/containers/platform241/etisalatwallet/core-server-jboss-7.2/bin'
logpwd1='/Users/pallavi/Documents/containers/platform241/etisalatwallet/core-server-jboss-7.2/standalone/log'

osascript -e "tell application \"Terminal\"" \

-e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
-e "do script \"cd $pwd\" in front window" \
-e "do script \"./startup.sh\" in front window" \
-e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
-e "do script \"cd $pwdlog\" in front window" \
-e "do script \"tail -f catalina.out \" in front window" \
-e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
-e "do script \"cd $pwd1\" in front window" \
-e "do script \"./standalone.sh\" in front window" \
-e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
-e "do script \"cd $logpwd1\" in front window" \
-e "do script \"tail -f core.log \" in front window" \
-e "end tell"
> /dev/null 

Maven: best way of linking custom external JAR to my project?

You can create an In Project Repository, so you don't have to run mvn install:install-file every time you work on a new computer

<repository>
    <id>in-project</id>
    <name>In Project Repo</name>
    <url>file://${project.basedir}/libs</url>
</repository>

<dependency>
    <groupId>dropbox</groupId>
    <artifactId>dropbox-sdk</artifactId>
    <version>1.3.1</version>
</dependency>

/groupId/artifactId/version/artifactId-verion.jar

detail read this blog post

https://web.archive.org/web/20121026021311/charlie.cu.cc/2012/06/how-add-external-libraries-maven

How to turn off caching on Firefox?

First of All, this can be easily done, for e.g. by PHP to force the browser to renew files based on cache date (expiration time). If you just need it for experimental needs, then try to use ctrl+shift+del to clear all cache at once inside Firefox browser. The third solution is to use many add-ons that exits for Firefox to clear cache based on time lines.

This certificate has an invalid issuer Apple Push Services

This is not actually a development issue. It happens due to expiration of the Apple Worldwide Developer Relations Intermediate Certificate issued by Apple Worldwide Developer Relations Certificate Authority. WWDRCA issues the certificate to sign your software for Apple devices, allowing our systems to confirm that your software is delivered to users as intended and has not been modified.

To resolve this issue, you have to follow the below steps:

  1. Open Keychain Access
  2. Go to View -> Show Expired Certificates

Enter image description here

  1. Go to System in Keychain Enter image description here

  2. Here you find that "Apple Worldwide Developer Relations Certificate Authority" is marked as expired. So delete it. Also check under Login Tab and delete expired WWDRCA.

  3. Download new WWDR Intermediate Certificate from here(The renewed Apple Worldwide Developer Relations Certification Intermediate Certificate will expire on February 7, 2023).

  4. Install it by double clicking on it.

If you still face any issue with your iOS apps, Mac apps, Safari extensions, Apple Wallet and Safari push notifications, then please follow this link of expiration.

The Apple Worldwide Developer Relations Certification Intermediate Certificate expires soon and we've issued a renewed certificate that must be included when signing all new Apple Wallet Passes, push packages for Safari Push Notifications, and Safari Extensions starting February 14, 2016.

While most developers and users will not be affected by the certificate change, we recommend that all developers download and install the renewed certificate on their development systems and servers as a best practice. All apps will remain available on the App Store for iOS, Mac, and Apple TV.

CRON command to run URL address every 5 minutes

To run a url, you need a program to get that url. You can try wget or curl. See manuals for available options.

What is the quickest way to HTTP GET in Python?

Actually in Python we can read from HTTP responses like from files, here is an example for reading JSON from an API.

import json
from urllib.request import urlopen

with urlopen(url) as f:
    resp = json.load(f)

return resp['some_key']

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

Find and replace words/lines in a file

This is the sort of thing I'd normally use a scripting language for. It's very useful to have the ability to perform these sorts of transformations very simply using something like Ruby/Perl/Python (insert your favorite scripting language here).

I wouldn't normally use Java for this since it's too heavyweight in terms of development cycle/typing etc.

Note that if you want to be particular in manipulating XML, it's advisable to read the file as XML and manipulate it as such (the above scripting languages have very useful and simple APIs for doing this sort of work). A simple text search/replace can invalidate your file in terms of character encoding etc. As always, it depends on the complexity of your search/replace requirements.

When and why to 'return false' in JavaScript?

Also, this short and interesting link to read through https://www.w3schools.com/jsref/event_preventdefault.asp

Definition and Usage

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

For example, this can be useful when:

Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL

Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.

Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.

Nginx: Job for nginx.service failed because the control process exited

In my case, it's because of apache server is running somehow. So I stop apache then restart nginx. Work like a charm!

sudo /etc/init.d/apache2 stop
sudo systemctl restart nginx

Why would one mark local variables and method parameters as "final" in Java?

Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.

The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.

Edit

In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.

Create Directory if it doesn't exist with Ruby

Another simple way:

Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')

Show constraints on tables command

Analogous to @Resh32, but without the need to use the USE statement:

SELECT TABLE_NAME,
       COLUMN_NAME,
       CONSTRAINT_NAME,
       REFERENCED_TABLE_NAME,
       REFERENCED_COLUMN_NAME
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE TABLE_SCHEMA = "database_name" 
      AND TABLE_NAME = "table_name" 
      AND REFERENCED_COLUMN_NAME IS NOT NULL;

Useful, e.g. using the ORM.

How can I use onItemSelected in Android?

Another thing: When you have more than one spinner in your layout, you have to implement a switch selection in the onItemSlected() method to know which widget was clicked. Something like this:

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    switch (parent.getId()){
        case R.id.sp_alarmSelection:
            //Do something
            Toast.makeText(this, "Alarm Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.sp_optionSelection:
            //Do another thing 
            Toast.makeText(this, "Option Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
            break;
    }
}

better way to drop nan rows in pandas

To expand Hitesh's answer if you want to drop rows where 'x' specifically is nan, you can use the subset parameter. His answer will drop rows where other columns have nans as well

dat.dropna(subset=['x'])

JSON formatter in C#?

Just use JsonDocument and Utf8JsonWriter. No third-party library required. No target object for deserialization for jsonString required.

using System.IO;
using System.Text;
using System.Text.Json;

// other code ...

public string Prettify(string jsonString)
{
    using var stream = new MemoryStream();
    var document = JsonDocument.Parse(jsonString);
    var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
    document.WriteTo(writer);
    writer.Flush();
    return Encoding.UTF8.GetString(stream.ToArray());
}

C++11 reverse range-based for-loop

If not using C++14, then I find below the simplest solution.

#define METHOD(NAME, ...) auto NAME __VA_ARGS__ -> decltype(m_T.r##NAME) { return m_T.r##NAME; }
template<typename T>
struct Reverse
{
  T& m_T;

  METHOD(begin());
  METHOD(end());
  METHOD(begin(), const);
  METHOD(end(), const);
};
#undef METHOD

template<typename T>
Reverse<T> MakeReverse (T& t) { return Reverse<T>{t}; }

Demo.
It doesn't work for the containers/data-types (like array), which doesn't have begin/rbegin, end/rend functions.

Difference between PCDATA and CDATA in DTD

CDATA (Character DATA): It is similarly to a comment but it is part of document. i.e. CDATA is a data, it is part of the document but the data can not parsed in XML.
Note: XML comment omits while parsing an XML but CDATA shows as it is.

PCDATA (Parsed Character DATA) :By default, everything is PCDATA. PCDATA is a data, it can be parsed in XML.

jQuery UI DatePicker to show month year only

Thanks for Ben Koehler's solution.

However, I had a problem with multiple instances of datepickers, with some of them needed with day selection. Ben Koehler's solution (in edit 3) works, but hides the day selection in all instances. Here's an update that solves this issue :

$('.date-picker').datepicker({
    dateFormat: "mm/yy",
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    onClose: function(dateText, inst) {
        if($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1) {
            $(this).datepicker(
                'setDate',
                new Date(
                    $("#ui-datepicker-div .ui-datepicker-year :selected").val(),
                    $("#ui-datepicker-div .ui-datepicker-month :selected").val(),
                    1
                )
            ).trigger('change');
            $('.date-picker').focusout();
        }
        $("#ui-datepicker-div").removeClass("month_year_datepicker");
    },
    beforeShow : function(input, inst) {
        if((datestr = $(this).val()).length > 0) {
            year = datestr.substring(datestr.length-4, datestr.length);
            month = datestr.substring(0, 2);
            $(this).datepicker('option', 'defaultDate', new Date(year, month-1, 1));
            $(this).datepicker('setDate', new Date(year, month-1, 1));
            $("#ui-datepicker-div").addClass("month_year_datepicker");
        }
    }
});

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

that's why Idon't like NULL values in the database at all.
I hope you are having it for a reason.

if ($_POST['location_id'] === '') {
  $location_id = 'NULL';
} else {
  $location_id = "'".$_POST['location_id']."'";
}
$notes = mysql_real_escape_string($_POST['notes']);
$ipid  = mysql_real_escape_string($_POST['ipid']);

$sql="UPDATE addresses 
    SET notes='$notes', location_id=$location_id
    WHERE ipid = '$ipid'";

echo $sql; //to see different queries this code produces
// and difference between NULL and 'NULL' in the query

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Replace multiple strings with multiple other strings

Use numbered items to prevent replacing again. eg

let str = "I have a %1, a %2, and a %3";
let pets = ["dog","cat", "goat"];

then

str.replace(/%(\d+)/g, (_, n) => pets[+n-1])

How it works:- %\d+ finds the numbers which come after a %. The brackets capture the number.

This number (as a string) is the 2nd parameter, n, to the lambda function.

The +n-1 converts the string to the number then 1 is subtracted to index the pets array.

The %number is then replaced with the string at the array index.

The /g causes the lambda function to be called repeatedly with each number which is then replaced with a string from the array.

In modern JavaScript:-

replace_n=(str,...ns)=>str.replace(/%(\d+)/g,(_,n)=>ns[n-1])

Create a user with all privileges in Oracle

My issue was, i am unable to create a view with my "scott" user in oracle 11g edition. So here is my solution for this

Error in my case

SQL>create view v1 as select * from books where id=10;

insufficient privileges.

Solution

1)open your cmd and change your directory to where you install your oracle database. in my case i was downloaded in E drive so my location is E:\app\B_Amar\product\11.2.0\dbhome_1\BIN> after reaching in the position you have to type sqlplus sys as sysdba

E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

2) Enter password: here you have to type that password that you give at the time of installation of oracle software.

3) Here in this step if you want create a new user then you can create otherwise give all the privileges to existing user.

for creating new user

SQL> create user abc identified by xyz;

here abc is user and xyz is password.

giving all the privileges to abc user

SQL> grant all privileges to abc;

 grant succeeded. 

if you are seen this message then all the privileges are giving to the abc user.

4) Now exit from cmd, go to your SQL PLUS and connect to the user i.e enter your username & password.Now you can happily create view.

In My case

in cmd E:\app\B_Amar\product\11.2.0\dbhome_1\BIN>sqlplus sys as sysdba

SQL> grant all privileges to SCOTT;

grant succeeded.

Now I can create views.

Convert a tensor to numpy array in Tensorflow?

You can convert a tensor in tensorflow to numpy array in the following ways.

First: Use np.array(your_tensor)

Second: Use your_tensor.numpy

SQLiteDatabase.query method

if your SQL query is like this

SELECT col-1, col-2 FROM tableName WHERE col-1=apple,col-2=mango
GROUPBY col-3 HAVING Count(col-4) > 5  ORDERBY col-2 DESC LIMIT 15;

Then for query() method, we can do as:-

String table = "tableName";
String[] columns = {"col-1", "col-2"};
String selection = "col-1 =? AND col-2=?";       
String[] selectionArgs = {"apple","mango"};
String groupBy =col-3;
String having =" COUNT(col-4) > 5";
String orderBy = "col-2 DESC";
String limit = "15";

query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

Pass parameter to controller from @Html.ActionLink MVC 4

You can pass values by using the below .

@Html.ActionLink("About", "About", "Home",new { name = ViewBag.Name }, htmlAttributes:null )

Controller:

public ActionResult About(string name)
        {
            ViewBag.Message = "Your application description page.";
            ViewBag.NameTransfer = name;
            return View();
        }

And the URL looks like

http://localhost:50297/Home/About?name=My%20Name%20is%20Vijay

Insert string at specified position

function insSubstr($str, $sub, $posStart, $posEnd){
  return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}

Detect if the device is iPhone X

For a quick fix, I like this:

let var:CGFloat = (UIDevice.current.userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height == 2436) ? <iPhoneX> : <AllOthers>

What is copy-on-write?

Just to provide another example, Mercurial uses copy-on-write to make cloning local repositories a really "cheap" operation.

The principle is the same as the other examples, except that you're talking about physical files instead of objects in memory. Initially, a clone is not a duplicate but a hard link to the original. As you change files in the clone, copies are written to represent the new version.

Is there an Eclipse plugin to run system shell in the Console?

Add C:\Windows\System32\cmd.exe as an external tool. Once run, you can then access it via the normal eclipse console.

http://www.avajava.com/tutorials/lessons/how-do-i-open-a-windows-command-prompt-in-my-console.html


(source: avajava.com)

How to import js-modules into TypeScript file?

I tested 3 methods to do that...

Method1:

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

Method2:

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

Method3:

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

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

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

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

Is there a max array length limit in C++?

Looking at it from a practical rather than theoretical standpoint, on a 32 bit Windows system, the maximum total amount of memory available for a single process is 2 GB. You can break the limit by going to a 64 bit operating system with much more physical memory, but whether to do this or look for alternatives depends very much on your intended users and their budgets. You can also extend it somewhat using PAE.

The type of the array is very important, as default structure alignment on many compilers is 8 bytes, which is very wasteful if memory usage is an issue. If you are using Visual C++ to target Windows, check out the #pragma pack directive as a way of overcoming this.

Another thing to do is look at what in memory compression techniques might help you, such as sparse matrices, on the fly compression, etc... Again this is highly application dependent. If you edit your post to give some more information as to what is actually in your arrays, you might get more useful answers.

Edit: Given a bit more information on your exact requirements, your storage needs appear to be between 7.6 GB and 76 GB uncompressed, which would require a rather expensive 64 bit box to store as an array in memory in C++. It raises the question why do you want to store the data in memory, where one presumes for speed of access, and to allow random access. The best way to store this data outside of an array is pretty much based on how you want to access it. If you need to access array members randomly, for most applications there tend to be ways of grouping clumps of data that tend to get accessed at the same time. For example, in large GIS and spatial databases, data often gets tiled by geographic area. In C++ programming terms you can override the [] array operator to fetch portions of your data from external storage as required.

Execute curl command within a Python script

You can use below code snippet

import shlex
import subprocess
import json

def call_curl(curl):
    args = shlex.split(curl)
    process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    return json.loads(stdout.decode('utf-8'))


if __name__ == '__main__':
    curl = '''curl - X
    POST - d
    '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
    http: // localhost: 8080 / firewall / rules / 0000000000000001 '''
    output = call_curl(curl)
    print(output)

Can I run javascript before the whole page is loaded?

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

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

Get remote registry value

For remote registry you have to use .NET with powershell 2.0

$w32reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$computer1)
$keypath = 'SOFTWARE\Veritas\NetBackup\CurrentVersion'
$netbackup = $w32reg.OpenSubKey($keypath)
$NetbackupVersion1 = $netbackup.GetValue('PackageVersion')

Setting HttpContext.Current.Session in a unit test

Try this:

        // MockHttpSession Setup
        var session = new MockHttpSession();

        // MockHttpRequest Setup - mock AJAX request
        var httpRequest = new Mock<HttpRequestBase>();

        // Setup this part of the HTTP request for AJAX calls
        httpRequest.Setup(req => req["X-Requested-With"]).Returns("XMLHttpRequest");

        // MockHttpContextBase Setup - mock request, cache, and session
        var httpContext = new Mock<HttpContextBase>();
        httpContext.Setup(ctx => ctx.Request).Returns(httpRequest.Object);
        httpContext.Setup(ctx => ctx.Cache).Returns(HttpRuntime.Cache);
        httpContext.Setup(ctx => ctx.Session).Returns(session);

        // MockHttpContext for cache
        var contextRequest = new HttpRequest("", "http://localhost/", "");
        var contextResponse = new HttpResponse(new StringWriter());
        HttpContext.Current = new HttpContext(contextRequest, contextResponse);

        // MockControllerContext Setup
        var context = new Mock<ControllerContext>();
        context.Setup(ctx => ctx.HttpContext).Returns(httpContext.Object);

        //TODO: Create new controller here
        //      Set controller's ControllerContext to context.Object

And Add the class:

public class MockHttpSession : HttpSessionStateBase
{
    Dictionary<string, object> _sessionDictionary = new Dictionary<string, object>();
    public override object this[string name]
    {
        get
        {
            return _sessionDictionary.ContainsKey(name) ? _sessionDictionary[name] : null;
        }
        set
        {
            _sessionDictionary[name] = value;
        }
    }

    public override void Abandon()
    {
        var keys = new List<string>();

        foreach (var kvp in _sessionDictionary)
        {
            keys.Add(kvp.Key);
        }

        foreach (var key in keys)
        {
            _sessionDictionary.Remove(key);
        }
    }

    public override void Clear()
    {
        var keys = new List<string>();

        foreach (var kvp in _sessionDictionary)
        {
            keys.Add(kvp.Key);
        }

        foreach(var key in keys)
        {
            _sessionDictionary.Remove(key);
        }
    }
}

This will allow you to test with both session and cache.

How to Get XML Node from XDocument

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Contacts>
  <Node>
    <ID>123</ID>
    <Name>ABC</Name>
  </Node>
  <Node>
    <ID>124</ID>
    <Name>DEF</Name>
  </Node>
</Contacts>

Select a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123"; // id to be selected

XElement Contact = (from xml2 in XMLDoc.Descendants("Node")
                    where xml2.Element("ID").Value == id
                    select xml2).FirstOrDefault();

Console.WriteLine(Contact.ToString());

Delete a single node:

XDocument XMLDoc = XDocument.Load("test.xml");
string id = "123";

var Contact = (from xml2 in XMLDoc.Descendants("Node")
               where xml2.Element("ID").Value == id
               select xml2).FirstOrDefault();

Contact.Remove();
XMLDoc.Save("test.xml");

Add new node:

XDocument XMLDoc = XDocument.Load("test.xml");

XElement newNode = new XElement("Node",
    new XElement("ID", "500"),
    new XElement("Name", "Whatever")
);

XMLDoc.Element("Contacts").Add(newNode);
XMLDoc.Save("test.xml");

cout is not a member of std

Also remember that it must be:

#include "stdafx.h"
#include <iostream>

and not the other way around

#include <iostream>
#include "stdafx.h"

Select all elements with a "data-xxx" attribute without using jQuery

Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:

It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.

ImportError: No Module Named bs4 (BeautifulSoup)

I will advise you to uninstall the bs4 library by using this command:

pip uninstall bs4

and then install it using this command:

sudo apt-get install python3-bs4

I was facing the same problem in my Linux Ubuntu when I used the following command for installing bs4 library:

pip install bs4

What is an Endpoint?

An endpoint is a URL pattern used to communicate with an API.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Set default encoder at the top of your code

import sys
reload(sys)
sys.setdefaultencoding("ISO-8859-1")

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

presentViewController and displaying navigation bar

If you didn't set the modalPresentationStyle property (like to UIModalPresentationFormSheet), the navigation bar will be displayed always. To ensure, always do

[[self.navigationController topViewController] presentViewController:vieController 
                                                            animated:YES 
                                                          completion:nil];

This will show the navigation bar always.

How to reload a page using Angularjs?

You can also try this, after injecting $window service.

$window.location.reload();

How to permanently export a variable in Linux?

add the line to your .bashrc or .profile. The variables set in $HOME/.profile are active for the current user, the ones in /etc/profile are global. The .bashrc is pulled on each bash session start.

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

Get distance between two points in canvas

Note that Math.hypot is part of the ES2015 standard. There's also a good polyfill on the MDN doc for this feature.

So getting the distance becomes as easy as Math.hypot(x2-x1, y2-y1).

unknown type name 'uint8_t', MinGW

To use uint8_t type alias, you have to include stdint.h standard header.

String comparison in Objective-C

You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:

if ([category isEqualToString:@"Some String"])
{
   // Both strings are equal without respect to their case.
}

Case-insensitive is like this:

if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
   // Both strings are equal with respect to their case.
}

.ssh directory not being created

As a slight improvement over the other answers, you can do the mkdir and chmod as a single operation using mkdir's -m switch.

$ mkdir -m 700 ${HOME}/.ssh

Usage

From a Linux system

$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.

Mandatory arguments to long options are mandatory for short options too.
  -m, --mode=MODE   set file mode (as in chmod), not a=rwx - umask
...
...

How can I pipe stderr, and not stdout?

It's much easier to visualize things if you think about what's really going on with "redirects" and "pipes." Redirects and pipes in bash do one thing: modify where the process file descriptors 0, 1, and 2 point to (see /proc/[pid]/fd/*).

When a pipe or "|" operator is present on the command line, the first thing to happen is that bash creates a fifo and points the left side command's FD 1 to this fifo, and points the right side command's FD 0 to the same fifo.

Next, the redirect operators for each side are evaluated from left to right, and the current settings are used whenever duplication of the descriptor occurs. This is important because since the pipe was set up first, the FD1 (left side) and FD0 (right side) are already changed from what they might normally have been, and any duplication of these will reflect that fact.

Therefore, when you type something like the following:

command 2>&1 >/dev/null | grep 'something'

Here is what happens, in order:

  1. a pipe (fifo) is created. "command FD1" is pointed to this pipe. "grep FD0" also is pointed to this pipe
  2. "command FD2" is pointed to where "command FD1" currently points (the pipe)
  3. "command FD1" is pointed to /dev/null

So, all output that "command" writes to its FD 2 (stderr) makes its way to the pipe and is read by "grep" on the other side. All output that "command" writes to its FD 1 (stdout) makes its way to /dev/null.

If instead, you run the following:

command >/dev/null 2>&1 | grep 'something'

Here's what happens:

  1. a pipe is created and "command FD 1" and "grep FD 0" are pointed to it
  2. "command FD 1" is pointed to /dev/null
  3. "command FD 2" is pointed to where FD 1 currently points (/dev/null)

So, all stdout and stderr from "command" go to /dev/null. Nothing goes to the pipe, and thus "grep" will close out without displaying anything on the screen.

Also note that redirects (file descriptors) can be read-only (<), write-only (>), or read-write (<>).

A final note. Whether a program writes something to FD1 or FD2, is entirely up to the programmer. Good programming practice dictates that error messages should go to FD 2 and normal output to FD 1, but you will often find sloppy programming that mixes the two or otherwise ignores the convention.

"Initializing" variables in python?

Python treats comma on the left hand side of equal sign ( = ) as an input splitter, Very useful for functions that return a tuple.

e.g,

x,y = (5,2)

What you want to do is:

grade_1 = grade_2 = grade_3 = average = 0.0

though that might not be the most clear way to write it.

C++ array initialization

Yes, I believe it should work and it can also be applied to other data types.

For class arrays though, if there are fewer items in the initializer list than elements in the array, the default constructor is used for the remaining elements. If no default constructor is defined for the class, the initializer list must be complete — that is, there must be one initializer for each element in the array.

Node.js - use of module.exports as a constructor

This question doesn't really have anything to do with how require() works. Basically, whatever you set module.exports to in your module will be returned from the require() call for it.

This would be equivalent to:

var square = function(width) {
  return {
    area: function() {
      return width * width;
    }
  };
}

There is no need for the new keyword when calling square. You aren't returning the function instance itself from square, you are returning a new object at the end. Therefore, you can simply call this function directly.

For more intricate arguments around new, check this out: Is JavaScript's "new" keyword considered harmful?

How to catch curl errors in PHP

If CURLOPT_FAILONERROR is false, http errors will not trigger curl errors.

<?php
if (@$_GET['curl']=="yes") {
  header('HTTP/1.1 503 Service Temporarily Unavailable');
} else {
  $ch=curl_init($url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."?curl=yes");
  curl_setopt($ch, CURLOPT_FAILONERROR, true);
  $response=curl_exec($ch);
  $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $curl_errno= curl_errno($ch);
  if ($http_status==503)
    echo "HTTP Status == 503 <br/>";
  echo "Curl Errno returned $curl_errno <br/>";
}

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Previous answers point out correctly that you can only do this with the standard JDK tools by converting the JKS file into PKCS #12 format first. If you're interested, I put together a compact utility to import OpenSSL-derived keys into a JKS-formatted keystore without having to convert the keystore to PKCS #12 first: http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art049

You would use the linked utility like this:

$ openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.csr -subj "/CN=localhost"

(sign the CSR, get back localhost.cer)

$ openssl rsa -in localhost.key -out localhost.rsa
Enter pass phrase for localhost.key:
writing RSA key
$ java -classpath . KeyImport -keyFile localhost.rsa -alias localhost -certificateFile localhost.cer -keystore localhost.jks -keystorePassword changeit -keystoreType JKS -keyPassword changeit

How to remove a package from Laravel using composer?

In case the given answers still don't help you remove that, try this:

  • Manually delete the line in require from composer.json

  • Run composer update