Programs & Examples On #Server side

The term "server-side" refers to the portion of an application run on a server. The counterpart of "server-side" is "client-side", meaning the part of an application running locally on the user's own machine, such as in a Web browser.

How do I parse a HTML page with Node.js

jsdom is too strict to do any real screen scraping sort of things, but beautifulsoup doesn't choke on bad markup.

node-soupselect is a port of python's beautifulsoup into nodejs, and it works beautifully

Send message to specific client with socket.io and node.js

You can use

//send message only to sender-client

socket.emit('message', 'check this');

//or you can send to all listeners including the sender

io.emit('message', 'check this');

//send to all listeners except the sender

socket.broadcast.emit('message', 'this is a message');

//or you can send it to a room

socket.broadcast.to('chatroom').emit('message', 'this is the message to all');

Using Excel OleDb to get sheet names IN SHEET ORDER

This is short, fast, safe, and usable...

public static List<string> ToExcelsSheetList(string excelFilePath)
{
    List<string> sheets = new List<string>();
    using (OleDbConnection connection = 
            new OleDbConnection((excelFilePath.TrimEnd().ToLower().EndsWith("x")) 
            ? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + excelFilePath + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
            : "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + excelFilePath + "';Extended Properties=Excel 8.0;"))
    {
        connection.Open();
        DataTable dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        foreach (DataRow drSheet in dt.Rows)
            if (drSheet["TABLE_NAME"].ToString().Contains("$"))
            {
                string s = drSheet["TABLE_NAME"].ToString();
                sheets.Add(s.StartsWith("'")?s.Substring(1, s.Length - 3): s.Substring(0, s.Length - 1));
            }
        connection.Close();
    }
    return sheets;
}

Do copyright dates need to be updated?

Copyright should be up to the date of publish.

So, if it's a static content (such as the Times article you linked to), it should probably be statically copyrighted.

If it's dynamically generated content, it should be copyrighted to the current year

mysql data directory location

Well, if yo don't know where is my.cnf (such Mac OS X installed with homebrew), or You are looking found others choices:

ps aux|grep mysql
abkrim            1160   0.0  0.2  2913068  26224   ??  R    Tue04PM   0:14.63 /usr/local/opt/mariadb/bin/mysqld --basedir=/usr/local/opt/mariadb --datadir=/usr/local/var/mysql --plugin-dir=/usr/local/opt/mariadb/lib/plugin --bind-address=127.0.0.1 --log-error=/usr/local/var/mysql/iMac-2.local.err --pid-file=iMac-2.local.pid

You get datadir=/usr/local/var/mysql

What is Mocking?

Other answers explain what mocking is. Let me walk you through it with different examples. And believe me, it's actually far more simpler than you think.

tl;dr It's an instance of the original class. It has other data injected into so you avoid testing the injected parts and solely focus on testing the implementation details of your class/functions.

Simple example:

class Foo {
    func add (num1: Int, num2: Int) -> Int { // Line A 
        return num1 + num2 // Line B
    }
}

let unit = Foo() // unit under test
assertEqual(unit.add(1,5),6)

As you can see, I'm not testing LineA ie I'm not validating the input parameters. I'm not validating to see if num1, num2 are an Integer. I have no asserts against that.

I'm only testing to see if LineB (my implementation) given the mocked values 1 and 5 is doing as I expect.

Obviously in the real word this can become much more complex. The parameters can be a custom object like a Person, Address, or the implementation details can be more than a single +. But the logic of testing would be the same.

Non-coding Example:

Assume you're building a machine that identifies the type and brand name of electronic devices for an airport security. The machine does this by processing what it sees with its camera.

Now your manager walks in the door and asks you to unit-test it.

Then you as a developer you can either bring 1000 real objects, like a MacBook pro, Google Nexus, a banana, an iPad etc in front of it and test and see if it all works.

But you can also use mocked objects, like an identical looking MacBook pro (with no real internal parts) or a plastic banana in front of it. You can save yourself from investing in 1000 real laptops and rotting bananas.

The point is you're not trying to test if the banana is fake or not. Nor testing if the laptop is fake or not. All you're doing is testing if your machine once it sees a banana it would say not an electronic device and for a MacBook Pro it would say: Laptop, Apple. To the machine, the outcome of its detection should be the same for fake/mocked electronics and real electronics. If your machine also factored in the internals of a laptop (x-ray scan) or banana then your mocks' internals need to look the same as well. But you could also use a gadget with a friend motherboard. Had your machine tested whether or not devices can power on then well you'd need real devices.

The logic mentioned above applies to unit-testing of actual code as well. That is a function should work the same with real values you get from real input (and interactions) or mocked values you inject during unit-testing. And just as how you save yourself from using a real banana or MacBook, with unit-tests (and mocking) you save yourself from having to do something that causes your server to return a status code of 500, 403, 200, etc (forcing your server to trigger 500 is only when server is down, while 200 is when server is up. It gets difficult to run 100 network focused tests if you have to constantly wait 10 seconds between switching over server up and down). So instead you inject/mock a response with status code 500, 200, 403, etc and test your unit/function with a injected/mocked value.

Be aware:

Sometimes you don't correctly mock the actual object. Or you don't mock every possibility. E.g. your fake laptops are dark, and your machine accurately works with them, but then it doesn't work accurately with white fake laptops. Later when you ship this machine to customers they complain that it doesn't work all the time. You get random reports that it's not working. It takes you 3 months of time to finally figure out that the color of fake laptops need to be more varied so you can test your modules appropriately.

For a true coding example, your implementation may be different for status code 200 with image data returned vs 200 with image data not returned. For this reason it's good to use an IDE that provides code coverage e.g. the image below shows that your unit-tests don't ever go through the lines marked with brown.

enter image description here

image source

Real world coding Example:

Let's say you are writing an iOS application and have network calls.Your job is to test your application. To test/identify whether or not the network calls work as expected is NOT YOUR RESPONSIBILITY . It's another party's (server team) responsibility to test it. You must remove this (network) dependency and yet continue to test all your code that works around it.

A network call can return different status codes 404, 500, 200, 303, etc with a JSON response.

Your app is suppose to work for all of them (in case of errors, your app should throw its expected error). What you do with mocking is you create 'imaginary—similar to real' network responses (like a 200 code with a JSON file) and test your code without 'making the real network call and waiting for your network response'. You manually hardcode/return the network response for ALL kinds of network responses and see if your app is working as you expect. (you never assume/test a 200 with incorrect data, because that is not your responsibility, your responsibility is to test your app with a correct 200, or in case of a 400, 500, you test if your app throws the right error)

This creating imaginary—similar to real is known as mocking.

In order to do this, you can't use your original code (your original code doesn't have the pre-inserted responses, right?). You must add something to it, inject/insert that dummy data which isn't normally needed (or a part of your class).

So you create an instance the original class and add whatever (here being the network HTTPResponse, data OR in the case of failure, you pass the correct errorString, HTTPResponse) you need to it and then test the mocked class.

Long story short, mocking is to simplify and limit what you are testing and also make you feed what a class depends on. In this example you avoid testing the network calls themselves, and instead test whether or not your app works as you expect with the injected outputs/responses —— by mocking classes

Needless to say, you test each network response separately.


Now a question that I always had in my mind was: The contracts/end points and basically the JSON response of my APIs get updated constantly. How can I write unit tests which take this into consideration?

To elaborate more on this: let’s say model requires a key/field named username. You test this and your test passes. 2 weeks later backend changes the key's name to id. Your tests still passes. right? or not?

Is it the backend developer’s responsibility to update the mocks. Should it be part of our agreement that they provide updated mocks?

The answer to the above issue is that: unit tests + your development process as a client-side developer should/would catch outdated mocked response. If you ask me how? well the answer is:

Our actual app would fail (or not fail yet not have the desired behavior) without using updated APIs...hence if that fails...we will make changes on our development code. Which again leads to our tests failing....which we’ll have to correct it. (Actually if we are to do the TDD process correctly we are to not write any code about the field unless we write the test for it...and see it fail and then go and write the actual development code for it.)

This all means that backend doesn’t have to say: “hey we updated the mocks”...it eventually happens through your code development/debugging. ??Because it’s all part of the development process! Though if backend provides the mocked response for you then it's easier.

My whole point on this is that (if you can’t automate getting updated mocked API response then) some human interaction is required ie manual updates of JSONs and having short meetings to make sure their values are up to date will become part of your process

This section was written thanks to a slack discussion in our CocoaHead meetup group


For iOS devs only:

A very good example of mocking is this Practical Protocol-Oriented talk by Natasha Muraschev. Just skip to minute 18:30, though the slides may become out of sync with the actual video ???

I really like this part from the transcript:

Because this is testing...we do want to make sure that the get function from the Gettable is called, because it can return and the function could theoretically assign an array of food items from anywhere. We need to make sure that it is called;

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

I had a similar issue with an Angular project. In my polyfills.ts I had to add both:

    import "core-js/es7/array";
    import "core-js/es7/object";

In addition to enabling all the other IE 11 defaults. (See comments in polyfills.ts if using angular)

After adding these imports the error went away and my Object data populated as intended.

how to query LIST using linq

var persons = new List<Person>
    {
        new Person {ID = 1, Name = "jhon", Salary = 2500},
        new Person {ID = 2, Name = "Sena", Salary = 1500},
        new Person {ID = 3, Name = "Max", Salary = 5500},
        new Person {ID = 4, Name = "Gen", Salary = 3500}
    };

var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
    acertainperson.Name, acertainperson.Salary);

jhon: 2500 points

var doingprettywell = persons.Where(p => p.Salary > 2000);
            foreach (var person in doingprettywell)
            {
                Console.WriteLine("{0}: {1} points",
                    person.Name, person.Salary);
            }

jhon: 2500 points
Max: 5500 points
Gen: 3500 points

        var astupidcalc = from p in persons
                          where p.ID > 2
                          select new
                                     {
                                         Name = p.Name,
                                         Bobos = p.Salary*p.ID,
                                         Bobotype = "bobos"
                                     };
        foreach (var person in astupidcalc)
        {
            Console.WriteLine("{0}: {1} {2}",
                person.Name, person.Bobos, person.Bobotype);
        }

Max: 16500 bobos
Gen: 14000 bobos

How to use regex in file find

Start with:

find . -name '*.log.*.zip' -a -mtime +1

You may not need a regex, try:

 find . -name '*.log.*-*-*.zip' -a -mtime +1

You will want the +1 in order to match 1, 2, 3 ...

Add property to an array of objects

  Object.defineProperty(Results, "Active", {value : 'true',
                       writable : true,
                       enumerable : true,
                       configurable : true});

How to access property of anonymous type in C#?

Recently, I had the same problem within .NET 3.5 (no dynamic available). Here is how I solved:

// pass anonymous object as argument
var args = new { Title = "Find", Type = typeof(FindCondition) };

using (frmFind f = new frmFind(args)) 
{
...
...
}

Adapted from somewhere on stackoverflow:

// Use a custom cast extension
public static T CastTo<T>(this Object x, T targetType)
{
   return (T)x;
}

Now get back the object via cast:

public partial class frmFind: Form
{
    public frmFind(object arguments)
    {

        InitializeComponent();

        var args = arguments.CastTo(new { Title = "", Type = typeof(Nullable) });

        this.Text = args.Title;

        ...
    }
    ...
}

bundle install returns "Could not locate Gemfile"

I had this problem as well on an OSX machine. I discovered that rails was not installed... which surprised me as I thought OSX always came with Rails. To install rails

  • sudo gem install rails
  • to install jekyll I also needed sudo
  • sudo gem install jekyll bundler
  • cd ~/Sites
  • jekyll new <foldername>
  • cd <foldername> OR cd !$ (that is magic ;)
  • bundle install
  • bundle exec jekyll serve
  • Then in your browser just go to http://127.0.0.1:4000/ and it really should be running

TSQL - Cast string to integer or return default value

My solution to this issue was to create the function shown below. My requirements included that the number had to be a standard integer, not a BIGINT, and I needed to allow negative numbers and positive numbers. I have not found a circumstance where this fails.

CREATE FUNCTION [dbo].[udfIsInteger]
(
    -- Add the parameters for the function here
    @Value nvarchar(max)
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result int = 0

    -- Add the T-SQL statements to compute the return value here
    DECLARE @MinValue nvarchar(11) = '-2147483648'
    DECLARE @MaxValue nvarchar(10) = '2147483647'

    SET @Value = ISNULL(@Value,'')

    IF LEN(@Value)=0 OR 
      ISNUMERIC(@Value)<>1 OR
      (LEFT(@Value,1)='-' AND LEN(@Value)>11) OR
      (LEFT(@Value,1)='-' AND LEN(@Value)=11 AND @Value>@MinValue) OR
      (LEFT(@Value,1)<>'-' AND LEN(@Value)>10) OR
      (LEFT(@Value,1)<>'-' AND LEN(@Value)=10 AND @Value>@MaxValue)
      GOTO FINISHED

    DECLARE @cnt int = 0
    WHILE @cnt<LEN(@Value)
    BEGIN
      SET @cnt=@cnt+1
      IF SUBSTRING(@Value,@cnt,1) NOT IN ('-','0','1','2','3','4','5','6','7','8','9') GOTO FINISHED
    END
    SET @Result=1

FINISHED:
    -- Return the result of the function
    RETURN @Result

END

(Excel) Conditional Formatting based on Adjacent Cell Value

I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:

Under Conditional Formatting > Manage Rules:

  1. Make a new rule with "Use a formula to determine which cells to format"
  2. Make your rule, but put a dollar sign only in front of the letter: $A2<$B2
  3. Under "Applies to", Manually select the second column (It would not work for me if I changed the value in the box, it just kept snapping back to what was already there), so it looks like $B$2:$B$100 (assuming you have 100 rows)

This worked for me in Excel 2016.

LINQ: Select where object does not contain items from list

Try this simple LINQ:

//For a file list/array
var files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);

//simply use Where ! x.Contains
var notContain = files.Where(x => ! x.Contains(@"\$RECYCLE.BIN\")).ToList();

//Or use Except()
var containing = files.Where(x => x.Contains(@"\$RECYCLE.BIN\")).ToList();
    notContain = files.Except(containing).ToList();

PostgreSQL IF statement

Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"

select 
    case
        when stage = 1 then 'running'
        when stage = 2 then 'done'
        when stage = 3 then 'stopped'
    else 
        'not running'
    end as run_status from processes

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

Try downloading apache-jmeter-2.6.zip from http://www.apache.org/dist/jmeter/binaries/

This contains the proper ApacheJMeter.jar that is needed to initiate.

Go to bin folder in the command prompt and try java -jar ApacheJMeter.jar if the download is correct this should open the GUI.

Edit on 23/08/2018:

d3.select("#element") not working when code above the html element

Please try this approach. It worked for me.

<head> 
<script  type="text/javascript" src='./d3.v4.min.js'></script>
</head> 

<body>
    <div id="jschart41448" style="color:red">
        Hi red
    </div>

    <div id="jschart41449" style="color:blueviolet">
        Hi blueviolet
    </div>

 <script type="text/javascript"   >
            d3.select("#jschart41448").style('color', 'green' , null);
            d3.select("#jschart41449").style('color', 'yellow', null);
</script>
</body>

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

Although you should have no problem running a 2005 instance of the database engine beside a 2008 instance, The tools are installed into a shared directory, so you can't have two versions of the tools installed. Fortunately, the 2008 tools are backwards-compatible. As we speak, I'm using SSMS 2008 and Profiler 2008 to manage my 2005 Express instances. Works great.

Before installing the 2008 tools, you need to remove any and all "shared" components from 2005. Try going to your Add/Remove programs control panel, find Microsoft SQL Server 2005, and click "Change." Then choose "Workstation Components" and remove everything there (this will not remove your database engine).

I believe the 2008 installer also has an option to upgrade shared components only. You might try that. Good luck!

Vue.js - How to properly watch for nested data

How if you want to watch a property for a while and then to un-watch it?

Or to watch a library child component property?

You can use the "dynamic watcher":

this.$watch(
 'object.property', //what you want to watch
 (newVal, oldVal) => {
    //execute your code here
 }
)

The $watch returns an unwatch function which will stop watching if it is called.

var unwatch = vm.$watch('a', cb)
// later, teardown the watcher
unwatch()

Also you can use the deep option:

this.$watch(
'someObject', () => {
    //execute your code here
},
{ deep: true }
)

Please make sure to take a look to docs

Using different Web.config in development and production environment

In Visual Studio 2010 and above, you now have the ability to apply a transformation to your web.config depending on the build configuration.

When creating a web.config, you can expand the file in the solution explorer, and you will see two files:

  • Web.Debug.Config
  • Web.Release.Config

They contain transformation code that can be used to

  • Change the connection string
  • Remove debugging trace and settings
  • Register error pages

See Web.config Transformation Syntax for Web Application Project Deployment on MSDN for more information.

It is also possible, albeit officially unsupported, to apply the same kind of transformation to an non web application app.config file. See Phil Bolduc blog concerning how to modify your project file to add a new task to msbuild.

This is a long withstanding request on the Visual Studio Uservoice.

An extension for Visual Studio 2010 and above, "SlowCheetah," is available to take care of creating transform for any config file. Starting with Visual Studio 2017.3, SlowCheetah has been integrated into the IDE and the code base is being managed by Microsoft. This new version also support JSON transformation.

How do I set the driver's python version in spark?

I had the same problem, just forgot to activate my virtual environment. For anyone out there who also had a mental blank.

What is the difference between a static and const variable?

A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.

A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

creating Hashmap from a JSON String

Best way to parse Json to HashMap

public static HashMap<String, String> jsonToMap(JSONObject json) throws JSONException {
            HashMap<String, String> map = new HashMap<>();
            try {
                Iterator<String> iterator = json.keys();

                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String value = json.getString(key);
                    map.put(key, value);
                }

                return map;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

How do I loop through a date range?

Iterate every 15 minutes

DateTime startDate = DateTime.Parse("2018-06-24 06:00");
        DateTime endDate = DateTime.Parse("2018-06-24 11:45");

        while (startDate.AddMinutes(15) <= endDate)
        {

            Console.WriteLine(startDate.ToString("yyyy-MM-dd HH:mm"));
            startDate = startDate.AddMinutes(15);
        }

INNER JOIN vs LEFT JOIN performance in SQL Server

If everything works as it should it shouldn't, BUT we all know everything doesn't work the way it should especially when it comes to the query optimizer, query plan caching and statistics.

First I would suggest rebuilding index and statistics, then clearing the query plan cache just to make sure that's not screwing things up. However I've experienced problems even when that's done.

I've experienced some cases where a left join has been faster than a inner join.

The underlying reason is this: If you have two tables and you join on a column with an index (on both tables). The inner join will produce the same result no matter if you loop over the entries in the index on table one and match with index on table two as if you would do the reverse: Loop over entries in the index on table two and match with index in table one. The problem is when you have misleading statistics, the query optimizer will use the statistics of the index to find the table with least matching entries (based on your other criteria). If you have two tables with 1 million in each, in table one you have 10 rows matching and in table two you have 100000 rows matching. The best way would be to do an index scan on table one and matching 10 times in table two. The reverse would be an index scan that loops over 100000 rows and tries to match 100000 times and only 10 succeed. So if the statistics isn't correct the optimizer might choose the wrong table and index to loop over.

If the optimizer chooses to optimize the left join in the order it is written it will perform better than the inner join.

BUT, the optimizer may also optimize a left join sub-optimally as a left semi join. To make it choose the one you want you can use the force order hint.

android button selector

You can't achieve text size change with a state list drawable. To change text color and text size do this:

Text color

To change the text color, you can create color state list resource. It will be a separate resource located in res/color/ directory. In layout xml you have to set it as the value for android:textColor attribute. The color selector will then contain something like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/text_pressed" />
    <item android:color="@color/text_normal" />
</selector>

Text size

You can't change the size of the text simply with resources. There's no "dimen selector". You have to do it in code. And there is no straightforward solution.

Probably the easiest solution might be utilizing View.onTouchListener() and handle the up and down events accordingly. Use something like this:

view.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // change text size to the "pressed value"
                return true;
            case MotionEvent.ACTION_UP:
                // change text size to the "normal value"
                return true;
            default:
                return false;
            }
        }
});

A different solution might be to extend the view and override the setPressed(Boolean) method. The method is internally called when the change of the pressed state happens. Then change the size of the text accordingly in the method call (don't forget to call the super).

Javascript select onchange='this.form.submit()'

Use :

<select onchange="myFunction()">

    function myFunction() {
        document.querySelectorAll("input[type=submit]")[0].click();
    }

"OverflowError: Python int too large to convert to C long" on windows but not mac

Could anyone help explain why

In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.

The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.

or give a solution for the code on windows? Thanks so much!

Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64

How to build a Debian/Ubuntu package from source?

you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet.

You can use "uupdate" (apt-get install devscripts) to build a package from source with existing debian sources:

Example for libdrm2:

apt-get build-dep libdrm2
apt-get source libdrm2
cd libdrm-2.3.1
uupdate ~/Downloads/libdrm-2.4.1.tar.gz
cd ../libdrm-2.4.1
dpkg-buildpackage -us -uc -nc

Convert time.Time to string

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

Best way to parse command-line parameters?

How to parse parameters without an external dependency. Great question! You may be interested in picocli.

Picocli is specifically designed to solve the problem asked in the question: it is a command line parsing framework in a single file, so you can include it in source form. This lets users run picocli-based applications without requiring picocli as an external dependency.

It works by annotating fields so you write very little code. Quick summary:

  • Strongly typed everything - command line options as well as positional parameters
  • Support for POSIX clustered short options (so it handles <command> -xvfInputFile as well as <command> -x -v -f InputFile)
  • An arity model that allows a minimum, maximum and variable number of parameters, e.g, "1..*", "3..5"
  • Fluent and compact API to minimize boilerplate client code
  • Subcommands
  • Usage help with ANSI colors

The usage help message is easy to customize with annotations (without programming). For example:

Extended usage help message (source)

I couldn't resist adding one more screenshot to show what kind of usage help messages are possible. Usage help is the face of your application, so be creative and have fun!

picocli demo

Disclaimer: I created picocli. Feedback or questions very welcome. It is written in java, but let me know if there is any issue using it in scala and I'll try to address it.

How do I add the Java API documentation to Eclipse?

I have had a similar issue and looks like that the culprit was the space in the path to the archive (e.g., C:\Program Files\java\jdk). After moving the archive to another directory without spaces in path it started to work.

Remove Array Value By index in jquery

Use the splice method.

ArrayName.splice(indexValueOfArray,1);

This removes 1 item from the array starting at indexValueOfArray.

Zero-pad digits in string

There's also str_pad

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

Determine distance from the top of a div to top of window with javascript

I used this:

                              myElement = document.getElemenById("xyz");
Get_Offset_From_Start       ( myElement );  // returns positions from website's start position
Get_Offset_From_CurrentView ( myElement );  // returns positions from current scrolled view's TOP and LEFT

code:

function Get_Offset_From_Start (object, offset) { 
    offset = offset || {x : 0, y : 0};
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    if(object.offsetParent) {
        offset = Get_Offset_From_Start (object.offsetParent, offset);
    }
    return offset;
}

function Get_Offset_From_CurrentView (myElement) {
    if (!myElement) return;
    var offset = Get_Offset_From_Start (myElement);
    var scrolled = GetScrolled (myElement.parentNode);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
//helper
function GetScrolled (object, scrolled) {
    scrolled = scrolled || {x : 0, y : 0};
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html" && object.parentNode) { scrolled=GetScrolled (object.parentNode, scrolled); }
    return scrolled;
}

    /*
    // live monitoring
    window.addEventListener('scroll', function (evt) {
        var Positionsss =  Get_Offset_From_CurrentView(myElement);  
        console.log(Positionsss);
    });
    */

sprintf like functionality in Python

Something like...

greetings = 'Hello {name}'.format(name = 'John')

Hello John

Convert object string to JSON

This will also work

let str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
let json = JSON.stringify(eval("("+ str +")"));

How do I change the figure size for a seaborn plot?

This shall also work.

from matplotlib import pyplot as plt
import seaborn as sns    

plt.figure(figsize=(15,16))
sns.countplot(data=yourdata, ...)

How can I initialize a MySQL database with schema in a Docker container?

Below is the Dockerfile I used successfully to install xampp, create a MariaDB with scheme and pre populated with the info used on local server(usrs,pics orders,etc..)

FROM ubuntu:14.04

COPY Ecommerce.sql /root

RUN apt-get update \
 && apt-get install wget -yq \
 && apt-get install nano \
 && wget https://www.apachefriends.org/xampp-files/7.1.11/xampp-linux-x64-7.1.11-0-installer.run \
 && mv xampp-linux-x64-7.1.11-0-installer.run /opt/ \
 && cd /opt/ \
 && chmod +x xampp-linux-x64-7.1.11-0-installer.run \
 && printf 'y\n\y\n\r\n\y\n\r\n' | ./xampp-linux-x64-7.1.11-0-installer.run \
 && cd /opt/lampp/bin \
 && /opt/lampp/lampp start \
 && sleep 5s \

 && ./mysql -uroot -e "CREATE DATABASE Ecommerce" \
 && ./mysql -uroot -D Ecommerce < /root/Ecommerce.sql \
 && cd / \
 && /opt/lampp/lampp reload \
 && mkdir opt/lampp/htdocs/Ecommerce

COPY /Ecommerce /opt/lampp/htdocs/Ecommerce

EXPOSE 80

How can I import data into mysql database via mysql workbench?

For MySQL Workbench 8.0 navigate to:

Server > Data Import

A new tab called Administration - Data Import/Restore appears. There you can choose to import a Dump Project Folder or use a specific SQL file according to your needs. Then you must select a schema where the data will be imported to, or you have to click the New... button to type a name for the new schema.

Then you can select the database objects to be imported or just click the Start Import button in the lower right part of the tab area.

Having done that and if the import was successful, you'll need to update the Schema Navigator by clicking the arrow circle icon.

That's it!

For more detailed info, check the MySQL Workbench Manual: 6.5.2 SQL Data Export and Import Wizard

Set android shape color programmatically

Expanding on Vikram's answer, if you are coloring dynamic views, like recycler view items, etc.... Then you probably want to call mutate() before you set the color. If you don't do this, any views that have a common drawable (i.e a background) will also have their drawable changed/colored.

public static void setBackgroundColorAndRetainShape(final int color, final Drawable background) {

    if (background instanceof ShapeDrawable) {
        ((ShapeDrawable) background.mutate()).getPaint().setColor(color);
    } else if (background instanceof GradientDrawable) {
        ((GradientDrawable) background.mutate()).setColor(color);
    } else if (background instanceof ColorDrawable) {
        ((ColorDrawable) background.mutate()).setColor(color);
    }else{
        Log.w(TAG,"Not a valid background type");
    }

}

Cannot find control with name: formControlName in angular reactive form

I also had this error, and you helped me solve it. If formGroup or formGroupName are not written with the good case, then the name of the control is not found. Correct the case of formGroup or formGroupName and it is OK.

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

[UPDATE] TL;DR pkg_resources is provided by either Distribute or setuptools.

[UPDATE 2] As announced at PyCon 2013, the Distribute and setuptools projects have re-merged. Distribute is now deprecated and you should just use the new current setuptools. Try this:

curl -O https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python ez_setup.py

Or, better, use a current pip as the high level interface and which will use setuptools under the covers.

[Longer answer for OP's specific problem]:

You don't say in your question but I'm assuming you upgraded from the Apple-supplied Python (2.5 on 10.5 or 2.6.1 on 10.6) or that you upgraded from a python.org Python 2.5. In any of those cases, the important point is that each Python instance has its own library, including its own site-packages library, which is where additional packages are installed. (And none of them use /usr/local/lib by default, by the way.) That means you'll need to install those additional packages you need for your new python 2.6. The easiest way to do this is to first ensure that the new python2.6 appears first on your search $PATH (that is, typing python2.6 invokes it as expected); the python2.6 installer should have modified your .bash_profile to put its framework bin directory at the front of $PATH. Then install easy_install using setuptools following the instructions there. The pkg_resources module is also automatically installed by this step.

Then use the newly-installed version of easy_install (or pip) to install ipython.

easy_install ipython

or

pip install ipython

It should automatically get installed to the correct site-packages location for that python instance and you should be good to go.

Equivalent of LIMIT for DB2

Support for OFFSET and LIMIT was recently added to DB2 for i 7.1 and 7.2. You need the following DB PTF group levels to get this support:

  • SF99702 level 9 for IBM i 7.2
  • SF99701 level 38 for IBM i 7.1

See here for more information: OFFSET and LIMIT documentation, DB2 for i Enhancement Wiki

Sorting a vector of custom objects

    // sort algorithm example
    #include <iostream>     // std::cout
    #include <algorithm>    // std::sort
    #include <vector>       // std::vector
    using namespace std;
    int main () {
        char myints[] = {'F','C','E','G','A','H','B','D'};
        vector<char> myvector (myints, myints+8);               // 32 71 12 45 26 80 53 33
        // using default comparison (operator <):
        sort (myvector.begin(), myvector.end());           //(12 32 45 71)26 80 53 33
        // print out content:
        cout << "myvector contains:";
        for (int i=0; i!=8; i++)
            cout << ' ' <<myvector[i];
        cout << '\n';
        system("PAUSE");
    return 0;
    }

Count work days between two dates

In Calculating Work Days you can find a good article about this subject, but as you can see it is not that advanced.

--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
--If the function already exists, drop it.
IF EXISTS
(
    SELECT *
    FROM dbo.SYSOBJECTS
    WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
    AND XType IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_WorkDays]
GO
 CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
    @StartDate DATETIME,
    @EndDate   DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)

--Define the output data type.
RETURNS INT

AS
--Calculate the RETURN of the function.
BEGIN
    --Declare local variables
    --Temporarily holds @EndDate during date reversal.
    DECLARE @Swap DATETIME

    --If the Start Date is null, return a NULL and exit.
    IF @StartDate IS NULL
        RETURN NULL

    --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
     IF @EndDate IS NULL
        SELECT @EndDate = @StartDate

    --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
    --Usually faster than CONVERT.
    --0 is a date (01/01/1900 00:00:00.000)
     SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
            @EndDate   = DATEADD(dd,DATEDIFF(dd,0,@EndDate)  , 0)

    --If the inputs are in the wrong order, reverse them.
     IF @StartDate > @EndDate
        SELECT @Swap      = @EndDate,
               @EndDate   = @StartDate,
               @StartDate = @Swap

    --Calculate and return the number of workdays using the input parameters.
    --This is the meat of the function.
    --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
     RETURN (
        SELECT
        --Start with total number of days including weekends
        (DATEDIFF(dd,@StartDate, @EndDate)+1)
        --Subtact 2 days for each full weekend
        -(DATEDIFF(wk,@StartDate, @EndDate)*2)
        --If StartDate is a Sunday, Subtract 1
        -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
            THEN 1
            ELSE 0
        END)
        --If EndDate is a Saturday, Subtract 1
        -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
            THEN 1
            ELSE 0
        END)
        )
    END
GO

If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.

Awaiting multiple Tasks with different results

You can use Task.WhenAll as mentioned, or Task.WaitAll, depending on whether you want the thread to wait. Take a look at the link for an explanation of both.

WaitAll vs WhenAll

How can I use Timer (formerly NSTimer) in Swift?

NSTimer has been renamed to Timer in Swift 4.2. this syntax will work in 4.2:

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)

CSS: how to add white space before element's content?

Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/

This will add 10 pixels to the left of the paragraph element

p {
    margin-left: 10px;
 }

or if you just want some padding within your paragraph element

p {
    padding-left: 10px;
}

How to get exception message in Python properly

from traceback import format_exc


try:
    fault = 10/0
except ZeroDivision:
    print(format_exc())

Another possibility is to use the format_exc() method from the traceback module.

read file from assets

@HpTerm answer Kotlin version:

private fun getDataFromAssets(activity: Activity): String {

    var bufferedReader: BufferedReader? = null
    var data = ""

    try {
        bufferedReader = BufferedReader(
            InputStreamReader(
                activity?.assets?.open("Your_FILE.html"),
                "UTF-8"
            )
        )                  //use assets? directly if in activity

        var mLine:String? = bufferedReader.readLine()
        while (mLine != null) {
            data+= mLine
            mLine=bufferedReader.readLine()
        }

    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        try {
            bufferedReader?.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    return data
}

How do I edit a file after I shell to a Docker container?

You can open existing file with

cat filename.extension

and copy all the existing text on clipboard.

Then delete old file with

rm filename.extension

or rename old file with

mv old-filename.extension new-filename.extension

Create new file with

cat > new-file.extension

Then paste all text copied on clipboard, press Enter and exit with save by pressing ctrl+z. And voila no need to install any kind of editors.

What is tail call optimization?

TCO (Tail Call Optimization) is the process by which a smart compiler can make a call to a function and take no additional stack space. The only situation in which this happens is if the last instruction executed in a function f is a call to a function g (Note: g can be f). The key here is that f no longer needs stack space - it simply calls g and then returns whatever g would return. In this case the optimization can be made that g just runs and returns whatever value it would have to the thing that called f.

This optimization can make recursive calls take constant stack space, rather than explode.

Example: this factorial function is not TCOptimizable:

def fact(n):
    if n == 0:
        return 1
    return n * fact(n-1)

This function does things besides call another function in its return statement.

This below function is TCOptimizable:

def fact_h(n, acc):
    if n == 0:
        return acc
    return fact_h(n-1, acc*n)

def fact(n):
    return fact_h(n, 1)

This is because the last thing to happen in any of these functions is to call another function.

Extract Google Drive zip from Google colab notebook

Mount GDrive:

from google.colab import drive
drive.mount('/content/gdrive')

Open the link -> copy authorization code -> paste that into the prompt and press "Enter"

Check GDrive access:

!ls "/content/gdrive/My Drive"

Unzip (q stands for "quiet") file from GDrive:

!unzip -q "/content/gdrive/My Drive/dataset.zip"

Print a div content using Jquery

Without using any plugin you can opt this logic.

$("#btn").click(function () {
    //Hide all other elements other than printarea.
    $("#printarea").show();
    window.print();
});

How to determine the content size of a UIWebView?

Resurrecting this question because I found Ortwin's answer to only work MOST of the time...

The webViewDidFinishLoad method may be called more than once, and the first value returned by sizeThatFits is only some portion of what the final size should be. Then for whatever reason the next call to sizeThatFits when webViewDidFinishLoad fires again will incorrectly return the same value it did before! This will happen randomly for the same content as if it's some kind of concurrency problem. Maybe this behaviour has changed over time, because I'm building for iOS 5 and have also found that sizeToFit works in much the same way (although previously this didn't?)

I have settled on this simple solution:

- (void)webViewDidFinishLoad:(UIWebView *)aWebView
{        
    CGFloat height = [[aWebView stringByEvaluatingJavaScriptFromString:@"document.height"] floatValue];
    CGFloat width = [[aWebView stringByEvaluatingJavaScriptFromString:@"document.width"] floatValue];
    CGRect frame = aWebView.frame;
    frame.size.height = height;
    frame.size.width = width;
    aWebView.frame = frame;
}

Swift (2.2):

func webViewDidFinishLoad(webView: UIWebView) {

    if let heightString = webView.stringByEvaluatingJavaScriptFromString("document.height"),
        widthString = webView.stringByEvaluatingJavaScriptFromString("document.width"),
        height = Float(heightString),
        width = Float(widthString) {

        var rect = webView.frame
        rect.size.height = CGFloat(height)
        rect.size.width = CGFloat(width)
        webView.frame = rect
    }
}

Update: I have found as mentioned in the comments this doesn't seem to catch the case where the content has shrunk. Not sure if it's true for all content and OS version, give it a try.

single line comment in HTML

No, you have to close the comment with -->.

Mime type for WOFF fonts?

Maybe this will help someone. I saw that on IIS 7 .ttf is already a known mime-type. It's configured as:

application/octet-stream

So I just added that for all the CSS font types (.oet, .svg, .ttf, .woff) and IIS started serving them. Chrome dev tools also do not complain about re-interpreting the type.

Cheers, Michael

Check if a key exists inside a json object

I change your if statement slightly and works (also for inherited obj - look on snippet)

if(!("merchant_id" in thisSession)) alert("yeah");

_x000D_
_x000D_
var sessionA = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  merchant_id: "sam",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
var sessionB = {_x000D_
  amt: "10.00",_x000D_
  email: "[email protected]",_x000D_
  mobileNo: "9874563210",_x000D_
  orderID: "123456",_x000D_
  passkey: "1234",_x000D_
}_x000D_
_x000D_
_x000D_
var sessionCfromA = Object.create(sessionA); // inheritance_x000D_
sessionCfromA.name = 'john';_x000D_
_x000D_
_x000D_
if (!("merchant_id" in sessionA)) alert("merchant_id not in sessionA");_x000D_
if (!("merchant_id" in sessionB)) alert("merchant_id not in sessionB");_x000D_
if (!("merchant_id" in sessionCfromA)) alert("merchant_id not in sessionCfromA");_x000D_
_x000D_
if ("merchant_id" in sessionA) alert("merchant_id in sessionA");_x000D_
if ("merchant_id" in sessionB) alert("merchant_id in sessionB");_x000D_
if ("merchant_id" in sessionCfromA) alert("merchant_id in sessionCfromA");
_x000D_
_x000D_
_x000D_

How to write inside a DIV box with javascript

HTML:

<div id="log"></div>

JS:

document.getElementById("log").innerHTML="WHATEVER YOU WANT...";

Java Singleton and Synchronization

You can also use static code block to instantiate the instance at class load and prevent the thread synchronization issues.

public class MySingleton {

  private static final MySingleton instance;

  static {
     instance = new MySingleton();
  }

  private MySingleton() {
  }

  public static MySingleton getInstance() {
    return instance;
  }

}

What is the difference between background and background-color

The difference is that the background shorthand property sets several background-related properties. It sets them all, even if you only specify e.g. a color value, since then the other properties are set to their initial values, e.g. background-image to none.

This does not mean that it would always override any other settings for those properties. This depends on the cascade according to the usual, generally misunderstood rules.

In practice, the shorthand tends to be somewhat safer. It is a precaution (not complete, but useful) against accidentally getting some unexpected background properties, such as a background image, from another style sheet. Besides, it’s shorter. But you need to remember that it really means “set all background properties”.

Very simple C# CSV reader

This fixed version of code above remember the last element of CVS row ;-)

(tested with a CSV file with 5400 rows and 26 elements by row)

   public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')  {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();

            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);

            /* to solve the last element problem */
            retAry.Add(bld.ToString()); /* added this line */
            return retAry.ToArray();
        }

repaint() in Java

You're doing things in the wrong order.

You need to first add all JComponents to the JFrame, and only then call pack() and then setVisible(true) on the JFrame

If you later added JComponents that could change the GUI's size you will need to call pack() again, and then repaint() on the JFrame after doing so.

How to display a Windows Form in full screen on top of the taskbar?

Use:

FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;

And then your form is placed over the taskbar.

Change x axes scale in matplotlib

Try using matplotlib.pyplot.ticklabel_format:

import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

This applies scientific notation (i.e. a x 10^b) to your x-axis tickmarks

How to replace plain URLs with links?

Thanks, this was very helpful. I also wanted something that would link things that looked like a URL -- as a basic requirement, it'd link something like www.yahoo.com, even if the http:// protocol prefix was not present. So basically, if "www." is present, it'll link it and assume it's http://. I also wanted emails to turn into mailto: links. EXAMPLE: www.yahoo.com would be converted to www.yahoo.com

Here's the code I ended up with (combination of code from this page and other stuff I found online, and other stuff I did on my own):

function Linkify(inputText) {
    //URLs starting with http://, https://, or ftp://
    var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with www. (without // before it, or it'd re-link the ones done above)
    var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links
    var replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText
}

In the 2nd replace, the (^|[^/]) part is only replacing www.whatever.com if it's not already prefixed by // -- to avoid double-linking if a URL was already linked in the first replace. Also, it's possible that www.whatever.com might be at the beginning of the string, which is the first "or" condition in that part of the regex.

This could be integrated as a jQuery plugin as Jesse P illustrated above -- but I specifically wanted a regular function that wasn't acting on an existing DOM element, because I'm taking text I have and then adding it to the DOM, and I want the text to be "linkified" before I add it, so I pass the text through this function. Works great.

How do you loop through each line in a text file using a windows batch file?

@MrKraus's answer is instructive. Further, let me add that if you want to load a file located in the same directory as the batch file, prefix the file name with %~dp0. Here is an example:

cd /d %~dp0
for /F "tokens=*" %%A in (myfile.txt) do [process] %%A

NB:: If your file name or directory (e.g. myfile.txt in the above example) has a space (e.g. 'my file.txt' or 'c:\Program Files'), use:

for /F "tokens=*" %%A in ('type "my file.txt"') do [process] %%A

, with the type keyword calling the type program, which displays the contents of a text file. If you don't want to suffer the overhead of calling the type command you should change the directory to the text file's directory. Note that type is still required for file names with spaces.

I hope this helps someone!

Parse JSON from HttpURLConnection object

The JSON string will just be the body of the response you get back from the URL you have called. So add this code

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

Here's an example using JSON-LIB

Memcache Vs. Memcached

(PartlyStolen from ServerFault)

I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

Ways to save enums in database

For a large database, I am reluctant to lose the size and speed advantages of the numeric representation. I often end up with a database table representing the Enum.

You can enforce database consistency by declaring a foreign key -- although in some cases it might be better to not declare that as a foreign key constraint, which imposes a cost on every transaction. You can ensure consistency by periodically doing a check, at times of your choosing, with:

SELECT reftable.* FROM reftable
  LEFT JOIN enumtable ON reftable.enum_ref_id = enumtable.enum_id
WHERE enumtable.enum_id IS NULL;

The other half of this solution is to write some test code that checks that the Java enum and the database enum table have the same contents. That's left as an exercise for the reader.

How do I get the time difference between two DateTime objects using C#?

You want the TimeSpan struct:

TimeSpan diff = dateTime1 - dateTime2;

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.

There are various methods for getting the days, hours, minutes, seconds and milliseconds back from this structure.

If you are just interested in the difference then:

TimeSpan diff = Math.Abs(dateTime1 - dateTime2);

will give you the positive difference between the times regardless of the order.

If you have just got the time component but the times could be split by midnight then you need to add 24 hours to the span to get the actual difference:

TimeSpan diff = dateTime1 - dateTime2;
if (diff < 0)
{
    diff = diff + TimeSpan.FromDays(1);
}

Generate a random number in the range 1 - 10

To summarize and a bit simplify, you can use:

-- 0 - 9
select floor(random() * 10);
-- 0 - 10
SELECT floor(random() * (10 + 1));
-- 1 - 10
SELECT ceil(random() * 10);

And you can test this like mentioned by @user80168

-- 0 - 9
SELECT min(i), max(i) FROM (SELECT floor(random() * 10) AS i FROM generate_series(0, 100000)) q;
-- 0 - 10
SELECT min(i), max(i) FROM (SELECT floor(random() * (10 + 1)) AS i FROM generate_series(0, 100000)) q;
-- 1 - 10
SELECT min(i), max(i) FROM (SELECT ceil(random() * 10) AS i FROM generate_series(0, 100000)) q;

How to sanity check a date in Java

I suggest you to use org.apache.commons.validator.GenericValidator class from apache.

GenericValidator.isDate(String value, String datePattern, boolean strict);

Note: strict - Whether or not to have an exact match of the datePattern.

How to position the form in the center screen?

If you use NetBeans IDE right click form then

Properties ->Code -> check out Generate Center

Add new element to an existing object

You could store your JSON inside of an array and then insert the JSON data into the array with push

Check this out https://jsfiddle.net/cx2rk40e/2/

$(document).ready(function(){

  // using jQuery just to load function but will work without library.
  $( "button" ).on( "click", go );

  // Array of JSON we will append too.
  var jsonTest = [{
    "colour": "blue",
    "link": "http1"
  }]

  // Appends JSON to array with push. Then displays the data in alert.
  function go() {    
      jsonTest.push({"colour":"red", "link":"http2"});
      alert(JSON.stringify(jsonTest));    
    }

}); 

Result of JSON.stringify(jsonTest)

[{"colour":"blue","link":"http1"},{"colour":"red","link":"http2"}]

This answer maybe useful to users who wish to emulate a similar result.

How to obtain the last index of a list?

Did you mean len(list1)-1?

If you're searching for other method, you can try list1.index(list1[-1]), but I don't recommend this one. You will have to be sure, that the list contains NO duplicates.

"git checkout <commit id>" is changing branch to "no branch"

If you checkout a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.

If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:

git checkout <branch>

If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:

# Checkout a new branch at current detached head state:
git checkout -b newBranch

You can read more about detached head state at the official Linux Kernel Git docs for checkout.

Combine two columns and add into one new column

You don't need to store the column to reference it that way. Try this:

To set up:

CREATE TABLE tbl
  (zipcode text NOT NULL, city text NOT NULL, state text NOT NULL);
INSERT INTO tbl VALUES ('10954', 'Nanuet', 'NY');

We can see we have "the right stuff":

\pset border 2
SELECT * FROM tbl;
+---------+--------+-------+
| zipcode |  city  | state |
+---------+--------+-------+
| 10954   | Nanuet | NY    |
+---------+--------+-------+

Now add a function with the desired "column name" which takes the record type of the table as its only parameter:

CREATE FUNCTION combined(rec tbl)
  RETURNS text
  LANGUAGE SQL
AS $$
  SELECT $1.zipcode || ' - ' || $1.city || ', ' || $1.state;
$$;

This creates a function which can be used as if it were a column of the table, as long as the table name or alias is specified, like this:

SELECT *, tbl.combined FROM tbl;

Which displays like this:

+---------+--------+-------+--------------------+
| zipcode |  city  | state |      combined      |
+---------+--------+-------+--------------------+
| 10954   | Nanuet | NY    | 10954 - Nanuet, NY |
+---------+--------+-------+--------------------+

This works because PostgreSQL checks first for an actual column, but if one is not found, and the identifier is qualified with a relation name or alias, it looks for a function like the above, and runs it with the row as its argument, returning the result as if it were a column. You can even index on such a "generated column" if you want to do so.

Because you're not using extra space in each row for the duplicated data, or firing triggers on all inserts and updates, this can often be faster than the alternatives.

Regular expression for extracting tag attributes

I have created a PHP function that could extract attributes of any HTML tags. It also can handle attributes like disabled that has no value, and also can determine whether the tag is a stand-alone tag (has no closing tag) or not (has a closing tag) by checking the content result:

/*! Based on <https://github.com/mecha-cms/cms/blob/master/system/kernel/converter.php> */
function extract_html_attributes($input) {
    if( ! preg_match('#^(<)([a-z0-9\-._:]+)((\s)+(.*?))?((>)([\s\S]*?)((<)\/\2(>))|(\s)*\/?(>))$#im', $input, $matches)) return false;
    $matches[5] = preg_replace('#(^|(\s)+)([a-z0-9\-]+)(=)(")(")#i', '$1$2$3$4$5<attr:value>$6', $matches[5]);
    $results = array(
        'element' => $matches[2],
        'attributes' => null,
        'content' => isset($matches[8]) && $matches[9] == '</' . $matches[2] . '>' ? $matches[8] : null
    );
    if(preg_match_all('#([a-z0-9\-]+)((=)(")(.*?)("))?(?:(\s)|$)#i', $matches[5], $attrs)) {
        $results['attributes'] = array();
        foreach($attrs[1] as $i => $attr) {
            $results['attributes'][$attr] = isset($attrs[5][$i]) && ! empty($attrs[5][$i]) ? ($attrs[5][$i] != '<attr:value>' ? $attrs[5][$i] : "") : $attr;
        }
    }
    return $results;
}

Test Code

$test = array(
    '<div class="foo" id="bar" data-test="1000">',
    '<div>',
    '<div class="foo" id="bar" data-test="1000">test content</div>',
    '<div>test content</div>',
    '<div>test content</span>',
    '<div>test content',
    '<div></div>',
    '<div class="foo" id="bar" data-test="1000"/>',
    '<div class="foo" id="bar" data-test="1000" />',
    '< div  class="foo"     id="bar"   data-test="1000"       />',
    '<div class id data-test>',
    '<id="foo" data-test="1000">',
    '<id data-test>',
    '<select name="foo" id="bar" empty-value-test="" selected disabled><option value="1">Option 1</option></select>'
);

foreach($test as $t) {
    var_dump($t, extract_html_attributes($t));
    echo '<hr>';
}

Create a directory if it does not exist and then create the files in that directory as well

Using java.nio.Path it would be quite simple -

public static Path createFileWithDir(String directory, String filename) {
        File dir = new File(directory);
        if (!dir.exists()) dir.mkdirs();
        return Paths.get(directory + File.separatorChar + filename);
    }

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

As far as I can tell, both syntaxes are equivalent. The first is SQL standard, the second is MySQL's extension.

So they should be exactly equivalent performance wise.

http://dev.mysql.com/doc/refman/5.6/en/insert.html says:

INSERT inserts new rows into an existing table. The INSERT ... VALUES and INSERT ... SET forms of the statement insert rows based on explicitly specified values. The INSERT ... SELECT form inserts rows selected from another table or tables.

Android Camera : data intent returns null

The following code works for me:

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 2);

And here is the result:

protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{ 
    super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

    if(resultCode == RESULT_OK)
    {
        Uri selectedImage = imageReturnedIntent.getData();
        ImageView photo = (ImageView) findViewById(R.id.add_contact_label_photo);
        Bitmap mBitmap = null;
        try
        {
            mBitmap = Media.getBitmap(this.getContentResolver(), selectedImage);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

How to find current transaction level?

SELECT CASE  
          WHEN transaction_isolation_level = 1 
             THEN 'READ UNCOMMITTED' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 1 
             THEN 'READ COMMITTED SNAPSHOT' 
          WHEN transaction_isolation_level = 2 
               AND is_read_committed_snapshot_on = 0 THEN 'READ COMMITTED' 
          WHEN transaction_isolation_level = 3 
             THEN 'REPEATABLE READ' 
          WHEN transaction_isolation_level = 4 
             THEN 'SERIALIZABLE' 
          WHEN transaction_isolation_level = 5 
             THEN 'SNAPSHOT' 
          ELSE NULL
       END AS TRANSACTION_ISOLATION_LEVEL 
FROM   sys.dm_exec_sessions AS s
       CROSS JOIN sys.databases AS d
WHERE  session_id = @@SPID
  AND  d.database_id = DB_ID();

Convert a 1D array to a 2D array in numpy

import numpy as np
array = np.arange(8) 
print("Original array : \n", array)
array = np.arange(8).reshape(2, 4)
print("New array : \n", array)

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

Adding image inside table cell in HTML

Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.

jQuery: load txt file and insert into div

Try

$(".text").text(data);

Or to convert the data received to a string.

not:first-child selector

One of the versions you posted actually works for all modern browsers (where CSS selectors level 3 are supported):

div ul:not(:first-child) {
    background-color: #900;
}

If you need to support legacy browsers, or if you are hindered by the :not selector's limitation (it only accepts a simple selector as an argument) then you can use another technique:

Define a rule that has greater scope than what you intend and then "revoke" it conditionally, limiting its scope to what you do intend:

div ul {
    background-color: #900;  /* applies to every ul */
}

div ul:first-child {
    background-color: transparent; /* limits the scope of the previous rule */
}

When limiting the scope use the default value for each CSS attribute that you are setting.

How to split a string, but also keep the delimiters?

A very naive solution, that doesn't involve regex would be to perform a string replace on your delimiter along the lines of (assuming comma for delimiter):

string.replace(FullString, "," , "~,~")

Where you can replace tilda (~) with an appropriate unique delimiter.

Then if you do a split on your new delimiter then i believe you will get the desired result.

Boolean vs boolean in Java

Boolean is threadsafe, so you can consider this factor as well along with all other listed in answers

What's the best way to do a backwards loop in C/C#/C++?

In C I like to do this:


int i = myArray.Length;
while (i--) {
  myArray[i] = 42;
}

C# example added by MusiGenesis:

{int i = myArray.Length; while (i-- > 0)
{
    myArray[i] = 42;
}}

How do I get rid of the "cannot empty the clipboard" error?

I have seen various answers which say when I uninstalled this or that it worked. I think that the uninstall is probably just sorting out an issue in the registry, rather it being an issue with the particular application that is being uninstalled.

I have also seen cases of people saying kill the RDP task but I don't have that and I still have the error.

I have seen cases of people saying clear the clipboard in Excel, but that doesn't work for me - nor does changing the settings in the Clipboard.

I believe that the issue is that an application has a lock on the clipboard and that application is not releasing it. The clipboard is a shared resource, so that implies that each application has to get a lock on it before changing it and then release the lock once it has completed the change, however, it looks like sometimes the lock is not released.

I found that the following cured it. Close down all MS applications including IE and Outlook. Check Task Manager processes to make sure that they are all gone.

Then restart the application where you had the Copy and Paste issue and it will probably then work.

Regards

Paul Simon

What are the ascii values of up down left right?

If you're programming in OpenGL, use GLUT. The following page should help: http://www.lighthouse3d.com/opengl/glut/index.php?5

GLUT_KEY_LEFT   Left function key
GLUT_KEY_RIGHT  Right function key
GLUT_KEY_UP     Up function key
GLUT_KEY_DOWN   Down function key

 

void processSpecialKeys(int key, int x, int y) {

switch(key) {
    case GLUT_KEY_F1 : 
            red = 1.0; 
            green = 0.0; 
            blue = 0.0; break;
    case GLUT_KEY_F2 : 
            red = 0.0; 
            green = 1.0; 
            blue = 0.0; break;
    case GLUT_KEY_F3 : 
            red = 0.0; 
            green = 0.0; 
            blue = 1.0; break;
}
}

Get Return Value from Stored procedure in asp.net

Procedure never returns a value.You have to use a output parameter in store procedure.

ALTER PROC TESTLOGIN
@UserName   varchar(50),
@password   varchar(50)
@retvalue int output
 as
 Begin
    declare @return     int 
    set @return  = (Select COUNT(*) 
    FROM    CPUser  
    WHERE   UserName = @UserName AND Password = @password)

   set @retvalue=@return
  End

Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.

Possible to extend types in Typescript?

you can intersect types:

type TypeA = {
    nameA: string;
};
type TypeB = {
    nameB: string;
};
export type TypeC = TypeA & TypeB;

somewhere in you code you can now do:

const some: TypeC = {
    nameB: 'B',
    nameA: 'A',
};

How do I remove the old history from a git repository?

Just create a graft of the parent of your new root commit to no parent (or to an empty commit, e.g. the real root commit of your repository). E.g. echo "<NEW-ROOT-SHA1>" > .git/info/grafts

After creating the graft, it takes effect right away; you should be able to look at git log and see that the unwanted old commits have gone away:

$ echo 4a46bc886318679d8b15e05aea40b83ff6c3bd47 > .git/info/grafts
$ git log --decorate | tail --lines=11
commit cb3da2d4d8c3378919844b29e815bfd5fdc0210c
Author: Your Name <[email protected]>
Date:   Fri May 24 14:04:10 2013 +0200

    Another message

commit 4a46bc886318679d8b15e05aea40b83ff6c3bd47 (grafted)
Author: Your Name <[email protected]>
Date:   Thu May 23 22:27:48 2013 +0200

    Some message

If all looks as intended, you can just do a simple git filter-branch -- --all to make it permanent.

BEWARE: after doing the filter-branch step, all commit ids will have changed, so anybody using the old repo must never merge with anyone using the new repo.

Vim: insert the same characters across multiple lines

An alternative that can be more flexible:

Example: To enter the text XYZ at the beginning of the line

:%norm IXYZ

What's happening here?

  • % == Execute on every line
  • norm == Execute the following keys in normal mode
  • I == Insert at beginning of line
  • XYZ == The text you want to enter

Then you hit Enter, and it executes.

Specific to your request:

:%norm Ivendor_

You can also choose a particular range:

:2,4norm Ivendor_

Or execute over a selected visual range:

:'<,'>norm Ivendor_

findViewById in Fragment

Try This:

View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);

return v;

How can I remove the gloss on a select element in Safari on Mac?

Sorry to pile on to an old item. I found partial answers to my questions here but had to do some work so I wanted to share my results for the next person.

I ended up using the same approach as the other contributors, but with a few tweaks to fix the following

  1. Long text was covering the arrows in the other solutions
  2. The image being used was a somewhat old and ugly up/down combo arrow.

The below will give you a working solution with the above issues fixed. Note: I used a white arrow for my use case, you may need to change the color of the arrow for yours.

here's a preview:

select with white arrow

select{    
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgaWQ9IkxheWVyXzEiICAgZGF0YS1uYW1lPSJMYXllciAxIiAgIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIiAgIHZlcnNpb249IjEuMSIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxIHIxMzcyNSIgICBzb2RpcG9kaTpkb2NuYW1lPSJkb3dubG9hZC5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE0MjAyIj4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgIDwvY2M6V29yaz4gICAgPC9yZGY6UkRGPiAgPC9tZXRhZGF0YT4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9IjEwMjciICAgICBpZD0ibmFtZWR2aWV3NDIwMCIgICAgIHNob3dncmlkPSJmYWxzZSIgICAgIGlua3NjYXBlOnpvb209Ijg0LjMiICAgICBpbmtzY2FwZTpjeD0iMi40NzQ5OTk5IiAgICAgaW5rc2NhcGU6Y3k9IjUiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyNyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjEiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJMYXllcl8xIiAvPiAgPGRlZnMgICAgIGlkPSJkZWZzNDE5MCI+ICAgIDxzdHlsZSAgICAgICBpZD0ic3R5bGU0MTkyIj4uY2xzLTJ7ZmlsbDojNDQ0O308L3N0eWxlPiAgPC9kZWZzPiAgPHRpdGxlICAgICBpZD0idGl0bGU0MTk0Ij5hcnJvd3M8L3RpdGxlPiAgPHBvbHlnb24gICAgIGNsYXNzPSJjbHMtMiIgICAgIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIiAgICAgaWQ9InBvbHlnb240MTk4IiAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MSIgLz48L3N2Zz4=) no-repeat 101% 50%;
  padding-right:20px;
}

Get a file name from a path

this is the only thing that actually finally worked for me:

#include "Shlwapi.h"

CString some_string = "c:\\path\\hello.txt";
LPCSTR file_path = some_string.GetString();
LPCSTR filepart_c = PathFindFileName(file_path);
LPSTR filepart = LPSTR(filepart_c);
PathRemoveExtension(filepart);

pretty much what Skrymsli suggested but doesn't work with wchar_t*, VS Enterprise 2015

_splitpath worked as well, but I don't like having to guess at how many char[?] characters I'm going to need; some people probably need this control, i guess.

CString c_model_name = "c:\\path\\hello.txt";
char drive[200];
char dir[200];
char name[200];
char ext[200];
_splitpath(c_model_name, drive, dir, name, ext);

I don't believe any includes were needed for _splitpath. No external libraries (like boost) were needed for either of these solutions.

How to use SharedPreferences in Android to store, fetch and edit values

To store values in shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.apply();

To retrieve values from shared preferences:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name", "");
if(!name.equalsIgnoreCase(""))
{
    name = name + "  Sethi";  /* Edit the value here*/
}

How to make Twitter bootstrap modal full screen

I've came up with a "responsive" solution for fullscreen modals:

Fullscreen Modals that can be enabled only on certain breakpoints. In this way the modal will display "normal" on wider (desktop) screens and fullscreen on smaller (tablet or mobile) screens, giving it the feeling of a native app.

Implemented for Bootstrap 3 and Bootstrap 4. Included by default in Bootstrap 5.


Bootstrap v5

Fullscreen modals are included by default in Bootstrap 5: https://getbootstrap.com/docs/5.0/components/modal/#fullscreen-modal


Bootstrap v4

The following generic code should work:

.modal {
  padding: 0 !important; // override inline padding-right added from js
}
.modal .modal-dialog {
  width: 100%;
  max-width: none;
  height: 100%;
  margin: 0;
}
.modal .modal-content {
  height: 100%;
  border: 0;
  border-radius: 0;
}
.modal .modal-body {
  overflow-y: auto;
}

By including the scss code below, it generates the following classes that need to be added to the .modal element:

+---------------+---------+---------+---------+---------+---------+
|               |   xs    |   sm    |   md    |   lg    |   xl    | 
|               | <576px  | =576px  | =768px  | =992px  | =1200px |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen    |  100%   | default | default | default | default | 
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-sm |  100%   |  100%   | default | default | default | 
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-md |  100%   |  100%   |  100%   | default | default |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-lg |  100%   |  100%   |  100%   |  100%   | default |
+---------------+---------+---------+---------+---------+---------+
|.fullscreen-xl |  100%   |  100%   |  100%   |  100%   |  100%   |
+---------------+---------+---------+---------+---------+---------+

The scss code is:

@mixin modal-fullscreen() {
  padding: 0 !important; // override inline padding-right added from js

  .modal-dialog {
    width: 100%;
    max-width: none;
    height: 100%;
    margin: 0;
  }

  .modal-content {
    height: 100%;
    border: 0;
    border-radius: 0;
  }

  .modal-body {
    overflow-y: auto;
  }

}

@each $breakpoint in map-keys($grid-breakpoints) {
  @include media-breakpoint-down($breakpoint) {
    $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

    .modal-fullscreen#{$infix} {
      @include modal-fullscreen();
    }
  }
}

Demo on Codepen: https://codepen.io/andreivictor/full/MWYNPBV/


Bootstrap v3

Based on previous responses to this topic (@Chris J, @kkarli), the following generic code should work:

.modal {
  padding: 0 !important; // override inline padding-right added from js
}

.modal .modal-dialog {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

.modal .modal-content {
  height: auto;
  min-height: 100%;
  border: 0 none;
  border-radius: 0;
  box-shadow: none;
}

If you want to use responsive fullscreen modals, use the following classes that need to be added to .modal element:

  • .modal-fullscreen-md-down - the modal is fullscreen for screens smaller than 1200px.
  • .modal-fullscreen-sm-down - the modal is fullscreen for screens smaller than 922px.
  • .modal-fullscreen-xs-down - the modal is fullscreen for screen smaller than 768px.

Take a look at the following code:

/* Extra small devices (less than 768px) */
@media (max-width: 767px) {
  .modal-fullscreen-xs-down {
    padding: 0 !important;
  }
  .modal-fullscreen-xs-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-xs-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  } 
}

/* Small devices (less than 992px) */
@media (max-width: 991px) {
  .modal-fullscreen-sm-down {
    padding: 0 !important;
  }
  .modal-fullscreen-sm-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-sm-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }
}

/* Medium devices (less than 1200px) */
@media (max-width: 1199px) {
  .modal-fullscreen-md-down {
    padding: 0 !important;
  }
  .modal-fullscreen-md-down .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }
  .modal-fullscreen-md-down .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }
}

Demo is available on Codepen: https://codepen.io/andreivictor/full/KXNdoO.

Those who use Sass as a preprocessor can take advantage of the following mixin:

@mixin modal-fullscreen() {
  padding: 0 !important; // override inline padding-right added from js

  .modal-dialog {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
  }

  .modal-content {
    height: auto;
    min-height: 100%;
    border: 0 none;
    border-radius: 0;
    box-shadow: none;
  }

}

How can I get a channel ID from YouTube?

At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA.

Update Fragment from ViewPager

A very simple yet effective solution to update your fragment views. Use setUserVisibleHint() method. It will be called upon when the fragment is about to be visible to user. There you can update our view (setText() or setVisibility() etc.)

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if(isVisibleToUser){
       //Write your code to be executed when it is visible to user
    }
}

It worked in my case. Hope it helps!

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Merge Cell values with PHPExcel - PHP

There is a specific method to do this:

$objPHPExcel->getActiveSheet()->mergeCells('A1:C1');

You can also use:

$objPHPExcel->setActiveSheetIndex(0)->mergeCells('A1:C1');

That should do the trick.

Draw text in OpenGL ES

Rendering text to a texture is simpler than what the Sprite Text demo make it looks like, the basic idea is to use the Canvas class to render to a Bitmap and then pass the Bitmap to an OpenGL texture:

// Create an empty, mutable bitmap
Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bitmap);
bitmap.eraseColor(0);

// get a background image from resources
// note the image format must match the bitmap format
Drawable background = context.getResources().getDrawable(R.drawable.background);
background.setBounds(0, 0, 256, 256);
background.draw(canvas); // draw the background to our bitmap

// Draw the text
Paint textPaint = new Paint();
textPaint.setTextSize(32);
textPaint.setAntiAlias(true);
textPaint.setARGB(0xff, 0x00, 0x00, 0x00);
// draw the text centered
canvas.drawText("Hello World", 16,112, textPaint);

//Generate one texture pointer...
gl.glGenTextures(1, textures, 0);
//...and bind it to our array
gl.glBindTexture(GL10.GL_TEXTURE_2D, textures[0]);

//Create Nearest Filtered Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);

//Different possible texture parameters, e.g. GL10.GL_CLAMP_TO_EDGE
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT);

//Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

//Clean up
bitmap.recycle();

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

Delete package-lock.json file and then try to install

Get the string within brackets in Python

This should do the job:

re.match(r"[^[]*\[([^]]*)\]", yourstring).groups()[0]

"Fatal error: Unable to find local grunt." when running "grunt" command

I had this issue on my Windows grunt because I installed the 32 bit version of Node on a 64 bit Windows OS. When I installed the 64bit version specifically, it started working.

Angular - Can't make ng-repeat orderBy work

Here's a version of @Julian Mosquera's code that also supports sorting by object key:

yourApp.filter('orderObjectBy', function () {
    return function (items, field, reverse) {
        // Build array
        var filtered = [];
        for (var key in items) {
            if (field === 'key')
                filtered.push(key);
            else
                filtered.push(items[key]);
        }
        // Sort array
        filtered.sort(function (a, b) {
            if (field === 'key')
                return (a > b ? 1 : -1);
            else
                return (a[field] > b[field] ? 1 : -1);
        });
        // Reverse array
        if (reverse)
            filtered.reverse();
        return filtered;
    };
});

HTTP Error 500.19 and error code : 0x80070021

In my case, there were rules for IIS URL Rewrite module but I didn't have that module installed. You should check your web.config if there are any modules included but not installed.

How do I load a PHP file into a variable?

If you are using http://, as eyze suggested, you will only be able to read the ouput of the PHP script. You can only read the PHP script itself if it is on the same server as your running script. You could then use something like

$Vdata = file_get_contents('/path/to/your/file.php");

Get the key corresponding to the minimum value within a dictionary

>>> d = {320:1, 321:0, 322:3}
>>> min(d, key=lambda k: d[k]) 
321

Why is the Android emulator so slow? How can we speed up the Android emulator?

After developing for a while, my emulator became brutally slow. I chose wipe user data, and it was much much better. I am guessing that it takes time to load up each APK file you've deployed.

Maven artifact and groupId naming

Consider this to get a fully unique jar file:

  • GroupID - com.companyname.project
  • ArtifactId - com-companyname-project
  • Package - com.companyname.project

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

How to initialize java.util.date to empty

An instance of Date always represents a date and cannot be empty. You can use a null value of date2 to represent "there is no date". You will have to check for null whenever you use date2 to avoid a NullPointerException, like when rendering your page:

if (date2 != null)
  // print date2
else
  // print nothing, or a default value

Dealing with multiple Python versions and PIP?

pip is also a python package. So the easiest way to install modules to a specific python version would be below

 python2.7 /usr/bin/pip install foo

or

python2.7 -m pip install foo

Find out a Git branch creator

A branch is nothing but a commit pointer. As such, it doesn't track metadata like "who created me." See for yourself. Try cat .git/refs/heads/<branch> in your repository.

That written, if you're really into tracking this information in your repository, check out branch descriptions. They allow you to attach arbitrary metadata to branches, locally at least.

Also DarVar's answer below is a very clever way to get at this information.

Twig ternary operator, Shorthand if-then-else

Support for the extended ternary operator was added in Twig 1.12.0.

  1. If foo echo yes else echo no:

    {{ foo ? 'yes' : 'no' }}
    
  2. If foo echo it, else echo no:

    {{ foo ?: 'no' }}
    

    or

    {{ foo ? foo : 'no' }}
    
  3. If foo echo yes else echo nothing:

    {{ foo ? 'yes' }}
    

    or

    {{ foo ? 'yes' : '' }}
    
  4. Returns the value of foo if it is defined and not null, no otherwise:

    {{ foo ?? 'no' }}
    
  5. Returns the value of foo if it is defined (empty values also count), no otherwise:

    {{ foo|default('no') }}
    

Set a DateTime database field to "Now"

Use GETDATE()

Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

UPDATE table SET date = GETDATE()

Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?

The pattern matches all non-digit characters. This will restrict you to non-negative integers, but for your example it will be more than sufficient.

string input = "0, 10, 20, 30, 100, 200";
Regex.Split(input, @"\D+");

Image comparison - fast algorithm

This post was the starting point of my solution, lots of good ideas here so I though I would share my results. The main insight is that I've found a way to get around the slowness of keypoint-based image matching by exploiting the speed of phash.

For the general solution, it's best to employ several strategies. Each algorithm is best suited for certain types of image transformations and you can take advantage of that.

At the top, the fastest algorithms; at the bottom the slowest (though more accurate). You might skip the slow ones if a good match is found at the faster level.

  • file-hash based (md5,sha1,etc) for exact duplicates
  • perceptual hashing (phash) for rescaled images
  • feature-based (SIFT) for modified images

I am having very good results with phash. The accuracy is good for rescaled images. It is not good for (perceptually) modified images (cropped, rotated, mirrored, etc). To deal with the hashing speed we must employ a disk cache/database to maintain the hashes for the haystack.

The really nice thing about phash is that once you build your hash database (which for me is about 1000 images/sec), the searches can be very, very fast, in particular when you can hold the entire hash database in memory. This is fairly practical since a hash is only 8 bytes.

For example, if you have 1 million images it would require an array of 1 million 64-bit hash values (8 MB). On some CPUs this fits in the L2/L3 cache! In practical usage I have seen a corei7 compare at over 1 Giga-hamm/sec, it is only a question of memory bandwidth to the CPU. A 1 Billion-image database is practical on a 64-bit CPU (8GB RAM needed) and searches will not exceed 1 second!

For modified/cropped images it would seem a transform-invariant feature/keypoint detector like SIFT is the way to go. SIFT will produce good keypoints that will detect crop/rotate/mirror etc. However the descriptor compare is very slow compared to hamming distance used by phash. This is a major limitation. There are a lot of compares to do, since there are maximum IxJxK descriptor compares to lookup one image (I=num haystack images, J=target keypoints per haystack image, K=target keypoints per needle image).

To get around the speed issue, I tried using phash around each found keypoint, using the feature size/radius to determine the sub-rectangle. The trick to making this work well, is to grow/shrink the radius to generate different sub-rect levels (on the needle image). Typically the first level (unscaled) will match however often it takes a few more. I'm not 100% sure why this works, but I can imagine it enables features that are too small for phash to work (phash scales images down to 32x32).

Another issue is that SIFT will not distribute the keypoints optimally. If there is a section of the image with a lot of edges the keypoints will cluster there and you won't get any in another area. I am using the GridAdaptedFeatureDetector in OpenCV to improve the distribution. Not sure what grid size is best, I am using a small grid (1x3 or 3x1 depending on image orientation).

You probably want to scale all the haystack images (and needle) to a smaller size prior to feature detection (I use 210px along maximum dimension). This will reduce noise in the image (always a problem for computer vision algorithms), also will focus detector on more prominent features.

For images of people, you might try face detection and use it to determine the image size to scale to and the grid size (for example largest face scaled to be 100px). The feature detector accounts for multiple scale levels (using pyramids) but there is a limitation to how many levels it will use (this is tunable of course).

The keypoint detector is probably working best when it returns less than the number of features you wanted. For example, if you ask for 400 and get 300 back, that's good. If you get 400 back every time, probably some good features had to be left out.

The needle image can have less keypoints than the haystack images and still get good results. Adding more doesn't necessarily get you huge gains, for example with J=400 and K=40 my hit rate is about 92%. With J=400 and K=400 the hit rate only goes up to 96%.

We can take advantage of the extreme speed of the hamming function to solve scaling, rotation, mirroring etc. A multiple-pass technique can be used. On each iteration, transform the sub-rectangles, re-hash, and run the search function again.

Android - R cannot be resolved to a variable

You want Clean Project Like this

click on

Projects>Clean>select your project

this will help to u

Converting float to char*

In Arduino:

//temporarily holds data from vals
char charVal[10];                

//4 is mininum width, 3 is precision; float value is copied onto buff
dtostrf(123.234, 4, 3, charVal);

monitor.print("charVal: ");
monitor.println(charVal);

How to change Elasticsearch max memory size

If you use the service wrapper provided in Elasticsearch's Github repository, found at https://github.com/elasticsearch/elasticsearch-servicewrapper, then the conf file at elasticsearch-servicewrapper / service / elasticsearch.conf controls memory settings. At the top of elasticsearch.conf is a parameter:

set.default.ES_HEAP_SIZE=1024

Just reduce this parameter, say to "set.default.ES_HEAP_SIZE=512", to reduce Elasticsearch's allotted memory.

Note that if you use the elasticsearch-wrapper, the ES_HEAP_SIZE provided in elasticsearch.conf OVERRIDES ALL OTHER SETTINGS. This took me a bit to figure out, since from the documentation, it seemed that heap memory could be set from elasticsearch.yml.

If your service wrapper settings are set somewhere else, such as at /etc/default/elasticsearch as in James's example, then set the ES_HEAP_SIZE there.

How do I pass multiple ints into a vector at once?

using vector::insert (const_iterator position, initializer_list il); http://www.cplusplus.com/reference/vector/vector/insert/

#include <iostream>
#include <vector>

int main() {
  std::vector<int> vec;
  vec.insert(vec.end(),{1,2,3,4});
  return 0;
}

Tools for creating Class Diagrams

I always use Gliffy works perfectly and does lots of things including class diagrams.

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

HTML character codes for this ? or this ?

There are several correct ways to display a down-pointing and upward-pointing triangle.

Method 1 : use decimal HTML entity

HTML :

&#9650;
&#9660;

Method 2 : use hexidecimal HTML entity

HTML :

&#x25B2;
&#x25BC;

Method 3 : use character directly

HTML :

?
?

Method 4 : use CSS

HTML :

<span class='icon-up'></span>
<span class='icon-down'></span>

CSS :

.icon-up:before {
    content: "\25B2";
}

.icon-down:before {
    content: "\25BC";
}

Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. &hearts; to display ?).

You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/.

Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like ?,?,?,?,?,? or ?, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated.

If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this.


Background images

A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols.

This following code is the base64 for and SVG version of the enter image description here icon :

/* size: 0.9kb */
url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4=

When to use background-images or fonts

For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences:

SVG images

  • They can have multiple colors
  • They can embed their own CSS and/or be styled by the HTML document
  • They can be loaded as a seperate file, embedded in CSS AND embedded in HTML
  • Each symbol is represented by XML code or base64 code. You cannot use the character directly within your code editor or use an HTML entity
  • Multiple uses of the same symbol implies duplication of the symbol when XML code is embedded in the HTML. Duplication is not required when embedding the file in the CSS or loading it as a seperate file
  • You can not use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually.
  • You need some knowledge of SVG and/or base64 encoding
  • Limited or no support in old versions of IE

Icon fonts

  • An icon can have but one fill color, one background color, etc.
  • An icon can be embedded in CSS or HTML. In HTML, you can use the character directly or use an HTML entity to represent it.
  • Some symbols can be displayed without the use of a webfont. Most symbols cannot.
  • Multiple uses of the same symbol implies duplication of the symbol when your character embedded in the HTML. Duplication is not required when embedding the file in the CSS.
  • You can use color, font-size, line-height, background-color or other font related styling rules to change the display of your icon
  • You need no special technical knowledge
  • Support in all major browsers, including old versions of IE

Personally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color, background-color and other color-related CSS rules for fonts.

The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Map with Key as String and Value as List in Groovy

you don't need to declare Map groovy internally recognizes it

def personDetails = [firstName:'John', lastName:'Doe', fullName:'John Doe']

// print the values..
    println "First Name: ${personDetails.firstName}"
    println "Last Name: ${personDetails.lastName}"

http://grails.asia/groovy-map-tutorial

PHP 7: Missing VCRUNTIME140.dll

For things like this, you don't blindly keep clicking 'Next', 'Next', and 'I Agree'.

WAMP informs you about this during and before installation:

The MSVC runtime libraries VC9, VC10, VC11 are required for Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions with VC11. Runtimes VC13, VC14 is required for PHP 7 and Apache 2.4.17

VC9 Packages (Visual C++ 2008 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=5582 http://www.microsoft.com/en-us/download/details.aspx?id=2092

VC10 Packages (Visual C++ 2010 SP1) http://www.microsoft.com/en-us/download/details.aspx?id=8328 http://www.microsoft.com/en-us/download/details.aspx?id=13523

VC11 Packages (Visual C++ 2012 Update 4) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=30679

VC13 Packages] (Visual C++ 2013[) The two files VSU4\vcredist_x86.exe and VSU4\vcredist_x64.exe to be download are on the same page: https://www.microsoft.com/en-us/download/details.aspx?id=40784

VC14 Packages (Visual C++ 2015) The two files vcredist_x86.exe and vcredist_x64.exe to be download are on the same page: http://www.microsoft.com/en-us/download/details.aspx?id=48145

You must install both 32 and 64bit versions, even if you do not use Wampserver 64 bit.

IMPORTANT NOTE: Be sure to to run all Microsoft Visual C++ installations with administrator privileges (right click ? Run as Administrator). Just missing this small step wasted my entire day.

Ignore mapping one property with Automapper

Hello All Please Use this it's working fine... for auto mapper use multiple .ForMember in C#

        if (promotionCode.Any())
        {
            Mapper.Reset();
            Mapper.CreateMap<PromotionCode, PromotionCodeEntity>().ForMember(d => d.serverTime, o => o.MapFrom(s => s.promotionCodeId == null ? "date" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", DateTime.UtcNow.AddHours(7.0))))
                .ForMember(d => d.day, p => p.MapFrom(s => s.code != "" ? LeftTime(Convert.ToInt32(s.quantity), Convert.ToString(s.expiryDate), Convert.ToString(DateTime.UtcNow.AddHours(7.0))) : "Day"))
                .ForMember(d => d.subCategoryname, o => o.MapFrom(s => s.subCategoryId == 0 ? "" : Convert.ToString(subCategory.Where(z => z.subCategoryId.Equals(s.subCategoryId)).FirstOrDefault().subCategoryName)))
                .ForMember(d => d.optionalCategoryName, o => o.MapFrom(s => s.optCategoryId == 0 ? "" : Convert.ToString(optionalCategory.Where(z => z.optCategoryId.Equals(s.optCategoryId)).FirstOrDefault().optCategoryName)))
                .ForMember(d => d.logoImg, o => o.MapFrom(s => s.vendorId == 0 ? "" : Convert.ToString(vendorImg.Where(z => z.vendorId.Equals(s.vendorId)).FirstOrDefault().logoImg)))
                .ForMember(d => d.expiryDate, o => o.MapFrom(s => s.expiryDate == null ? "" : String.Format("{0:dd/MM/yyyy h:mm:ss tt}", s.expiryDate))); 
            var userPromotionModel = Mapper.Map<List<PromotionCode>, List<PromotionCodeEntity>>(promotionCode);
            return userPromotionModel;
        }
        return null;

Automatically running a batch file as an administrator

Use

runas /savecred /profile /user:Administrator whateveryouwanttorun.cmd

It will ask for the password the first time only. It will not ask for password again, unless the password is changed, etc.

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

Unfortunately MyApp has stopped. How can I solve this?

Let me share a basic Logcat analysis for when you meet a Force Close (when the app stops working).

DOCS

The basic tool from Android to collect/analyze logs is the logcat.

HERE is the Android's page about logcat

If you use android Studio, you can also check this LINK.

Capturing

Basically, you can MANUALLY capture logcat with the following command (or just check AndroidMonitor window in AndroidStudio):

adb logcat

There's a lot of parameters you can add to the command which helps you to filter and display the message that you want... This is personal... I always use the command below to get the message timestamp:

adb logcat -v time

You can redirect the output to a file and analyze it in a Text Editor.

Analyzing

If you app is Crashing, you'll get something like:

07-09 08:29:13.474 21144-21144/com.example.khan.abc D/AndroidRuntime: Shutting down VM
07-09 08:29:13.475 21144-21144/com.example.khan.abc E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.khan.abc, PID: 21144
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.onBackPressed()' on a null object reference
     at com.example.khan.abc.AudioFragment$1.onClick(AudioFragment.java:125)
     at android.view.View.performClick(View.java:4848)
     at android.view.View$PerformClick.run(View.java:20262)
     at android.os.Handler.handleCallback(Handler.java:815)
     at android.os.Handler.dispatchMessage(Handler.java:104)
     at android.os.Looper.loop(Looper.java:194)
     at android.app.ActivityThread.main(ActivityThread.java:5631)
     at java.lang.reflect.Method.invoke(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:372)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
07-09 08:29:15.195 21144-21144/com.example.khan.abc I/Process: Sending signal. PID: 21144 SIG: 9

This part of the log shows you a lot of information:

  • When the issue happened: 07-09 08:29:13.475

It is important to check when the issue happened... You may find several errors in a log... you must be sure that you are checking the proper messages :)

  • Which app crashed: com.example.khan.abc

This way, you know which app crashed (to be sure that you are checking the logs about your message)

  • Which ERROR: java.lang.NullPointerException

A NULL Pointer Exception error

  • Detailed info about the error: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.onBackPressed()' on a null object reference

You tried to call method onBackPressed() from a FragmentActivity object. However, that object was null when you did it.

  • Stack Trace: Stack Trace shows you the method invocation order... Sometimes, the error happens in the calling method (and not in the called method).

    at com.example.khan.abc.AudioFragment$1.onClick(AudioFragment.java:125)

Error happened in file com.example.khan.abc.AudioFragment.java, inside onClick() method at line: 125 (stacktrace shows the line that error happened)

It was called by:

at android.view.View.performClick(View.java:4848)

Which was called by:

at android.view.View$PerformClick.run(View.java:20262)

which was called by:

at android.os.Handler.handleCallback(Handler.java:815)

etc....

Overview

This was just an overview... Not all logs are simple but the error gives specific problem and verbose shows up all problem ... It is just to share the idea and provide entry-level information to you...

I hope I could help you someway... Regards

Detect if the device is iPhone X

The best and easiest way to detect if the device is iPhone X is,

https://github.com/stephanheilner/UIDevice-DisplayName

var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 , value != 0 else { return identifier}
            return identifier + String(UnicodeScalar(UInt8(value)))}

And identifier is either "iPhone10,3" or "iPhone10,6" for iPhone X.

Visual Studio 2008 Product Key in Registry?

For 32 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Registration\PIDKEY


For 64 bit Windows:


Visual Studio 2003:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\7.0\Registration\PIDKEY

Visual Studio 2005:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\8.0\Registration\PIDKEY

Visual Studio 2008:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Registration\PIDKEY


Notes:

  • Data is a GUID without dashes. Put a dash ( – ) after every 5 characters to convert to product key.
  • If PIDKEY value is empty try to look at the subfolders e.g.

    ...\Registration\1000.0x0000\PIDKEY

    or

    ...\Registration\2000.0x0000\PIDKEY

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

Insert Update trigger how to determine if insert or update

In first scenario I supposed that your table have IDENTITY column

CREATE TRIGGER [dbo].[insupddel_yourTable] ON [yourTable]
FOR INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0 return
SET NOCOUNT ON;
DECLARE @action nvarchar(10)
SELECT @action = CASE WHEN COUNT(i.Id) > COUNT(d.Id) THEN 'inserted'
                      WHEN COUNT(i.Id) < COUNT(d.Id) THEN 'deleted' ELSE 'updated' END
FROM inserted i FULL JOIN deleted d ON i.Id = d.Id

In second scenario don't need to use IDENTITTY column

CREATE TRIGGER [dbo].[insupddel_yourTable] ON [yourTable]
FOR INSERT, UPDATE, DELETE
AS
IF @@ROWCOUNT = 0 return
SET NOCOUNT ON;
DECLARE @action nvarchar(10),
        @insCount int = (SELECT COUNT(*) FROM inserted),
        @delCount int = (SELECT COUNT(*) FROM deleted)
SELECT @action = CASE WHEN @insCount > @delCount THEN 'inserted'
                      WHEN @insCount < @delCount THEN 'deleted' ELSE 'updated' END

Best way to concatenate List of String objects?

If you are developing for Android, there is TextUtils.join provided by the SDK.

What should every programmer know about security?

The importance of secure defaults in frameworks and APIs:

  • Lots of early web frameworks didn't escape html by default in templates and had XSS problems because of this
  • Lots of early web frameworks made it easier to concatenate SQL than to create parameterized queries leading to lots of SQL injection bugs.
  • Some versions of Erlang (R13B, maybe others) don't verify ssl peer certificates by default and there are probably lots of erlang code that is susceptible to SSL MITM attacks
  • Java's XSLT transformer by default allows execution of arbitrary java code. There has been many serious security bugs created by this.
  • Java's XML parsing APIs by default allow the parsed document to read arbitrary files on the filesystem. More fun :)

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

Can we instantiate an abstract class directly?

No, you can never instantiate an abstract class. That's the purpose of an abstract class. The getProvider method you are referring to returns a specific implementation of the abstract class. This is the abstract factory pattern.

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How to open the terminal in Atom?

In current versions of Mac Catalina

  1. go to packages tab --> Settings View ---> Install Packages/Themes ---> +Install button --> add "platformio-ide-terminal"

  2. control ~ to get the terminal

Export query result to .csv file in SQL Server 2008

  1. Open SQL Server Management Studio
  2. Go to Tools > Options > Query Results > SQL Server > Results To Text
  3. On the far right, there is a drop down box called Output Format
  4. Choose Comma Delimited and click OK

Here's a full screen version of that image, below

enter image description here

This will show your query results as comma-delimited text.

To save the results of a query to a file: Ctrl + Shift + F

Node.js Logging

Log4js is one of the most popular logging library for nodejs application.

It supports many cool features:

  1. Coloured console logging
  2. Replacement of node's console.log functions (optional)
  3. File appender, with log rolling based on file size
  4. SMTP, GELF, hook.io, Loggly appender
  5. Multiprocess appender (useful when you've got worker processes)
  6. A logger for connect/express servers
  7. Configurable log message layout/patterns
  8. Different log levels for different log categories (make some parts of your app log as DEBUG, others only ERRORS, etc.)

Example:

  1. Installation: npm install log4js

  2. Configuration (./config/log4js.json):

    {"appenders": [
        {
            "type": "console",
            "layout": {
                "type": "pattern",
                "pattern": "%m"
            },
            "category": "app"
        },{
            "category": "test-file-appender",
            "type": "file",
            "filename": "log_file.log",
            "maxLogSize": 10240,
            "backups": 3,
            "layout": {
                "type": "pattern",
                "pattern": "%d{dd/MM hh:mm} %-5p %m"
            }
        }
    ],
    "replaceConsole": true }
    
  3. Usage:

    var log4js = require( "log4js" );
    log4js.configure( "./config/log4js.json" );
    var logger = log4js.getLogger( "test-file-appender" );
    // log4js.getLogger("app") will return logger that prints log to the console
    logger.debug("Hello log4js");// store log in file
    

__FILE__, __LINE__, and __FUNCTION__ usage in C++

Personally, I'm reluctant to use these for anything but debugging messages. I have done it, but I try not to show that kind of information to customers or end users. My customers are not engineers and are sometimes not computer savvy. I might log this info to the console, but, as I said, reluctantly except for debug builds or for internal tools. I suppose it does depend on the customer base you have, though.

Completely removing phpMyAdmin

Try purge

sudo aptitude purge phpmyadmin

Not sure this works with plain old apt-get though

How to put img inline with text

This should display the image inline:

.content-dir-item img.mail {
    display: inline-block;
    *display: inline; /* for older IE */
    *zoom: 1; /* for older IE */
}

Where in an Eclipse workspace is the list of projects stored?

You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.

Viewing full output of PS command

simple and perfect:

ps -efww

won't truncate line

What is the regex for "Any positive integer, excluding 0"

You might want this (edit: allow number of the form 0123):

^\\+?[1-9]$|^\\+?\d+$

however, if it were me, I would instead do

int x = Integer.parseInt(s)
if (x > 0) {...}

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

Change the database.php file from

$db['default']['dbdriver'] = 'mysql';

to

$db['default']['dbdriver'] = 'mysqli';

Call and receive output from Python script in Java?

Jython approach

Java is supposed to be platform independent, and to call a native application (like python) isn't very platform independent.

There is a version of Python (Jython) which is written in Java, which allow us to embed Python in our Java programs. As usually, when you are going to use external libraries, one hurdle is to compile and to run it correctly, therefore we go through the process of building and running a simple Java program with Jython.

We start by getting hold of jython jar file:

https://www.jython.org/download.html

I copied jython-2.5.3.jar to the directory where my Java program was going to be. Then I typed in the following program, which do the same as the previous two; take two numbers, sends them to python, which adds them, then python returns it back to our Java program, where the number is outputted to the screen:

import org.python.util.PythonInterpreter; 
import org.python.core.*; 

class test3{
    public static void main(String a[]){

        PythonInterpreter python = new PythonInterpreter();

        int number1 = 10;
        int number2 = 32;
        python.set("number1", new PyInteger(number1));
        python.set("number2", new PyInteger(number2));
        python.exec("number3 = number1+number2");
        PyObject number3 = python.get("number3");
        System.out.println("val : "+number3.toString());
    }
}

I call this file "test3.java", save it, and do the following to compile it:

javac -classpath jython-2.5.3.jar test3.java

The next step is to try to run it, which I do the following way:

java -classpath jython-2.5.3.jar:. test3

Now, this allows us to use Python from Java, in a platform independent manner. It is kind of slow. Still, it's kind of cool, that it is a Python interpreter written in Java.

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime to UNIX timestamp:

public static double DateTimeToUnixTimestamp(DateTime dateTime)
{
    return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
           new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
}

Check cell for a specific letter or set of letters

Just use = IF(A1="Bla*","YES","NO"). When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.

How to find length of a string array?

I think you are looking for this

String[] car = new String[10];
int size = car.length;

Escape double quotes in parameter

I'm calling powershell from cmd, and passing quotes and neither escapes here worked. The grave accent worked to escape double quotes on this Win 10 surface pro.

>powershell.exe "echo la`"" >> test
>type test
la"

Below are outputs I got for other characters to escape a double quote:

la\
la^
la
la~

Using another quote to escape a quote resulted in no quotes. As you can see, the characters themselves got typed, but didn't escape the double quotes.

Delete all rows in an HTML table

this would work iteration deletetion in HTML table in native

document.querySelectorAll("table tbody tr").forEach(function(e){e.remove()})

DateTimeFormat in TypeScript

This should work...

var displayDate = new Date().toLocaleDateString();

alert(displayDate);

But I suspect you are trying it on something else, for example:

var displayDate = Date.now.toLocaleDateString(); // No!

alert(displayDate);

How do I pull from a Git repository through an HTTP proxy?

Worth to mention: Most examples on the net show examples like

git config --global http.proxy proxy_user:proxy_passwd@proxy_ip:proxy_port

So it seems, that - if your proxy needs authentication - you must leave your company-password in the git-config. Which isn't really cool.

But, if you just configure the user without password:

git config --global http.proxy proxy_user@proxy_ip:proxy_port

Git seems (at least on my Windows-machine without credentials-helper) to recognize that and prompts for the proxy-password on repo-access.

Android: How do bluetooth UUIDs work?

It usually represents some common service (protocol) that bluetooth device supports.

When creating your own rfcomm server (with listenUsingRfcommWithServiceRecord), you should specify your own UUID so that the clients connecting to it could identify it; it is one of the reasons why createRfcommSocketToServiceRecord requires an UUID parameter.

Otherwise, some common services have the same UUID, just find one you need and use it.

See here

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For Boto3 , use this code.

import boto3
from botocore.client import Config


s3 = boto3.resource('s3',
        aws_access_key_id='xxxxxx',
        aws_secret_access_key='xxxxxx',
        region_name='us-south-1',
        config=Config(signature_version='s3v4')
        )

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

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

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

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

Running SQL Server 2008 R2

EditorFor() and html properties

I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.

@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})

...and also validation works.

Disable scrolling in an iPhone web application?

document.addEventListener('touchstart', function (e) {
    e.preventDefault();
});

Do not use the ontouchmove property to register the event handler as you are running at risk of overwriting an existing event handler(s). Use addEventListener instead (see the note about IE on the MDN page).

Beware that preventing default for the touchstart event on the window or document will disable scrolling of the descending areas.

To prevent the scrolling of the document but leave all the other events intact prevent default for the first touchmove event following touchstart:

var firstMove;

window.addEventListener('touchstart', function (e) {
    firstMove = true;
});

window.addEventListener('touchmove', function (e) {
    if (firstMove) {
        e.preventDefault();

        firstMove = false;
    }
});

The reason this works is that mobile Safari is using the first move to determine if body of the document is being scrolled. I have realised this while devising a more sophisticated solution.

In case this would ever stop working, the more sophisticated solution is to inspect the touchTarget element and its parents and make a map of directions that can be scrolled to. Then use the first touchmove event to detect the scroll direction and see if it is going to scroll the document or the target element (or either of the target element parents):

var touchTarget,
    touchScreenX,
    touchScreenY,
    conditionParentUntilTrue,
    disableScroll,
    scrollMap;

conditionParentUntilTrue = function (element, condition) {
    var outcome;

    if (element === document.body) {
        return false;
    }

    outcome = condition(element);

    if (outcome) {
        return true;
    } else {
        return conditionParentUntilTrue(element.parentNode, condition);
    }
};

window.addEventListener('touchstart', function (e) {
    touchTarget = e.targetTouches[0].target;
    // a boolean map indicating if the element (or either of element parents, excluding the document.body) can be scrolled to the X direction.
    scrollMap = {}

    scrollMap.left = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollLeft > 0;
    });

    scrollMap.top = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollTop > 0;
    });

    scrollMap.right = conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollWidth > element.clientWidth &&
               element.scrollWidth - element.clientWidth > element.scrollLeft;
    });

    scrollMap.bottom =conditionParentUntilTrue(touchTarget, function (element) {
        return element.scrollHeight > element.clientHeight &&
               element.scrollHeight - element.clientHeight > element.scrollTop;
    });

    touchScreenX = e.targetTouches[0].screenX;
    touchScreenY = e.targetTouches[0].screenY;
    disableScroll = false;
});

window.addEventListener('touchmove', function (e) {
    var moveScreenX,
        moveScreenY;

    if (disableScroll) {
        e.preventDefault();

        return;
    }

    moveScreenX = e.targetTouches[0].screenX;
    moveScreenY = e.targetTouches[0].screenY;

    if (
        moveScreenX > touchScreenX && scrollMap.left ||
        moveScreenY < touchScreenY && scrollMap.bottom ||
        moveScreenX < touchScreenX && scrollMap.right ||
        moveScreenY > touchScreenY && scrollMap.top
    ) {
        // You are scrolling either the element or its parent.
        // This will not affect document.body scroll.
    } else {
        // This will affect document.body scroll.

        e.preventDefault();

        disableScroll = true;
    }
});

The reason this works is that mobile Safari is using the first touch move to determine if the document body is being scrolled or the element (or either of the target element parents) and sticks to this decision.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

MongoDB query with an 'or' condition

Just thought I'd update in-case anyone stumbles across this page in the future. As of 1.5.3, mongo now supports a real $or operator: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24or

Your query of "(expires >= Now()) OR (expires IS NULL)" can now be rendered as:

{$or: [{expires: {$gte: new Date()}}, {expires: null}]}

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

How to comment out a block of Python code in Vim

one way manually

:set number
:10,12s/^/#

C#: How would I get the current time into a string?

string t = DateTime.Now.ToString("h/m/s tt");
string t2 = DateTime.Now.ToString("hh:mm:ss tt");
string d = DateTime.Now.ToString("MM/dd/yy");

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

It is possible to do everything you want. Aaron's answer was not quite complete.

His approach is correct, up to creating the temporary table in the inner query. Then, you need to insert the results into a table in the outer query.

The following code snippet grabs the first line of a file and inserts it into the table @Lines:

declare @fieldsep char(1) = ',';
declare @recordsep char(1) = char(10);

declare @Lines table (
    line varchar(8000)
);

declare @sql varchar(8000) = ' 
    create table #tmp (
        line varchar(8000)
    );

    bulk insert #tmp
        from '''+@filename+'''
        with (FirstRow = 1, FieldTerminator = '''+@fieldsep+''', RowTerminator = '''+@recordsep+''');

    select * from #tmp';

insert into @Lines
    exec(@sql);

select * from @lines

Mongod complains that there is no /data/db folder

After getting the same error as Nik

chown: id -u: Invalid argument

I found out this apparently occurred from using the wrong type of quotation marks (should have been backquotes) Ubuntu Forums

Instead I just used

sudo chown $USER /data/db

as an alternative and now mongod has the permissions it needs.

How to set label size in Bootstrap

In Bootstrap 3 they do not have separate classes for different styles of labels.

http://getbootstrap.com/components/

However, you can customize bootstrap classes that way. In your css file

.lb-sm {
  font-size: 12px;
}

.lb-md {
  font-size: 16px;
}

.lb-lg {
  font-size: 20px;
}

Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
_x000D_
_x000D_

They might add size classes for labels in future Bootstrap versions.

Import CSV file into SQL Server

Firs you need to import CSV file into Data Table

Then you can insert bulk rows using SQLBulkCopy

using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlBulkInsertExample
{
    class Program
    {
      static void Main(string[] args)
        {
            DataTable prodSalesData = new DataTable("ProductSalesData");

            // Create Column 1: SaleDate
            DataColumn dateColumn = new DataColumn();
            dateColumn.DataType = Type.GetType("System.DateTime");
            dateColumn.ColumnName = "SaleDate";

            // Create Column 2: ProductName
            DataColumn productNameColumn = new DataColumn();
            productNameColumn.ColumnName = "ProductName";

            // Create Column 3: TotalSales
            DataColumn totalSalesColumn = new DataColumn();
            totalSalesColumn.DataType = Type.GetType("System.Int32");
            totalSalesColumn.ColumnName = "TotalSales";

            // Add the columns to the ProductSalesData DataTable
            prodSalesData.Columns.Add(dateColumn);
            prodSalesData.Columns.Add(productNameColumn);
            prodSalesData.Columns.Add(totalSalesColumn);

            // Let's populate the datatable with our stats.
            // You can add as many rows as you want here!

            // Create a new row
            DataRow dailyProductSalesRow = prodSalesData.NewRow();
            dailyProductSalesRow["SaleDate"] = DateTime.Now.Date;
            dailyProductSalesRow["ProductName"] = "Nike";
            dailyProductSalesRow["TotalSales"] = 10;

            // Add the row to the ProductSalesData DataTable
            prodSalesData.Rows.Add(dailyProductSalesRow);

            // Copy the DataTable to SQL Server using SqlBulkCopy
            using (SqlConnection dbConnection = new SqlConnection("Data Source=ProductHost;Initial Catalog=dbProduct;Integrated Security=SSPI;Connection Timeout=60;Min Pool Size=2;Max Pool Size=20;"))
            {
                dbConnection.Open();
                using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
                {
                    s.DestinationTableName = prodSalesData.TableName;

                    foreach (var column in prodSalesData.Columns)
                        s.ColumnMappings.Add(column.ToString(), column.ToString());

                    s.WriteToServer(prodSalesData);
                }
            }
        }
    }
}

Update ViewPager dynamically?

I have lived same problem and I have searched too much times. Any answer given in stackoverflow or via google was not solution for my problem. My problem was easy. I have a list, I show this list with viewpager. When I add a new element to head of the list and I refresh the viewpager nothings changed. My final solution was very easy anybody can use. When a new element added to list and want to refresh the list. Firstly set viewpager adapter to null then recreate the adapter and set i to it to viewpager.

myVPager.setAdapter(null);
myFragmentAdapter = new MyFragmentAdapter(getSupportFragmentManager(),newList);
myVPager.setAdapter(myFragmentAdapter);

Be sure your adapter must extend FragmentStatePagerAdapter

In Javascript, how do I check if an array has duplicate values?

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

Documentation for using JavaScript code inside a PDF file

Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"

Revised: January 27, 1999

It’s very old, but it is still useful.

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

How to allow users to check for the latest app version from inside the app?

Navigate to your play page:

https://play.google.com/store/apps/details?id=com.yourpackage

Using a standard HTTP GET. Now the following jQuery finds important info for you:

Current Version

$("[itemprop='softwareVersion']").text()

What's new

$(".recent-change").each(function() { all += $(this).text() + "\n"; })

Now that you can extract these information manually, simply make a method in your app that executes this for you.

public static String[] getAppVersionInfo(String playUrl) {
    HtmlCleaner cleaner = new HtmlCleaner();
    CleanerProperties props = cleaner.getProperties();
    props.setAllowHtmlInsideAttributes(true);
    props.setAllowMultiWordAttributes(true);
    props.setRecognizeUnicodeChars(true);
    props.setOmitComments(true);
    try {
        URL url = new URL(playUrl);
        URLConnection conn = url.openConnection();
        TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
        Object[] new_nodes = node.evaluateXPath("//*[@class='recent-change']");
        Object[] version_nodes = node.evaluateXPath("//*[@itemprop='softwareVersion']");

        String version = "", whatsNew = "";
        for (Object new_node : new_nodes) {
            TagNode info_node = (TagNode) new_node;
            whatsNew += info_node.getAllChildren().get(0).toString().trim()
                    + "\n";
        }
        if (version_nodes.length > 0) {
            TagNode ver = (TagNode) version_nodes[0];
            version = ver.getAllChildren().get(0).toString().trim();
        }
        return new String[]{version, whatsNew};
    } catch (IOException | XPatherException e) {
        e.printStackTrace();
        return null;
    }
}

Uses HtmlCleaner

if condition in sql server update query

Since you're using SQL 2008:

UPDATE
    table_Name

SET
    column_A  
     = CASE
        WHEN @flag = '1' THEN @new_value
        ELSE 0
    END + column_A,

    column_B  
     = CASE
        WHEN @flag = '0' THEN @new_value
        ELSE 0
    END + column_B 
WHERE
    ID = @ID

If you were using SQL 2012:

UPDATE
    table_Name
SET
    column_A  = column_A + IIF(@flag = '1', @new_value, 0),
    column_B  = column_B + IIF(@flag = '0', @new_value, 0)
WHERE
    ID = @ID

What's the difference setting Embed Interop Types true and false in Visual Studio?

This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.

It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.

Read more in Scott Hanselman's blog post about it and other VS improvements here.

As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:

The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.

Apache 13 permission denied in user's home directory

Not sure if you've fixed it but in your httpd.conf

Check to see your User/Group settings. Usually it will be set to

User www Group www

If so change it to your name/group

User Greg group staff

Find out whether radio button is checked with JQuery?

jQuery is still popular, but if you want to have no dependencies, see below. Short & clear function to find out if radio button is checked on ES-2015:

_x000D_
_x000D_
function getValueFromRadioButton( name ){_x000D_
  return [...document.getElementsByName(name)]_x000D_
         .reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)_x000D_
}_x000D_
_x000D_
console.log( getValueFromRadioButton('payment') );
_x000D_
<div>  _x000D_
  <input type="radio" name="payment" value="offline">_x000D_
  <input type="radio" name="payment" value="online">_x000D_
  <input type="radio" name="payment" value="part" checked>_x000D_
  <input type="radio" name="payment" value="free">_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

How to margin the body of the page (html)?

For start you can use:

<body style="margin:0;padding:0">

Once you study a bit about css, you can change it to:

body {margin:0;padding:0}

in your stylesheet.

Hiding the address bar of a browser (popup)

What is the truth?

Microsoft's documentation describing the behaviour of their browser is correct.

Is there any solution to hide the addressbar?

No. If you could hide it, then you could use HTML/CSS to make something that looked like a common address bar. You could then put a different address in it. You could then trick people into thinking they were on a different site and entering their password for it.

It is impossible to conceal the user's location from them because it is essential for security that they know what their location is.

How to import spring-config.xml of one project into spring-config.xml of another project?

For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:

<import resource="classpath*:/spring-config.xml" />

sendUserActionEvent() is null

Even i face similar problem after I did some modification in code related to Cursor.

public boolean onContextItemSelected(MenuItem item) 
{
        AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
        Cursor c = (Cursor)adapter.getItem(info.position);
        long id = c.getLong(...);
        String tempCity = c.getString(...);
            //c.close();
...
}

After i commented out //c.close(); It is working fine. Try out at your end and update Initial setup is as... I have a list view in Fragment, and trying to delete and item from list via contextMenu.

C# string reference type?

As others have stated, the String type in .NET is immutable and it's reference is passed by value.

In the original code, as soon as this line executes:

test = "after passing";

then test is no longer referring to the original object. We've created a new String object and assigned test to reference that object on the managed heap.

I feel that many people get tripped up here since there's no visible formal constructor to remind them. In this case, it's happening behind the scenes since the String type has language support in how it is constructed.

Hence, this is why the change to test is not visible outside the scope of the TestI(string) method - we've passed the reference by value and now that value has changed! But if the String reference were passed by reference, then when the reference changed we will see it outside the scope of the TestI(string) method.

Either the ref or out keyword are needed in this case. I feel the out keyword might be slightly better suited for this particular situation.

class Program
{
    static void Main(string[] args)
    {
        string test = "before passing";
        Console.WriteLine(test);
        TestI(out test);
        Console.WriteLine(test);
        Console.ReadLine();
    }

    public static void TestI(out string test)
    {
        test = "after passing";
    }
}

How do I create ColorStateList programmatically?

The first dimension is an array of state sets, the second ist the state set itself. The colors array lists the colors for each matching state set, therefore the length of the colors array has to match the first dimension of the states array (or it will crash when the state is "used"). Here and example:

ColorStateList myColorStateList = new ColorStateList(
                        new int[][]{
                                new int[]{android.R.attr.state_pressed}, //1
                                new int[]{android.R.attr.state_focused}, //2
                                new int[]{android.R.attr.state_focused, android.R.attr.state_pressed} //3
                        },
                        new int[] {
                            Color.RED, //1
                            Color.GREEN, //2
                            Color.BLUE //3
                        }
                    );

hope this helps.

EDIT example: a xml color state list like:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/white"/>
    <item android:color="@color/black"/>
</selector>

would look like this

ColorStateList myColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{}
        },
        new int[] {
                context.getResources().getColor(R.color.white),
                context.getResources().getColor(R.color.black)
        }
);

Regular Expression For Duplicate Words

Try this regular expression:

\b(\w+)\s+\1\b

Here \b is a word boundary and \1 references the captured match of the first group.

Create zip file and ignore directory structure

Use the -j option:

   -j     Store  just the name of a saved file (junk the path), and do not
          store directory names. By default, zip will store the full  path
          (relative to the current path).