Programs & Examples On #Aurigma

How to do INSERT into a table records extracted from another table

Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.

  1. Open both recordsets
  2. Extract the data from the first table (SELECT blablabla)
  3. Update 2nd recordset with data available in the first recordset (either by adding new records or updating existing records
  4. Close both recordsets

This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)

Converting an integer to a hexadecimal string in Ruby

To summarize:

p 10.to_s(16) #=> "a"
p "%x" % 10 #=> "a"
p "%02X" % 10 #=> "0A"
p sprintf("%02X", 10) #=> "0A"
p "#%02X%02X%02X" % [255, 0, 10] #=> "#FF000A"

MYSQL Sum Query with IF Condition

Try with a CASE in this way :

SUM(CASE 
    WHEN PaymentType = "credit card" 
    THEN TotalAmount 
    ELSE 0 
END) AS CreditCardTotal,

Should give what you are looking for ...

Updating address bar with new URL without hash or reloading the page

Changing only what's after hash - old browsers

document.location.hash = 'lookAtMeNow';

Changing full URL. Chrome, Firefox, IE10+

history.pushState('data to be passed', 'Title of the page', '/test');

The above will add a new entry to the history so you can press Back button to go to the previous state. To change the URL in place without adding a new entry to history use

history.replaceState('data to be passed', 'Title of the page', '/test');

Try running these in the console now!

SQL query for today's date minus two months

SELECT COUNT(1)
FROM FB
WHERE
    Dte BETWEEN CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(DATEADD(month, -1, GETDATE())) AS VARCHAR(2)) + '-20 00:00:00'
        AND CAST(YEAR(GETDATE()) AS VARCHAR(4)) + '-' + CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-20 00:00:00'

Command failed due to signal: Segmentation fault: 11

In my case, I was trying to extend a CoreData class with a helper method that could work on all of its subclasses:

extension ExampleCoreDataClass {
   static func insert() -> Self {
   ...

I got no warnings about this, but when I tried to compile it the segmentation fault appeared.

After struggling for a while I used a protocol extension instead and this resolved the error:

extension NSFetchRequestResult where Self: ExampleCoreDataClass {
   static func insert() -> Self {
   ...

The FastCGI process exited unexpectedly

You might be using C:/[your-php-directory]/php.exe in Handler mapping of IIS just change it C:/[your-php-directory]/php-cgi.exe.

Link to all Visual Studio $ variables

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

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

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

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

How to make graphics with transparent background in R using ggplot2?

Updated with the theme() function, ggsave() and the code for the legend background:

df <- data.frame(y = d, x = 1, group = rep(c("gr1", "gr2"), 50))
p <- ggplot(df) +
  stat_boxplot(aes(x = x, y = y, color = group), 
               fill = "transparent" # for the inside of the boxplot
  ) 

Fastest way is using using rect, as all the rectangle elements inherit from rect:

p <- p +
  theme(
        rect = element_rect(fill = "transparent") # all rectangles
      )
    p

More controlled way is to use options of theme:

p <- p +
  theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent") # get rid of legend panel bg
  )
p

To save (this last step is important):

ggsave(p, filename = "tr_tst2.png",  bg = "transparent")

HTML-encoding lost when attribute read from input field

Here is a simple javascript solution. It extends String object with a method "HTMLEncode" which can be used on an object without parameter, or with a parameter.

String.prototype.HTMLEncode = function(str) {
  var result = "";
  var str = (arguments.length===1) ? str : this;
  for(var i=0; i<str.length; i++) {
     var chrcode = str.charCodeAt(i);
     result+=(chrcode>128) ? "&#"+chrcode+";" : str.substr(i,1)
   }
   return result;
}
// TEST
console.log("stetaewteaw æø".HTMLEncode());
console.log("stetaewteaw æø".HTMLEncode("æåøåæå"))

I have made a gist "HTMLEncode method for javascript".

How to decorate a class?

Here is an example which answers the question of returning the parameters of a class. Moreover, it still respects the chain of inheritance, i.e. only the parameters of the class itself are returned. The function get_params is added as a simple example, but other functionalities can be added thanks to the inspect module.

import inspect 

class Parent:
    @classmethod
    def get_params(my_class):
        return list(inspect.signature(my_class).parameters.keys())

class OtherParent:
    def __init__(self, a, b, c):
        pass

class Child(Parent, OtherParent):
    def __init__(self, x, y, z):
        pass

print(Child.get_params())
>>['x', 'y', 'z']

Convert nested Python dict to object?

Let me explain a solution I almost used some time ago. But first, the reason I did not is illustrated by the fact that the following code:

d = {'from': 1}
x = dict2obj(d)

print x.from

gives this error:

  File "test.py", line 20
    print x.from == 1
                ^
SyntaxError: invalid syntax

Because "from" is a Python keyword there are certain dictionary keys you cannot allow.


Now my solution allows access to the dictionary items by using their names directly. But it also allows you to use "dictionary semantics". Here is the code with example usage:

class dict2obj(dict):
    def __init__(self, dict_):
        super(dict2obj, self).__init__(dict_)
        for key in self:
            item = self[key]
            if isinstance(item, list):
                for idx, it in enumerate(item):
                    if isinstance(it, dict):
                        item[idx] = dict2obj(it)
            elif isinstance(item, dict):
                self[key] = dict2obj(item)

    def __getattr__(self, key):
        return self[key]

d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

x = dict2obj(d)

assert x.a == x['a'] == 1
assert x.b.c == x['b']['c'] == 2
assert x.d[1].foo == x['d'][1]['foo'] == "bar"

Difference between "enqueue" and "dequeue"

A queue is a certain 2-sided data structure. You can add new elements on one side, and remove elements from the other side (as opposed to a stack that has only one side). Enqueue means to add an element, dequeue to remove an element. Please have a look here.

How to catch SQLServer timeout exceptions

Updated for c# 6:

    try
    {
        // some code
    }
    catch (SqlException ex) when (ex.Number == -2)  // -2 is a sql timeout
    {
        // handle timeout
    }

Very simple and nice to look at!!

How to read single Excel cell value

The issue with reading single Excel Cell in .Net comes from the fact, that the empty cell is evaluated to a Null. Thus, one cannot use its .Value or .Value2 properties, because an error shows up.

To return an empty string, when the cell is Null the Convert.ToString(Cell) can be used in the following way:

Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);

for (int i = 1; i < 5; i++)
{
    string a = Convert.ToString(wk.Cells[i, 1].Value2);
    Console.WriteLine(a);
}

Is a LINQ statement faster than a 'foreach' loop?

I was interested in this question, so I did a test just now. Using .NET Framework 4.5.2 on an Intel(R) Core(TM) i3-2328M CPU @ 2.20GHz, 2200 Mhz, 2 Core(s) with 8GB ram running Microsoft Windows 7 Ultimate.

It looks like LINQ might be faster than for each loop. Here are the results I got:

Exists = True
Time   = 174
Exists = True
Time   = 149

It would be interesting if some of you could copy & paste this code in a console app and test as well. Before testing with an object (Employee) I tried the same test with integers. LINQ was faster there as well.

public class Program
{
    public class Employee
    {
        public int id;
        public string name;
        public string lastname;
        public DateTime dateOfBirth;

        public Employee(int id,string name,string lastname,DateTime dateOfBirth)
        {
            this.id = id;
            this.name = name;
            this.lastname = lastname;
            this.dateOfBirth = dateOfBirth;

        }
    }

    public static void Main() => StartObjTest();

    #region object test

    public static void StartObjTest()
    {
        List<Employee> items = new List<Employee>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(new Employee(i,"name" + i,"lastname" + i,DateTime.Today));
        }

        Test3(items, items.Count-100);
        Test4(items, items.Count - 100);

        Console.Read();
    }


    public static void Test3(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item.id == idToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test4(List<Employee> items, int idToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Exists(e => e.id == idToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion


    #region int test
    public static void StartIntTest()
    {
        List<int> items = new List<int>();

        for (int i = 0; i < 10000000; i++)
        {
            items.Add(i);
        }

        Test1(items, -100);
        Test2(items, -100);

        Console.Read();
    }

    public static void Test1(List<int> items,int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = false;
        foreach (var item in items)
        {
            if (item == itemToCheck)
            {
                exists = true;
                break;
            }
        }

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    public static void Test2(List<int> items, int itemToCheck)
    {

        Stopwatch s = new Stopwatch();
        s.Start();

        bool exists = items.Contains(itemToCheck);

        Console.WriteLine("Exists=" + exists);
        Console.WriteLine("Time=" + s.ElapsedMilliseconds);

    }

    #endregion

}

difference between iframe, embed and object elements

Another reason to use object over iframe is that object sub resources (when an <object> performs HTTP requests) are considered as passive/display in terms of Mixed content, which means it's more secure when you must have Mixed content.

Mixed content means that when you have https but your resource is from http.

Reference: https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content

Check if a class `active` exist on element with jquery

$(document).ready(function()
{
  changeColor = $(.active).css("color","any color");
  if($(".classname").hasClass('active')) {
  $(this).eq(changeColor);
  }
});

How to add New Column with Value to the Existing DataTable?

//Data Table

 protected DataTable tblDynamic
        {
            get
            {
                return (DataTable)ViewState["tblDynamic"];
            }
            set
            {
                ViewState["tblDynamic"] = value;
            }
        }
//DynamicReport_GetUserType() function for getting data from DB


System.Data.DataSet ds = manage.DynamicReport_GetUserType();
                tblDynamic = ds.Tables[13];

//Add Column as "TypeName"

                tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));

//fill column data against ds.Tables[13]


                for (int i = 0; i < tblDynamic.Rows.Count; i++)
                {

                    if (tblDynamic.Rows[i]["Type"].ToString()=="A")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Apple";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "B")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Ball";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "C")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Cat";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "D")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Dog;
                    }
                }

Reset MySQL root password using ALTER USER statement after install on Mac

Here is the way works for me.

mysql> show databases ;

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

mysql> uninstall plugin validate_password;

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

mysql> alter user 'root'@'localhost' identified by 'root';

Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;

Query OK, 0 rows affected (0.03 sec)

Releasing memory in Python

I'm guessing the question you really care about here is:

Is there a way to force Python to release all the memory that was used (if you know you won't be using that much memory again)?

No, there is not. But there is an easy workaround: child processes.

If you need 500MB of temporary storage for 5 minutes, but after that you need to run for another 2 hours and won't touch that much memory ever again, spawn a child process to do the memory-intensive work. When the child process goes away, the memory gets released.

This isn't completely trivial and free, but it's pretty easy and cheap, which is usually good enough for the trade to be worthwhile.

First, the easiest way to create a child process is with concurrent.futures (or, for 3.1 and earlier, the futures backport on PyPI):

with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor:
    result = executor.submit(func, *args, **kwargs).result()

If you need a little more control, use the multiprocessing module.

The costs are:

  • Process startup is kind of slow on some platforms, notably Windows. We're talking milliseconds here, not minutes, and if you're spinning up one child to do 300 seconds' worth of work, you won't even notice it. But it's not free.
  • If the large amount of temporary memory you use really is large, doing this can cause your main program to get swapped out. Of course you're saving time in the long run, because that if that memory hung around forever it would have to lead to swapping at some point. But this can turn gradual slowness into very noticeable all-at-once (and early) delays in some use cases.
  • Sending large amounts of data between processes can be slow. Again, if you're talking about sending over 2K of arguments and getting back 64K of results, you won't even notice it, but if you're sending and receiving large amounts of data, you'll want to use some other mechanism (a file, mmapped or otherwise; the shared-memory APIs in multiprocessing; etc.).
  • Sending large amounts of data between processes means the data have to be pickleable (or, if you stick them in a file or shared memory, struct-able or ideally ctypes-able).

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

Change arrow colors in Bootstraps carousel

I hope this works, cheers.

_x000D_
_x000D_
.carousel-control-prev-icon,_x000D_
.carousel-control-next-icon {_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  outline: black;_x000D_
  background-size: 100%, 100%;_x000D_
  border-radius: 50%;_x000D_
  border: 1px solid black;_x000D_
  background-image: none;_x000D_
}_x000D_
_x000D_
.carousel-control-next-icon:after_x000D_
{_x000D_
  content: '>';_x000D_
  font-size: 55px;_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
.carousel-control-prev-icon:after {_x000D_
  content: '<';_x000D_
  font-size: 55px;_x000D_
  color: red;_x000D_
}
_x000D_
_x000D_
_x000D_

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

Why does Maven have such a bad rep?

Because Maven is a device for reducing grown men to sobbing masses of absolute terror.

how to pass variable from shell script to sqlplus

You appear to have a heredoc containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF

or if BUILDING is $2 in your script:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF

If your file.sql had an exit at the end then it would be even simpler as you wouldn't need the heredoc:

sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2

In your SQL you can then refer to the position parameters using substitution variables:

...
}',SEM_Models('&1'),NULL,
...

The &1 will be replaced with the first value passed to the SQL script, BUILDING; because that is a string it still needs to be enclosed in quotes. You might want to set verify off to stop if showing you the substitutions in the output.


You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1, the second is &2, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF

or:

sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF

If total_count is being passed to your shell script then just use its positional parameter, $4 or whatever. And your SQL would then be:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:

define MY_ALIAS = &1
define MY_MODEL = &2

SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

From your separate question, maybe you just wanted:

SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
        ?s rdf:type :ProcessSpec .
        ?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));

... so the alias will be the same value you're querying on (the value in $2, or BUILDING in the original part of the answer). You can refer to a substitution variable as many times as you want.

That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:

select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT

If you set pages 0 and set heading off, your repeated calls might appear in a neat list. You might also need to set tab off and possibly use rpad('&1', 20) or similar to make that column always the same width. Or get the results as CSV with:

select '&1' ||','|| COUNT(*)

Depends what you're using the results for...

select records from postgres where timestamp is in certain range

Search till the seconds for the timestamp column in postgress

select * from "TableName" e
    where timestamp >= '2020-08-08T13:00:00' and timestamp < '2020-08-08T17:00:00';

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Contain an image within a div?

Use max width and max height. It will keep the aspect ratio

#container img 
{
 max-width: 250px;
 max-height: 250px;
}

http://jsfiddle.net/rV77g/

Launching Google Maps Directions via an intent on Android

Using the latest cross-platform Google Maps URLs: Even if google maps app is missing it will open in browser

Example https://www.google.com/maps/dir/?api=1&origin=81.23444,67.0000&destination=80.252059,13.060604

Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
    .authority("www.google.com")
    .appendPath("maps")
    .appendPath("dir")
    .appendPath("")
    .appendQueryParameter("api", "1")
    .appendQueryParameter("destination", 80.00023 + "," + 13.0783);
String url = builder.build().toString();
Log.d("Directions", url);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

How to unnest a nested list

Use itertools.chain:

itertools.chain(*iterables):

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

The output is:

[1, 2, 3, 4]
[1, 2, 3, 4]

How to remove all null elements from a ArrayList or String Array?

As of 2015, this is the best way (Java 8):

tourists.removeIf(Objects::isNull);

Note: This code will throw java.lang.UnsupportedOperationException for fixed-size lists (such as created with Arrays.asList), including immutable lists.

laravel throwing MethodNotAllowedHttpException

well when i had these problem i faced 2 code errors

{!! Form::model(['method' => 'POST','route' => ['message.store']]) !!}

i corrected it by doing this

{!! Form::open(['method' => 'POST','route' => 'message.store']) !!}

so just to expatiate i changed the form model to open and also the route where wrongly placed in square braces.

Is iterating ConcurrentHashMap values thread safe?

What does it mean?

That means that each iterator you obtain from a ConcurrentHashMap is designed to be used by a single thread and should not be passed around. This includes the syntactic sugar that the for-each loop provides.

What happens if I try to iterate the map with two threads at the same time?

It will work as expected if each of the threads uses it's own iterator.

What happens if I put or remove a value from the map while iterating it?

It is guaranteed that things will not break if you do this (that's part of what the "concurrent" in ConcurrentHashMap means). However, there is no guarantee that one thread will see the changes to the map that the other thread performs (without obtaining a new iterator from the map). The iterator is guaranteed to reflect the state of the map at the time of it's creation. Futher changes may be reflected in the iterator, but they do not have to be.

In conclusion, a statement like

for (Object o : someConcurrentHashMap.entrySet()) {
    // ...
}

will be fine (or at least safe) almost every time you see it.

Can Powershell Run Commands in Parallel?

This has been answered thoroughly. Just want to post this method i have created based on Powershell-Jobs as a reference.

Jobs are passed on as a list of script-blocks. They can be parameterized. Output of the jobs is color-coded and prefixed with a job-index (just like in a vs-build-process, as this will be used in a build) Can be used to startup multiple servers at a time or running build steps in parallel or so..

function Start-Parallel {
    param(
        [ScriptBlock[]]
        [Parameter(Position = 0)]
        $ScriptBlock,

        [Object[]]
        [Alias("arguments")]
        $parameters
    )

    $jobs = $ScriptBlock | ForEach-Object { Start-Job -ScriptBlock $_ -ArgumentList $parameters }
    $colors = "Blue", "Red", "Cyan", "Green", "Magenta"
    $colorCount = $colors.Length

    try {
        while (($jobs | Where-Object { $_.State -ieq "running" } | Measure-Object).Count -gt 0) {
            $jobs | ForEach-Object { $i = 1 } {
                $fgColor = $colors[($i - 1) % $colorCount]
                $out = $_ | Receive-Job
                $out = $out -split [System.Environment]::NewLine
                $out | ForEach-Object {
                    Write-Host "$i> "-NoNewline -ForegroundColor $fgColor
                    Write-Host $_
                }
                
                $i++
            }
        }
    } finally {
        Write-Host "Stopping Parallel Jobs ..." -NoNewline
        $jobs | Stop-Job
        $jobs | Remove-Job -Force
        Write-Host " done."
    }
}

sample output:

sample output

jQuery event for images loaded

Waiting for all images to load...
I found the anwser to my problem with jfriend00 here jquery: how to listen to the image loaded event of one container div? .. and "if (this.complete)"
Waiting for the all thing to load and some possibly in cache !.. and i have added the "error" event... it's robust across all browsers

$(function() { // Wait dom ready
    var $img = $('img'), // images collection
        totalImg = $img.length,
        waitImgDone = function() {
            totalImg--;
            if (!totalImg) {
                console.log($img.length+" image(s) chargée(s) !");
            }
        };
    $img.each(function() {
        if (this.complete) waitImgDone(); // already here..
        else $(this).load(waitImgDone).error(waitImgDone); // completed...
    });
});

Demo : http://jsfiddle.net/molokoloco/NWjDb/

How do I redirect output to a variable in shell?

TL;DR

To store "abc" into $foo:

echo "abc" | read foo

But, because pipes create forks, you have to use $foo before the pipe ends, so...

echo "abc" | ( read foo; date +"I received $foo on %D"; )

Sure, all these other answers show ways to not do what the OP asked, but that really screws up the rest of us who searched for the OP's question.

The answer to the question is to use the read command.

Here's how you do it

# I would usually do this on one line, but for readability...
series | of | commands \
| \
(
  read string;
  mystic_command --opt "$string" /path/to/file
) \
| \
handle_mystified_file

Here is what it is doing and why it is important:

  1. Let's pretend that the series | of | commands is a very complicated series of piped commands.

  2. mystic_command can accept the content of a file as stdin in lieu of a file path, but not the --opt arg therefore it must come in as a variable. The command outputs the modified content and would commonly be redirected into a file or piped to another command. (E.g. sed, awk, perl, etc.)

  3. read takes stdin and places it into the variable $string

  4. Putting the read and the mystic_command into a "sub shell" via parenthesis is not necessary but makes it flow like a continuous pipe as if the 2 commands where in a separate script file.

There is always an alternative, and in this case the alternative is ugly and unreadable compared to my example above.

# my example above as a oneliner
series | of | commands | (read string; mystic_command --opt "$string" /path/to/file) | handle_mystified_file

# ugly and unreadable alternative
mystic_command --opt "$(series | of | commands)" /path/to/file | handle_mystified_file

My way is entirely chronological and logical. The alternative starts with the 4th command and shoves commands 1, 2, and 3 into command substitution.

I have a real world example of this in this script but I didn't use it as the example above because it has some other crazy/confusing/distracting bash magic going on also.

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

You need to replace it as WHERE clockDate = { fn CURRENT_DATE() } AND userName = 'test'. Please remove extra ")" from { fn CURRENT_DATE() })

Plot multiple boxplot in one graph

Since you don't mention a plot package , I propose here using Lattice version( I think there is more ggplot2 answers than lattice ones, at least since I am here in SO).

 ## reshaping the data( similar to the other answer)
 library(reshape2)
 dat.m <- melt(TestData,id.vars='Label')
 library(lattice)
 bwplot(value~Label |variable,    ## see the powerful conditional formula 
        data=dat.m,
        between=list(y=1),
        main="Bad or Good")

enter image description here

Fastest way to flatten / un-flatten nested JSON objects

Here is some code I wrote to flatten an object I was working with. It creates a new class that takes every nested field and brings it into the first layer. You could modify it to unflatten by remembering the original placement of the keys. It also assumes the keys are unique even across nested objects. Hope it helps.

class JSONFlattener {
    ojson = {}
    flattenedjson = {}

    constructor(original_json) {
        this.ojson = original_json
        this.flattenedjson = {}
        this.flatten()
    }

    flatten() {
        Object.keys(this.ojson).forEach(function(key){
            if (this.ojson[key] == null) {

            } else if (this.ojson[key].constructor == ({}).constructor) {
                this.combine(new JSONFlattener(this.ojson[key]).returnJSON())
            } else {
                this.flattenedjson[key] = this.ojson[key]
            }
        }, this)        
    }

    combine(new_json) {
        //assumes new_json is a flat array
        Object.keys(new_json).forEach(function(key){
            if (!this.flattenedjson.hasOwnProperty(key)) {
                this.flattenedjson[key] = new_json[key]
            } else {
                console.log(key+" is a duplicate key")
            }
        }, this)
    }

    returnJSON() {
        return this.flattenedjson
    }
}

console.log(new JSONFlattener(dad_dictionary).returnJSON())

As an example, it converts

nested_json = {
    "a": {
        "b": {
            "c": {
                "d": {
                    "a": 0
                }
            }
        }
    },
    "z": {
        "b":1
    },
    "d": {
        "c": {
            "c": 2
        }
    }
}

into

{ a: 0, b: 1, c: 2 }

Resize background image in div using css

i would recommend using this:

  background-repeat:no-repeat;
  background-image: url(your file location here);
  background-size:cover;(will only work with css3)

hope it helps :D

And if this doesnt support your needs just say it: i can make a jquery for multibrowser support.

Delimiter must not be alphanumeric or backslash and preg_match

Maybe not related to original code example, but I received the error "Delimiter must not be alphanumeric or backslash" and Googled here. Reason: I mixed order of parameters for preg_match. Pattern was the second parameter and string to match was first. Be careful :)

build maven project with propriatery libraries included

You could either add the jar to your project and mess around with the maven-assembly-plugin, or add the jar to your local repository:

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> -DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging> -DgeneratePom=true

Where: <path-to-file>  the path to the file to load
       <group-id>      the group that the file should be registered under
       <artifact-id>   the artifact name for the file
       <version>       the version of the file
       <packaging>     the packaging of the file e.g. jar

Remove element of a regular array

In a normal array you have to shuffle down all the array entries above 2 and then resize it using the Resize method. You might be better off using an ArrayList.

Change value in a cell based on value in another cell

by typing yes it wont charge taxes, by typing no it will charge taxes.

=IF(C39="Yes","0",IF(C39="no",PRODUCT(G36*0.0825)))

How to use if, else condition in jsf to display image

For those like I who just followed the code by skuntsel and received a cryptic stack trace, allow me to save you some time.

It seems c:if cannot by itself be followed by c:otherwise.

The correct solution is as follows:

<c:choose>
    <c:when test="#{some.test}">
        <p>some.test is true</p>
    </c:when>
    <c:otherwise>
        <p>some.test is not true</p>
    </c:otherwise>
</c:choose>

You can add additional c:when tests in as necessary.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Managing SSH keys within Jenkins for Git

According to this article, you may try following command:

   ssh-add -l

If your key isn't in the list, then

   ssh-add /var/lib/jenkins/.ssh/id_rsa_project

Setting a timeout for socket operations

Use the Socket() constructor, and connect(SocketAddress endpoint, int timeout) method instead.

In your case it would look something like:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);

Quoting from the documentation

connect

public void connect(SocketAddress endpoint, int timeout) throws IOException

Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

Parameters:

endpoint - the SocketAddress
timeout - the timeout value to be used in milliseconds.

Throws:

IOException - if an error occurs during the connection
SocketTimeoutException - if timeout expires before connecting
IllegalBlockingModeException - if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException - if endpoint is null or is a SocketAddress subclass not supported by this socket

Since: 1.4

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        @ResponseBody
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.

Eg:

ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);

Check if string matches pattern

One-liner: re.match(r"pattern", string) # No need to compile

import re
>>> if re.match(r"hello[0-9]+", 'hello1'):
...     print('Yes')
... 
Yes

You can evalute it as bool if needed

>>> bool(re.match(r"hello[0-9]+", 'hello1'))
True

bodyParser is deprecated express 4

Want zero warnings? Use it like this:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

Explanation: The default value of the extended option has been deprecated, meaning you need to explicitly pass true or false value.

How to generate a random string in Ruby

Since Ruby 2.5, it's really easy with SecureRandom.alphanumeric:

len = 8
SecureRandom.alphanumeric(len)
=> "larHSsgL"

It generates random strings containing A-Z, a-z and 0-9 and therefore should be applicable in most use-cases. And they are generated randomly secure, which might be a benefit, too.


This is a benchmark to compare it with the solution having the most upvotes:

require 'benchmark'
require 'securerandom'

len = 10
n = 100_000

Benchmark.bm(12) do |x|
  x.report('SecureRandom') { n.times { SecureRandom.alphanumeric(len) } }
  x.report('rand') do
    o = [('a'..'z'), ('A'..'Z'), (0..9)].map(&:to_a).flatten
    n.times { (0...len).map { o[rand(o.length)] }.join }
  end
end

                   user     system      total        real
SecureRandom   0.429442   0.002746   0.432188 (  0.432705)
rand           0.306650   0.000716   0.307366 (  0.307745)

So the rand solution only takes about 3/4 of the time of SecureRandom. That might matter if you generate a lot of strings, but if you just create some random string from time to time I'd always go with the more secure implementation since it is also easier to call and more explicit.

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

The width is being restricted by the size of the body. If you make the width of the body larger you will see it stays on one line with the background color.

To maintain the minimum width: min-width:100%

How do I clone a Django model instance object and save it to the database?

setting pk to None is better, sinse Django can correctly create a pk for you

object_copy = MyObject.objects.get(pk=...)
object_copy.pk = None
object_copy.save()

Hide Command Window of .BAT file that Executes Another .EXE File

I used this to start a cmd file from C#:

Process proc = new Process();
proc.StartInfo.WorkingDirectory = "myWorkingDirectory";
proc.StartInfo.FileName = "myFileName.cmd";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();

Job for mysqld.service failed See "systemctl status mysqld.service"

In my particular case, the error was appearing due to missing /var/log/mysql with mysql-server package 5.7.21-1 on Debian-based Linux distro. Having ran strace and sudo /usr/sbin/mysqld --daemonize --pid-file=/run/mysqld/mysqld.pid ( which is what the systemd service actually runs), it became apparent that the issue was due to this:

2019-01-01T09:09:22.102568Z 0 [ERROR] Could not open file '/var/log/mysql/error.log' for error logging: No such file or directory

I've recently removed contents of several directories in /var/log so it was no surprise. The solution was to create the directory and make it owned by mysql user as in

$ sudo mkdir /var/log/mysql
$ sudo chown -R mysql:mysql /var/log/mysql

Having done that I've happily logged in via sudo mysql -u root and greeted with the old and familiar mysql> prompt

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

Passing event and argument to v-on in Vue.js

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.

How to create empty folder in java?

Looks file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
    // Directory creation failed
}

Dealing with commas in a CSV file

You can use alternative "delimiters" like ";" or "|" but simplest might just be quoting which is supported by most (decent) CSV libraries and most decent spreadsheets.

For more on CSV delimiters and a spec for a standard format for describing delimiters and quoting see this webpage

Create parameterized VIEW in SQL Server 2008

in fact there exists one trick:

create view view_test as

select
  * 
from 
  table 
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)

... in sql-query:

set context_info 2
select * from view_test

will be the same with

select * from table where id = 2

but using udf is more acceptable

Jenkins - how to build a specific branch

This is extension of answer provided by Ranjith

I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter

And after that, you can specify branches to build. Branch to Build

Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"

You can also write a groovy script to fetch all your branches to in active choice parameter.

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

Display QImage with QtGui

Drawing an image using a QLabel seems like a bit of a kludge to me. With newer versions of Qt you can use a QGraphicsView widget. In Qt Creator, drag a Graphics View widget onto your UI and name it something (it is named mainImage in the code below). In mainwindow.h, add something like the following as private variables to your MainWindow class:

QGraphicsScene *scene;
QPixmap image;

Then just edit mainwindow.cpp and make the constructor something like this:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    image.load("myimage.png");
    scene = new QGraphicsScene(this);
    scene->addPixmap(image);
    scene->setSceneRect(image.rect());

    ui->mainImage->setScene(scene);
}

How to work on UAC when installing XAMPP

You can press OK and install xampp to C:\xampp and not into program files

How to check a string starts with numeric number?

See the isDigit(char ch) method:

https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Character.html

and pass it to the first character of the String using the String.charAt() method.

Character.isDigit(myString.charAt(0));

How can I do string interpolation in JavaScript?

If you want to interpolate in console.log output, then just

console.log("Eruption 1: %s", eruption1);
                         ^^

Here, %s is what is called a "format specifier". console.log has this sort of interpolation support built-in.

What is WEB-INF used for in a Java EE web application?

There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.

How to replace a substring of a string

In javascript:

var str = "abcdaaaaaabcdaabbccddabcd";
document.write(str.replace(/(abcd)/g,"----"));
//example output: ----aaaaa----aabbccdd----

In other languages, it would be something similar. Remember to enable global matches.

Plotting a list of (x, y) coordinates in python matplotlib

As per this example:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

will produce:

enter image description here

To unpack your data from pairs into lists use zip:

x, y = zip(*li)

So, the one-liner:

plt.scatter(*zip(*li))

How to make a radio button look like a toggle button

PURE CSS AND HTML (as asked) with ANIMATIONS!

Example Image (you can run the code below):

Toggle Buttons (Radio and Checkbox) in Pure CSS and HTML

After looking for something really clean and straight forward, I ended up building this with ONE simple change from another code that was built only thinking on checkboxes, so I tryed the funcionality for RADIOS and it worked too(!).

The CSS (SCSS) is fully from @mallendeo (as established on the JS credits), what I did was simply change the type of the input to RADIO, and gave the same name to all the radio switches.... and VOILA!! They deactivate automatically one to the other!!

Very clean, and as you asked it's only CSS and HTML!!

It is exactly what I was looking for since 3 days after trying and editing more than a dozen of options (which mostly requiered jQuery, or didn't allow labels, or even wheren't really compatible with current browsers). This one's got it all!

I'm obligated to include the code in here to allow you to see a working example, so:

_x000D_
_x000D_
/** Toggle buttons_x000D_
 * @mallendeo_x000D_
 * forked @davidtaubmann_x000D_
 * from https://codepen.io/mallendeo/pen/eLIiG_x000D_
 */
_x000D_
html, body {_x000D_
  display: -webkit-box;_x000D_
  display: -webkit-flex;_x000D_
  display: -ms-flexbox;_x000D_
  display: flex;_x000D_
  min-height: 100%;_x000D_
  -webkit-box-pack: center;_x000D_
  -webkit-justify-content: center;_x000D_
      -ms-flex-pack: center;_x000D_
          justify-content: center;_x000D_
  -webkit-box-align: center;_x000D_
  -webkit-align-items: center;_x000D_
      -ms-flex-align: center;_x000D_
          align-items: center;_x000D_
  -webkit-box-orient: vertical;_x000D_
  -webkit-box-direction: normal;_x000D_
  -webkit-flex-direction: column;_x000D_
      -ms-flex-direction: column;_x000D_
          flex-direction: column;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
ul, li {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
.tg-list {_x000D_
  text-align: center;_x000D_
  display: -webkit-box;_x000D_
  display: -webkit-flex;_x000D_
  display: -ms-flexbox;_x000D_
  display: flex;_x000D_
  -webkit-box-align: center;_x000D_
  -webkit-align-items: center;_x000D_
      -ms-flex-align: center;_x000D_
          align-items: center;_x000D_
}_x000D_
_x000D_
.tg-list-item {_x000D_
  margin: 0 10px;;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  color: #777;_x000D_
}_x000D_
_x000D_
h4 {_x000D_
  color: #999;_x000D_
}_x000D_
_x000D_
.tgl {_x000D_
  display: none;_x000D_
}_x000D_
.tgl, .tgl:after, .tgl:before, .tgl *, .tgl *:after, .tgl *:before, .tgl + .tgl-btn {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
.tgl::-moz-selection, .tgl:after::-moz-selection, .tgl:before::-moz-selection, .tgl *::-moz-selection, .tgl *:after::-moz-selection, .tgl *:before::-moz-selection, .tgl + .tgl-btn::-moz-selection {_x000D_
  background: none;_x000D_
}_x000D_
.tgl::selection, .tgl:after::selection, .tgl:before::selection, .tgl *::selection, .tgl *:after::selection, .tgl *:before::selection, .tgl + .tgl-btn::selection {_x000D_
  background: none;_x000D_
}_x000D_
.tgl + .tgl-btn {_x000D_
  outline: 0;_x000D_
  display: block;_x000D_
  width: 4em;_x000D_
  height: 2em;_x000D_
  position: relative;_x000D_
  cursor: pointer;_x000D_
  -webkit-user-select: none;_x000D_
     -moz-user-select: none;_x000D_
      -ms-user-select: none;_x000D_
          user-select: none;_x000D_
}_x000D_
.tgl + .tgl-btn:after, .tgl + .tgl-btn:before {_x000D_
  position: relative;_x000D_
  display: block;_x000D_
  content: "";_x000D_
  width: 50%;_x000D_
  height: 100%;_x000D_
}_x000D_
.tgl + .tgl-btn:after {_x000D_
  left: 0;_x000D_
}_x000D_
.tgl + .tgl-btn:before {_x000D_
  display: none;_x000D_
}_x000D_
.tgl:checked + .tgl-btn:after {_x000D_
  left: 50%;_x000D_
}_x000D_
_x000D_
.tgl-light + .tgl-btn {_x000D_
  background: #f0f0f0;_x000D_
  border-radius: 2em;_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .4s ease;_x000D_
  transition: all .4s ease;_x000D_
}_x000D_
.tgl-light + .tgl-btn:after {_x000D_
  border-radius: 50%;_x000D_
  background: #fff;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
}_x000D_
.tgl-light:checked + .tgl-btn {_x000D_
  background: #9FD6AE;_x000D_
}_x000D_
_x000D_
.tgl-ios + .tgl-btn {_x000D_
  background: #fbfbfb;_x000D_
  border-radius: 2em;_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .4s ease;_x000D_
  transition: all .4s ease;_x000D_
  border: 1px solid #e8eae9;_x000D_
}_x000D_
.tgl-ios + .tgl-btn:after {_x000D_
  border-radius: 2em;_x000D_
  background: #fbfbfb;_x000D_
  -webkit-transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;_x000D_
  transition: left 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275), padding 0.3s ease, margin 0.3s ease;_x000D_
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 0 rgba(0, 0, 0, 0.08);_x000D_
}_x000D_
.tgl-ios + .tgl-btn:hover:after {_x000D_
  will-change: padding;_x000D_
}_x000D_
.tgl-ios + .tgl-btn:active {_x000D_
  box-shadow: inset 0 0 0 2em #e8eae9;_x000D_
}_x000D_
.tgl-ios + .tgl-btn:active:after {_x000D_
  padding-right: .8em;_x000D_
}_x000D_
.tgl-ios:checked + .tgl-btn {_x000D_
  background: #86d993;_x000D_
}_x000D_
.tgl-ios:checked + .tgl-btn:active {_x000D_
  box-shadow: none;_x000D_
}_x000D_
.tgl-ios:checked + .tgl-btn:active:after {_x000D_
  margin-left: -.8em;_x000D_
}_x000D_
_x000D_
.tgl-skewed + .tgl-btn {_x000D_
  overflow: hidden;_x000D_
  -webkit-transform: skew(-10deg);_x000D_
          transform: skew(-10deg);_x000D_
  -webkit-backface-visibility: hidden;_x000D_
          backface-visibility: hidden;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  font-family: sans-serif;_x000D_
  background: #888;_x000D_
}_x000D_
.tgl-skewed + .tgl-btn:after, .tgl-skewed + .tgl-btn:before {_x000D_
  -webkit-transform: skew(10deg);_x000D_
          transform: skew(10deg);_x000D_
  display: inline-block;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  line-height: 2em;_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4);_x000D_
}_x000D_
.tgl-skewed + .tgl-btn:after {_x000D_
  left: 100%;_x000D_
  content: attr(data-tg-on);_x000D_
}_x000D_
.tgl-skewed + .tgl-btn:before {_x000D_
  left: 0;_x000D_
  content: attr(data-tg-off);_x000D_
}_x000D_
.tgl-skewed + .tgl-btn:active {_x000D_
  background: #888;_x000D_
}_x000D_
.tgl-skewed + .tgl-btn:active:before {_x000D_
  left: -10%;_x000D_
}_x000D_
.tgl-skewed:checked + .tgl-btn {_x000D_
  background: #86d993;_x000D_
}_x000D_
.tgl-skewed:checked + .tgl-btn:before {_x000D_
  left: -100%;_x000D_
}_x000D_
.tgl-skewed:checked + .tgl-btn:after {_x000D_
  left: 0;_x000D_
}_x000D_
.tgl-skewed:checked + .tgl-btn:active:after {_x000D_
  left: 10%;_x000D_
}_x000D_
_x000D_
.tgl-flat + .tgl-btn {_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  background: #fff;_x000D_
  border: 4px solid #f2f2f2;_x000D_
  border-radius: 2em;_x000D_
}_x000D_
.tgl-flat + .tgl-btn:after {_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  background: #f2f2f2;_x000D_
  content: "";_x000D_
  border-radius: 1em;_x000D_
}_x000D_
.tgl-flat:checked + .tgl-btn {_x000D_
  border: 4px solid #7FC6A6;_x000D_
}_x000D_
.tgl-flat:checked + .tgl-btn:after {_x000D_
  left: 50%;_x000D_
  background: #7FC6A6;_x000D_
}_x000D_
_x000D_
.tgl-flip + .tgl-btn {_x000D_
  padding: 2px;_x000D_
  -webkit-transition: all .2s ease;_x000D_
  transition: all .2s ease;_x000D_
  font-family: sans-serif;_x000D_
  -webkit-perspective: 100px;_x000D_
          perspective: 100px;_x000D_
}_x000D_
.tgl-flip + .tgl-btn:after, .tgl-flip + .tgl-btn:before {_x000D_
  display: inline-block;_x000D_
  -webkit-transition: all .4s ease;_x000D_
  transition: all .4s ease;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  position: absolute;_x000D_
  line-height: 2em;_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  -webkit-backface-visibility: hidden;_x000D_
          backface-visibility: hidden;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
.tgl-flip + .tgl-btn:after {_x000D_
  content: attr(data-tg-on);_x000D_
  background: #02C66F;_x000D_
  -webkit-transform: rotateY(-180deg);_x000D_
          transform: rotateY(-180deg);_x000D_
}_x000D_
.tgl-flip + .tgl-btn:before {_x000D_
  background: #FF3A19;_x000D_
  content: attr(data-tg-off);_x000D_
}_x000D_
.tgl-flip + .tgl-btn:active:before {_x000D_
  -webkit-transform: rotateY(-20deg);_x000D_
          transform: rotateY(-20deg);_x000D_
}_x000D_
.tgl-flip:checked + .tgl-btn:before {_x000D_
  -webkit-transform: rotateY(180deg);_x000D_
          transform: rotateY(180deg);_x000D_
}_x000D_
.tgl-flip:checked + .tgl-btn:after {_x000D_
  -webkit-transform: rotateY(0);_x000D_
          transform: rotateY(0);_x000D_
  left: 0;_x000D_
  background: #7FC6A6;_x000D_
}_x000D_
.tgl-flip:checked + .tgl-btn:active:after {_x000D_
  -webkit-transform: rotateY(20deg);_x000D_
          transform: rotateY(20deg);_x000D_
}
_x000D_
<h2>Toggle 'em</h2>_x000D_
<ul class='tg-list'>_x000D_
  <li class='tg-list-item'>_x000D_
    <h3>Radios:</h3>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd1'>_x000D_
      <h4>Light</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-light' id='rd1' name='group' type='radio'>_x000D_
    <label class='tgl-btn' for='rd1'></label>_x000D_
    <label class='tgl-btn' for='rd1'>_x000D_
      <h4>Light</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd2'>_x000D_
      <h4>iOS 7 (Disabled)</h4>_x000D_
    </label>_x000D_
    <input checked class='tgl tgl-ios' disabled id='rd2' name='group' type='radio'>_x000D_
    <label class='tgl-btn' for='rd2'></label>_x000D_
    <label class='tgl-btn' for='rd2'>_x000D_
      <h4>iOS 7 (Disabled)</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd3'>_x000D_
      <h4>Skewed</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-skewed' id='rd3' name='group' type='radio'>_x000D_
    <label class='tgl-btn' data-tg-off='OFF' data-tg-on='ON' for='rd3'></label>_x000D_
    <label class='tgl-btn' for='rd3'>_x000D_
      <h4>Skewed</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd4'>_x000D_
      <h4>Flat</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-flat' id='rd4' name='group' type='radio'>_x000D_
    <label class='tgl-btn' for='rd4'></label>_x000D_
    <label class='tgl-btn' for='rd4'>_x000D_
      <h4>Flat</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='rd5'>_x000D_
      <h4>Flip</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-flip' id='rd5' name='group' type='radio'>_x000D_
    <label class='tgl-btn' data-tg-off='Nope' data-tg-on='Yeah!' for='rd5'></label>_x000D_
    <label class='tgl-btn' for='rd5'>_x000D_
      <h4>Flip</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
</ul>_x000D_
<ul class='tg-list'>_x000D_
  <li class='tg-list-item'>_x000D_
    <h3>Checkboxes:</h3>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb1'>_x000D_
      <h4>Light</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-light' id='cb1' type='checkbox'>_x000D_
    <label class='tgl-btn' for='cb1'></label>_x000D_
    <label class='tgl-btn' for='cb1'>_x000D_
      <h4>Light</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb2'>_x000D_
      <h4>iOS 7</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-ios' id='cb2' type='checkbox'>_x000D_
    <label class='tgl-btn' for='cb2'></label>_x000D_
    <label class='tgl-btn' for='cb2'>_x000D_
      <h4>iOS 7</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb3'>_x000D_
      <h4>Skewed</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-skewed' id='cb3' type='checkbox'>_x000D_
    <label class='tgl-btn' data-tg-off='OFF' data-tg-on='ON' for='cb3'></label>_x000D_
    <label class='tgl-btn' for='cb3'>_x000D_
      <h4>Skewed</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb4'>_x000D_
      <h4>Flat</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-flat' id='cb4' type='checkbox'>_x000D_
    <label class='tgl-btn' for='cb4'></label>_x000D_
    <label class='tgl-btn' for='cb4'>_x000D_
      <h4>Flat</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
  <li class='tg-list-item'>_x000D_
    <label class='tgl-btn' for='cb5'>_x000D_
      <h4>Flip</h4>_x000D_
    </label>_x000D_
    <input class='tgl tgl-flip' id='cb5' type='checkbox'>_x000D_
    <label class='tgl-btn' data-tg-off='Nope' data-tg-on='Yeah!' for='cb5'></label>_x000D_
    <label class='tgl-btn' for='cb5'>_x000D_
      <h4>Flip</h4>_x000D_
    </label>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

If you run the snippet, you'll see I leave the iOS radio checked and disabled, so you can watch how it is also affected when activating another one. I also included 2 labels for each radio, one before and one after. The copy of the original code to show the working checkboxes in the same window is also included.

How to find row number of a value in R code

If you want to know the row and column of a value in a matrix or data.frame, consider using the arr.ind=TRUE argument to which:

> which(mydata_2 == 1578, arr.ind=TRUE)
  row col
7   7   3

So 1578 is in column 3 (which you already know) and row 7.

Python check if website exists

from urllib2 import Request, urlopen, HTTPError, URLError

user_agent = 'Mozilla/20.0.1 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent':user_agent }
link = "http://www.abc.com/"
req = Request(link, headers = headers)
try:
        page_open = urlopen(req)
except HTTPError, e:
        print e.code
except URLError, e:
        print e.reason
else:
        print 'ok'

To answer the comment of unutbu:

Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. Source

How do I add Git version control (Bitbucket) to an existing source code folder?

Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:

  1. Suppose you have your project folder on PC;
  2. Create a new repository on bitbucket: enter image description here

  3. Press on I have an existing project: enter image description here

  4. Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)

  5. Type command git init

  6. Type command git add --all

  7. Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO)

  8. Type command git commit -m "my first commit"

  9. Type command git push -u origin master

Note: if you get error unable to detect email or name, just type following commands after 5th step:

 git config --global user.email "yourEmail"  #your email at Bitbucket
 git config --global user.name "yourName"  #your name at Bitbucket

Arrays in type script

This is a very c# type of code:

var bks: Book[] = new Book[2];

In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:

var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;

Now to explain what new Book[2]; would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:

Book[2] = function (){alert("hey");}
var foo = new Book[2]

and you should see hey. Try it

Data at the root level is invalid

For the record:

"Data at the root level is invalid" means that you have attempted to parse something that is not an XML document. It doesn't even start to look like an XML document. It usually means just what you found: you're parsing something like the string "C:\inetpub\wwwroot\mysite\officelist.xml".

How to drop unique in MySQL?

Try it to remove uique of a column:

ALTER TABLE  `0_ms_labdip_details` DROP INDEX column_tcx

Run this code in phpmyadmin and remove unique of column

How do I make a composite key with SQL Server Management Studio?

enter image description here

  1. Open the design table tab
  2. Highlight your two INT fields (Ctrl/Shift+click on the grey blocks in the very first column)
  3. Right click -> Set primary key

What's the best way to limit text length of EditText in Android

Another way you can achieve this is by adding the following definition to the XML file:

<EditText
    android:id="@+id/input"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:maxLength="6"
    android:hint="@string/hint_gov"
    android:layout_weight="1"/>

This will limit the maximum length of the EditText widget to 6 characters.

How to get row index number in R?

See row in ?base::row. This gives the row indices for any matrix-like object.

How to set bot's status

Use this:

client.user.setActivity("with depression", {
  type: "STREAMING",
  url: "https://www.twitch.tv/monstercat"
});

How to enable php7 module in apache?

For Windows users looking for solution of same problem. I just repleced

LoadModule php7_module "C:/xampp/php/php7apache2_4.dll"

in my /conf/extra/http?-xampp.conf

Invalidating JSON Web Tokens

If you are using axios or a similar promise-based http request lib you can simply destroy token on the front-end inside the .then() part. It will be launched in the response .then() part after user executes this function (result code from the server endpoint must be ok, 200). After user clicks this route while searching for data, if database field user_enabled is false it will trigger destroying token and user will immediately be logged-off and stopped from accessing protected routes/pages. We don't have to await for token to expire while user is permanently logged on.

function searchForData() {   // front-end js function, user searches for the data
    // protected route, token that is sent along http request for verification
    var validToken = 'Bearer ' + whereYouStoredToken; // token stored in the browser 

    // route will trigger destroying token when user clicks and executes this func
    axios.post('/my-data', {headers: {'Authorization': validToken}})
     .then((response) => {
   // If Admin set user_enabled in the db as false, we destroy token in the browser localStorage
       if (response.data.user_enabled === false) {  // user_enabled is field in the db
           window.localStorage.clear();  // we destroy token and other credentials
       }  
    });
     .catch((e) => {
       console.log(e);
    });
}

NULL or BLANK fields (ORACLE)

SELECT COUNT (COL_NAME) 
FROM TABLE 
WHERE TRIM (COL_NAME) IS NULL 
or COL_NAME='NULL'

What are the differences between the BLOB and TEXT datatypes in MySQL?

TEXT and CHAR will convert to/from the character set they have associated with time. BLOB and BINARY simply store bytes.

BLOB is used for storing binary data while Text is used to store large string.

BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.

TEXT values are treated as nonbinary strings (character strings). They have a character set, and values are sorted and compared based on the collation of the character set.

http://dev.mysql.com/doc/refman/5.0/en/blob.html

Undefined symbols for architecture i386

Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project

QuartzCore.framework

For the bug

Undefined symbols for architecture i386:

"NoClassDefFoundError: Could not initialize class" error

I recently ran into this error on Windows 10. It turned out that windows was looking for .dll files necessary for my project and couldn't find them because it looks for them in the system path, PATH, rather than the CLASSPATH or -Djava.library.path

Brackets.io: Is there a way to auto indent / format <html>

Beautify does a good job. It provides a "Beautify on save" option, so that you may use ctrl+s to reformate html, less, css, etc

Can I dispatch an action in reducer?

Dispatching and action inside of reducer seems occurs bug.

I made a simple counter example using useReducer which "INCREASE" is dispatched then "SUB" also does.

In the example I expected "INCREASE" is dispatched then also "SUB" does and, set cnt to -1 and then continue "INCREASE" action to set cnt to 0, but it was -1 ("INCREASE" was ignored)

See this: https://codesandbox.io/s/simple-react-context-example-forked-p7po7?file=/src/index.js:144-154

let listener = () => {
  console.log("test");
};
const middleware = (action) => {
  console.log(action);
  if (action.type === "INCREASE") {
    listener();
  }
};

const counterReducer = (state, action) => {
  middleware(action);
  switch (action.type) {
    case "INCREASE":
      return {
        ...state,
        cnt: state.cnt + action.payload
      };
    case "SUB":
      return {
        ...state,
        cnt: state.cnt - action.payload
      };
    default:
      return state;
  }
};

const Test = () => {
  const { cnt, increase, substract } = useContext(CounterContext);

  useEffect(() => {
    listener = substract;
  });

  return (
    <button
      onClick={() => {
        increase();
      }}
    >
      {cnt}
    </button>
  );
};

{type: "INCREASE", payload: 1}
{type: "SUB", payload: 1}
// expected: cnt: 0
// cnt = -1

What is the difference between cache and persist?

The difference between cache and persist operations is purely syntactic. cache is a synonym of persist or persist(MEMORY_ONLY), i.e. cache is merely persist with the default storage level MEMORY_ONLY

But Persist() We can save the intermediate results in 5 storage levels.

  1. MEMORY_ONLY
  2. MEMORY_AND_DISK
  3. MEMORY_ONLY_SER
  4. MEMORY_AND_DISK_SER
  5. DISK_ONLY

/** * Persist this RDD with the default storage level (MEMORY_ONLY). */
def persist(): this.type = persist(StorageLevel.MEMORY_ONLY)

/** * Persist this RDD with the default storage level (MEMORY_ONLY). */
def cache(): this.type = persist()

see more details here...


Caching or persistence are optimization techniques for (iterative and interactive) Spark computations. They help saving interim partial results so they can be reused in subsequent stages. These interim results as RDDs are thus kept in memory (default) or more solid storage like disk and/or replicated. RDDs can be cached using cache operation. They can also be persisted using persist operation.

#persist, cache

These functions can be used to adjust the storage level of a RDD. When freeing up memory, Spark will use the storage level identifier to decide which partitions should be kept. The parameter less variants persist() and cache() are just abbreviations for persist(StorageLevel.MEMORY_ONLY).

Warning: Once the storage level has been changed, it cannot be changed again!


Warning -Cache judiciously... see ((Why) do we need to call cache or persist on a RDD)

Just because you can cache a RDD in memory doesn’t mean you should blindly do so. Depending on how many times the dataset is accessed and the amount of work involved in doing so, recomputation can be faster than the price paid by the increased memory pressure.

It should go without saying that if you only read a dataset once there is no point in caching it, it will actually make your job slower. The size of cached datasets can be seen from the Spark Shell..

Listing Variants...

def cache(): RDD[T]
 def persist(): RDD[T]
 def persist(newLevel: StorageLevel): RDD[T]

See below example :

val c = sc.parallelize(List("Gnu", "Cat", "Rat", "Dog", "Gnu", "Rat"), 2)
     c.getStorageLevel
     res0: org.apache.spark.storage.StorageLevel = StorageLevel(false, false, false, false, 1)
     c.cache
     c.getStorageLevel
     res2: org.apache.spark.storage.StorageLevel = StorageLevel(false, true, false, true, 1)

enter image here

Note : Due to the very small and purely syntactic difference between caching and persistence of RDDs the two terms are often used interchangeably.

See more visually here....

Persist in memory and disk:

enter image description here

Cache

Caching can improve the performance of your application to a great extent.

enter image description here

Copy multiple files from one directory to another from Linux shell

Use wildcards:

cp /home/ankur/folder/* /home/ankur/dest

If you don't want to copy all the files, you can use braces to select files:

cp /home/ankur/folder/{file{1,2},xyz,abc} /home/ankur/dest

This will copy file1, file2, xyz, and abc.

You should read the sections of the bash man page on Brace Expansion and Pathname Expansion for all the ways you can simplify this.

Another thing you can do is cd /home/ankur/folder. Then you can type just the filenames rather than the full pathnames, and you can use filename completion by typing Tab.

What is the volatile keyword useful for?

Yes, volatile must be used whenever you want a mutable variable to be accessed by multiple threads. It is not very common usecase because typically you need to perform more than a single atomic operation (e.g. check the variable state before modifying it), in which case you would use a synchronized block instead.

How do you set up use HttpOnly cookies in PHP

You can specify it in the set cookie function see the php manual

setcookie('Foo','Bar',0,'/', 'www.sample.com'  , FALSE, TRUE);

How can I get the current array index in a foreach loop?

well since this is the first google hit for this problem:

function mb_tell(&$msg) {
    if(count($msg) == 0) {
        return 0;
    }
    //prev($msg);
    $kv = each($msg);
    if(!prev($msg)) {
        end($msg);

        print_r($kv);
        return ($kv[0]+1);
    }
    print_r($kv);
    return ($kv[0]);
}

CSS animation delay in repeating

This is what you should do. It should work in that you have a 1 second animation, then a 4 second delay between iterations:

@keyframes barshine {
  0% {
  background-image:linear-gradient(120deg,rgba(255,255,255,0) 0%,rgba(255,255,255,0.25) -5%,rgba(255,255,255,0) 0%);
  }
  20% {
    background-image:linear-gradient(120deg,rgba(255,255,255,0) 10%,rgba(255,255,255,0.25) 105%,rgba(255,255,255,0) 110%);
  }
}
.progbar {
  animation: barshine 5s 0s linear infinite;
}

So I've been messing around with this a lot and you can do it without being very hacky. This is the simplest way to put in a delay between animation iterations that's 1. SUPER EASY and 2. just takes a little logic. Check out this dance animation I've made:

.dance{
  animation-name: dance;
  -webkit-animation-name: dance;

  animation-iteration-count: infinite;
  -webkit-animation-iteration-count: infinite;
  animation-duration: 2.5s;
  -webkit-animation-duration: 2.5s;

  -webkit-animation-delay: 2.5s;
  animation-delay: 2.5s;
  animation-timing-function: ease-in;
  -webkit-animation-timing-function: ease-in;

}
@keyframes dance {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  25% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  50% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
  100% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
}

@-webkit-keyframes dance {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  20% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
  40% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  60% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  80% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  95% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
}

I actually came here trying to figure out how to put a delay in the animation, when I realized that you just 1. extend the duration of the animation and shirt the proportion of time for each animation. Beore I had them each lasting .5 seconds for the total duration of 2.5 seconds. Now lets say i wanted to add a delay equal to the total duration, so a 2.5 second delay.

You animation time is 2.5 seconds and delay is 2.5, so you change duration to 5 seconds. However, because you doubled the total duration, you'll want to halve the animations proportion. Check the final below. This worked perfectly for me.

@-webkit-keyframes dance {
  0% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  10% {
    -webkit-transform: rotate(20deg);
    -moz-transform: rotate(20deg);
    -o-transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    transform: rotate(20deg);
  }
  20% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  30% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  40% {
    -webkit-transform: rotate(-120deg);
    -moz-transform: rotate(-120deg);
    -o-transform: rotate(-120deg);
    -ms-transform: rotate(-120deg);
    transform: rotate(-120deg);
  }
  50% {
    -webkit-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    -ms-transform: rotate(0deg);
    transform: rotate(0deg);
  }
}

In sum:

These are the calcultions you'd probably use to figure out how to change you animation's duration and the % of each part.

desired_duration = x

desired_duration = animation_part_duration1 + animation_part_duration2 + ... (and so on)

desired_delay = y

total duration = x + y

animation_part_duration1_actual = animation_part_duration1 * desired_duration / total_duration

DateTime.ToString("MM/dd/yyyy HH:mm:ss.fff") resulted in something like "09/14/2013 07.20.31.371"

You can use String.Format:

DateTime d = DateTime.Now;
string str = String.Format("{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}.{6:000}", d.Month, d.Day, d.Year, d.Hour, d.Minute, d.Second, d.Millisecond);
// I got this result: "02/23/2015 16:42:38.234"

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

Dynamically add data to a javascript map

Well any Javascript object functions sort-of like a "map"

randomObject['hello'] = 'world';

Typically people build simple objects for the purpose:

var myMap = {};

// ...

myMap[newKey] = newValue;

edit — well the problem with having an explicit "put" function is that you'd then have to go to pains to avoid having the function itself look like part of the map. It's not really a Javascripty thing to do.

13 Feb 2014 — modern JavaScript has facilities for creating object properties that aren't enumerable, and it's pretty easy to do. However, it's still the case that a "put" property, enumerable or not, would claim the property name "put" and make it unavailable. That is, there's still only one namespace per object.

Deleting multiple columns based on column names in Pandas

Simple and Easy. Remove all columns after the 22th.

df.drop(columns=df.columns[22:]) # love it

How to pass form input value to php function

Make your action empty. You don't need to set the onclick attribute, that's only javascript. When you click your submit button, it will reload your page with input from the form. So write your PHP code at the top of the form.

<?php
if( isset($_GET['submit']) )
{
    //be sure to validate and clean your variables
    $val1 = htmlentities($_GET['val1']);
    $val2 = htmlentities($_GET['val2']);

    //then you can use them in a PHP function. 
    $result = myFunction($val1, $val2);
}
?>

<?php if( isset($result) ) echo $result; //print the result above the form ?>

<form action="" method="get">
    Inserisci number1: 
    <input type="text" name="val1" id="val1"></input>

    <?php echo "ciaoooo"; ?>

    <br></br>
    Inserisci number2:
    <input type="text" name="val2" id="val2"></input>

    <br></br>

    <input type="submit" name="submit" value="send"></input>
</form>

Scheduling Python Script to run every hour accurately

the simplest option I can suggest is using the schedule library.

In your question, you said "I will need to run a function once every hour" the code to do this is very simple:

    import schedule

    def thing_you_wanna_do():
        ...
        ...
        return


    schedule.every().hour.do(thing_you_wanna_do)

    while True:
        schedule.run_pending()

you also asked how to do something at a certain time of the day some examples of how to do this are:

    import schedule


    def thing_you_wanna_do():
        ...
        ...
        return


    schedule.every().day.at("10:30").do(thing_you_wanna_do)
    schedule.every().monday.do(thing_you_wanna_do)
    schedule.every().wednesday.at("13:15").do(thing_you_wanna_do)
    # If you would like some randomness / variation you could also do something like this
    schedule.every(1).to(2).hours.do(thing_you_wanna_do)

    while True:
        schedule.run_pending()

90% of the code used is the example code of the schedule library. Happy scheduling!

Round up to Second Decimal Place in Python

The round funtion stated does not works for definate integers like :

a=8
round(a,3)
8.0
a=8.00
round(a,3)
8.0
a=8.000000000000000000000000
round(a,3)
8.0

but , works for :

r=400/3.0
r
133.33333333333334
round(r,3)
133.333

Morever the decimals like 2.675 are rounded as 2.67 not 2.68.
Better use the other method provided above.

What is a callback?

If you referring to ASP.Net callbacks:

In the default model for ASP.NET Web pages, the user interacts with a page and clicks a button or performs some other action that results in a postback. The page and its controls are re-created, the page code runs on the server, and a new version of the page is rendered to the browser. However, in some situations, it is useful to run server code from the client without performing a postback. If the client script in the page is maintaining some state information (for example, local variable values), posting the page and getting a new copy of it destroys that state. Additionally, page postbacks introduce processing overhead that can decrease performance and force the user to wait for the page to be processed and re-created.

To avoid losing client state and not incur the processing overhead of a server roundtrip, you can code an ASP.NET Web page so that it can perform client callbacks. In a client callback, a client-script function sends a request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle. The page is initiated and its controls and other members are created, and then a specially marked method is invoked. The method performs the processing that you have coded and then returns a value to the browser that can be read by another client script function. Throughout this process, the page is live in the browser.

Source: http://msdn.microsoft.com/en-us/library/ms178208.aspx

If you are referring to callbacks in code:

Callbacks are often delegates to methods that are called when the specific operation has completed or performs a sub-action. You'll often find them in asynchronous operations. It is a programming principle that you can find in almost every coding language.

More info here: http://msdn.microsoft.com/en-us/library/ms173172.aspx

Change color inside strings.xml

<string name="hello_world"><font fgcolor="red">Hello</font>
    </font fgcolor="blue">world!</font></string>

But note that this only works on a relatively short list of built-in colors: aqua, black, blue, fuchsia, green, grey, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. See https://stackoverflow.com/a/31655150/338479 for a way to do it with arbitrary colors.

How to check if running as root in a bash script

try the following code:

if [ "$(id -u)" != "0" ]; then
    echo "Sorry, you are not root."
    exit 1
fi

OR

if [ `id -u` != "0" ]; then
    echo "Sorry, you are not root."
    exit 1
fi

How do I make flex box work in safari?

Just try -webkit-flexbox. it's working for safari. webkit-flex safari will not taking.

What does the "@" symbol do in SQL?

What you are talking about is the way a parameterized query is written. '@' just signifies that it is a parameter. You can add the value for that parameter during execution process

eg:
sqlcommand cmd = new sqlcommand(query,connection);
cmd.parameters.add("@custid","1");
sqldatareader dr = cmd.executequery();

What is base 64 encoding used for?

Base-64 encoding is a way of taking binary data and turning it into text so that it's more easily transmitted in things like e-mail and HTML form data.

http://en.wikipedia.org/wiki/Base64

How do I get a human-readable file size in bytes abbreviation using .NET?

One more approach, for what it's worth. I liked @humbads optimized solution referenced above, so have copied the principle, but I've implemented it a little differently.

I suppose it's debatable as to whether it should be an extension method (since not all longs are necessarily byte sizes), but I like them, and it's somewhere I can find the method when I next need it!

Regarding the units, I don't think I've ever said 'Kibibyte' or 'Mebibyte' in my life, and while I'm skeptical of such enforced rather than evolved standards, I suppose it'll avoid confusion in the long term.

public static class LongExtensions
{
    private static readonly long[] numberOfBytesInUnit;
    private static readonly Func<long, string>[] bytesToUnitConverters;

    static LongExtensions()
    {
        numberOfBytesInUnit = new long[6]    
        {
            1L << 10,    // Bytes in a Kibibyte
            1L << 20,    // Bytes in a Mebibyte
            1L << 30,    // Bytes in a Gibibyte
            1L << 40,    // Bytes in a Tebibyte
            1L << 50,    // Bytes in a Pebibyte
            1L << 60     // Bytes in a Exbibyte
        };

        // Shift the long (integer) down to 1024 times its number of units, convert to a double (real number), 
        // then divide to get the final number of units (units will be in the range 1 to 1023.999)
        Func<long, int, string> FormatAsProportionOfUnit = (bytes, shift) => (((double)(bytes >> shift)) / 1024).ToString("0.###");

        bytesToUnitConverters = new Func<long,string>[7]
        {
            bytes => bytes.ToString() + " B",
            bytes => FormatAsProportionOfUnit(bytes, 0) + " KiB",
            bytes => FormatAsProportionOfUnit(bytes, 10) + " MiB",
            bytes => FormatAsProportionOfUnit(bytes, 20) + " GiB",
            bytes => FormatAsProportionOfUnit(bytes, 30) + " TiB",
            bytes => FormatAsProportionOfUnit(bytes, 40) + " PiB",
            bytes => FormatAsProportionOfUnit(bytes, 50) + " EiB",
        };
    }

    public static string ToReadableByteSizeString(this long bytes)
    {
        if (bytes < 0)
            return "-" + Math.Abs(bytes).ToReadableByteSizeString();

        int counter = 0;
        while (counter < numberOfBytesInUnit.Length)
        {
            if (bytes < numberOfBytesInUnit[counter])
                return bytesToUnitConverters[counter](bytes);
            counter++;
        }
        return bytesToUnitConverters[counter](bytes);
    }
}

Select multiple columns in data.table by their numeric indices

@Tom, thank you very much for pointing out this solution. It works great for me.

I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this

library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]

Missing visible-** and hidden-** in Bootstrap v4

I do no expect that multiple div's is a good solution.

I also think you can replace .visible-sm-block with .hidden-xs-down and .hidden-md-up (or .hidden-sm-down and .hidden-lg-up to act on the same media queries).

hidden-sm-up compiles into:

.visible-sm-block {
  display: none !important;
}
@media (min-width: 768px) and (max-width: 991px) {
  .visible-sm-block {
    display: block !important;
  }
}

.hidden-sm-down and .hidden-lg-up compiles into:

@media (max-width: 768px) {
  .hidden-xs-down {
    display: none !important;
  }
}
@media (min-width: 991px) {
  .hidden-lg-up {
    display: none !important;
  }
}

Both situation should act the same.

You situation become different when you try to replace .visible-sm-block and .visible-lg-block. Bootstrap v4 docs tell you:

These classes don’t attempt to accommodate less common cases where an element’s visibility can’t be expressed as a single contiguous range of viewport breakpoint sizes; you will instead need to use custom CSS in such cases.

.visible-sm-and-lg {
  display: none !important;
}
@media (min-width: 768px) and (max-width: 991px) {
  .visible-sm-and-lg {
    display: block !important;
  }
}
@media (min-width: 1200px) {
  .visible-sm-and-lg {
    display: block !important;
  }
}

How to keep :active css style after clicking an element

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

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

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

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can just call the Execute command.

EXEC spDoSomthing @myDate

Edit:

Since you want to return data..that's a little harder. You can use user defined functions instead that return data.

urlencode vs rawurlencode?

It will depend on your purpose. If interoperability with other systems is important then it seems rawurlencode is the way to go. The one exception is legacy systems which expect the query string to follow form-encoding style of spaces encoded as + instead of %20 (in which case you need urlencode).

rawurlencode follows RFC 1738 prior to PHP 5.3.0 and RFC 3986 afterwards (see http://us2.php.net/manual/en/function.rawurlencode.php)

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in » RFC 3986 for protecting literal characters from being interpreted as special URL delimiters, and for protecting URLs from being mangled by transmission media with character conversions (like some email systems).

Note on RFC 3986 vs 1738. rawurlencode prior to php 5.3 encoded the tilde character (~) according to RFC 1738. As of PHP 5.3, however, rawurlencode follows RFC 3986 which does not require encoding tilde characters.

urlencode encodes spaces as plus signs (not as %20 as done in rawurlencode)(see http://us2.php.net/manual/en/function.urlencode.php)

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

This corresponds to the definition for application/x-www-form-urlencoded in RFC 1866.

Additional Reading:

You may also want to see the discussion at http://bytes.com/groups/php/5624-urlencode-vs-rawurlencode.

Also, RFC 2396 is worth a look. RFC 2396 defines valid URI syntax. The main part we're interested in is from 3.4 Query Component:

Within a query component, the characters ";", "/", "?", ":", "@",
"&", "=", "+", ",", and "$"
are reserved.

As you can see, the + is a reserved character in the query string and thus would need to be encoded as per RFC 3986 (as in rawurlencode).

Non-invocable member cannot be used like a method?

As the error clearly states, OffenceBox.Text() is not a function and therefore doesn't make sense.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

I've just checked-in a test for my library dollar:

@Test
public void join() {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    String string = $(list).join(",");
}

it create a fluent wrapper around lists/arrays/strings/etc using only one static import: $.

NB:

using ranges the previous list can be re-writed as $(1, 5).join(",")

How to capture a list of specific type with mockito

List<String> mockedList = mock(List.class);

List<String> l = new ArrayList();
l.add("someElement");

mockedList.addAll(l);

ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);

verify(mockedList).addAll(argumentCaptor.capture());

List<String> capturedArgument = argumentCaptor.<List<String>>getValue();

assertThat(capturedArgument, hasItem("someElement"));

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

how to use LIKE with column name

...
WHERE table1.x LIKE table2.y + '%'

How to edit/save a file through Ubuntu Terminal

Normal text editors are nano, or vi.

For example:

root@user:# nano galfit.feedme

or

root@user:# vi galfit.feedme

Jquery .on('scroll') not firing the event while scrolling

I know that this is quite old thing, but I solved issue like that: I had parent and child element was scrollable.

   if ($('#parent > *').length == 0 ){
        var wait = setInterval(function() {
            if($('#parent > *').length != 0 ) {
                $('#parent .child').bind('scroll',function() {
                  //do staff
                });
                clearInterval(wait);
            },1000);
        }

The issue I had is that I didn't know when the child is loaded to DOM, but I kept checking for it every second.

NOTE:this is useful if it happens soon but not right after document load, otherwise it will use clients computing power for no reason.

How to solve time out in phpmyadmin?

But if you are using Plesk, change your settings in :

/usr/local/psa/admin/htdocs/domains/databases/phpMyAdmin/libraries/config.default.php

Change $cfg['ExecTimeLimit'] = 300; to $cfg['ExecTimeLimit'] = 0;

And restart with Plesk UI or use:

/etc/init.d/psa restart and /etc/init.d/httpd restart

Global variables in AngularJS

I just found another method by mistake :

What I did was to declare a var db = null above app declaration and then modified it in the app.js then when I accessed it in the controller.js I was able to access it without any problem.There might be some issues with this method which I'm not aware of but It's a good solution I guess.

javax.websocket client simple example

Use this library org.java_websocket

First thing you should import that library in build.gradle

repositories {
 mavenCentral()
 }

then add the implementation in dependency{}

implementation "org.java-websocket:Java-WebSocket:1.3.0"

Then you can use this code

In your activity declare object for Websocketclient like

private WebSocketClient mWebSocketClient;

then add this method for callback

 private void ConnectToWebSocket() {
URI uri;
try {
    uri = new URI("ws://your web socket url");
} catch (URISyntaxException e) {
    e.printStackTrace();
    return;
}

mWebSocketClient = new WebSocketClient(uri) {
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        Log.i("Websocket", "Opened");
        mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
    }

    @Override
    public void onMessage(String s) {
        final String message = s;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TextView textView = (TextView)findViewById(R.id.edittext_chatbox);
                textView.setText(textView.getText() + "\n" + message);
            }
        });
    }

    @Override
    public void onClose(int i, String s, boolean b) {
        Log.i("Websocket", "Closed " + s);
    }

    @Override
    public void onError(Exception e) {
        Log.i("Websocket", "Error " + e.getMessage());
    }
};
mWebSocketClient.connect();

}

SQL Server SELECT INTO @variable?

"SELECT *
  INTO 
    @TempCustomer 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId"

Which means creating a new @tempCustomer tablevariable and inserting data FROM Customer. You had already declared it above so no need of again declaring. Better to go with

INSERT INTO @tempCustomer SELECT * FROM Customer

Delete all rows in table

Truncate table is faster than delete * from XXX. Delete is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.

How do I update pip itself from inside my virtual environment?

I was in a similar situation and wanted to update urllib3 package. What worked for me was:

pip3 install --upgrade --force-reinstall --ignore-installed urllib3==1.25.3

How to copy from CSV file to PostgreSQL table with headers in CSV file?

This worked. The first row had column names in it.

COPY wheat FROM 'wheat_crop_data.csv' DELIMITER ';' CSV HEADER

Static link of shared library function in gcc

Yeah, I know this is an 8 year-old question, but I was told that it was possible to statically link against a shared-object library and this was literally the top hit when I searched for more information about it.

To actually demonstrate that statically linking a shared-object library is not possible with ld (gcc's linker) -- as opposed to just a bunch of people insisting that it's not possible -- use the following gcc command:

gcc -o executablename objectname.o -Wl,-Bstatic -l:libnamespec.so

(Of course you'll have to compile objectname.o from sourcename.c, and you should probably make up your own shared-object library as well. If you do, use -Wl,--library-path,. so that ld can find your library in the local directory.)

The actual error you receive is:

/usr/bin/ld: attempted static link of dynamic object `libnamespec.so'
collect2: error: ld returned 1 exit status

Hope that helps.

How do I read / convert an InputStream into a String in Java?

Taking into account file one should first get a java.io.Reader instance. This can then be read and added to a StringBuilder (we don't need StringBuffer if we are not accessing it in multiple threads, and StringBuilder is faster). The trick here is that we work in blocks, and as such don't need other buffering streams. The block size is parameterized for run-time performance optimization.

public static String slurp(final InputStream is, final int bufferSize) {
    final char[] buffer = new char[bufferSize];
    final StringBuilder out = new StringBuilder();
    try (Reader in = new InputStreamReader(is, "UTF-8")) {
        for (;;) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer, 0, rsz);
        }
    }
    catch (UnsupportedEncodingException ex) {
        /* ... */
    }
    catch (IOException ex) {
        /* ... */
    }
    return out.toString();
}

sqlite database default time value 'now'

It may be better to use REAL type, to save storage space.

Quote from 1.2 section of Datatypes In SQLite Version 3

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT, 
    t REAL DEFAULT (datetime('now', 'localtime'))
);

see column-constraint .

And insert a row without providing any value.

INSERT INTO "test" DEFAULT VALUES;

TypeError: $ is not a function WordPress

Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.

  1. Wrap your code using:

    <script> 
    jQuery(function($) {
    
    YOUR CODE GOES HERE
    
    });
    </script>
    
  2. You can also use jQuery's API using noConflict();

    <script>
    $.noConflict();
    jQuery( document ).ready(function( $ ) {
    // Code that uses jQuery's $ can follow here.
    });
    // Code that uses other library's $ can follow here.
    </script>
    
  3. Another example of using noConflict without using document ready:

    <script>
    jQuery.noConflict();
        (function( $ ) {
            $(function() { 
                // YOUR CODE HERE
            });
         });
    </script>
    
  4. You could even choose to create your very alias to avoid conflicts like so:

    var jExample = jQuery.noConflict();
    // Do something with jQuery
    jExample( "div p" ).hide();
    
  5. Yet another longer solution is to rename all referances of $ to jQuery:

    $( "div p" ).hide(); to jQuery( "div p" ).hide();

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

How to make a new line or tab in <string> XML (eclipse/android)?

  • Include this line in your layout xmlns:tools="http://schemas.android.com/tools"
  • Now , use \n for new line and \t for space like tab.
  • Example :

    for \n : android:text="Welcome back ! \nPlease login to your account agilanbu"

    for \t : android:text="Welcome back ! \tPlease login to your account agilanbu"

How to center a subview of UIView

Objective-C

yourSubView.center = CGPointMake(yourView.frame.size.width  / 2, 
                                 yourView.frame.size.height / 2);

Swift

yourSubView.center = CGPoint(x: yourView.frame.size.width  / 2,
                             y: yourView.frame.size.height / 2)

Why std::cout instead of simply cout?

It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:

#include <iostream.h>

or

#include <iostream>

The former is pre-standard, and you'll be able to just say cout as opposed to std::cout without anything additional. You can get the same behavior in standard C++ by adding

using std::cout;

or

using namespace std;

Just one idea, anyway.

What is the meaning of "operator bool() const"

I'd like to give more codes to make it clear.

struct A
{
    operator bool() const { return true; }
};

struct B
{
    explicit operator bool() const { return true; }
};

int main()
{
    A a1;
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

    B b1;     
    if (b1) cout << "true" << endl; // OK: B::operator bool()
    // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}

How to select the last record of a table in SQL?

Assuming you have an Id column:

SELECT TOP 1 *
  FROM table
 ORDER
    BY Id DESC;

Also, this will work on SQL Server. I think that MySQL you might need to use:

SELECT *
  FROM table
 ORDER
    BY Id DESC
 LIMIT 1

But, I'm not 100% sure about this.

EDIT

Looking at the other answers, I'm now 100% confident that I'm correct with the MySQL statement :o)

EDIT

Just seen your latest comment. You could do:

SELECT MAX(Id)
  FROM table

This will get you the highest Id number.

Adding days to a date in Python

Here is another method to add days on date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(days=5)
print 'After 5 Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

Output:

Today: 25/06/2015 15:56:09

After 5 Days: 30/06/2015 15:56:09

Handling InterruptedException in Java

The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.

Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.

So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.

There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.

If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.

So in summary your choices for handling should follow this list:

  1. By default, add to throws.
  2. If not allowed to add to throws, throw RuntimeException(e). (Best choice of multiple bad options)
  3. Only when you know an explicit cause of the Interrupt, handle as desired. If your handling is local to your method, then reset interrupted by a call to Thread.currentThread().interrupt().

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

javax vs java package

Javax used to be only for extensions. Yet later sun added it to the java libary forgetting to remove the x. Developers started making code with javax. Yet later on in time suns decided to change it to java. Developers didn't like the idea because they're code would be ruined... so javax was kept.

Confirm postback OnClientClick button ASP.NET

I know this is old and there are so many answers, some are really convoluted, can be quick and inline:

<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" OnClick="BtnUserDelete_Click" OnClientClick="return confirm('Are you sure you want to delete this user?');" meta:resourcekey="BtnUserDeleteResource1" />
                       

What does it mean if a Python object is "subscriptable" or not?

A scriptable object is an object that records the operations done to it and it can store them as a "script" which can be replayed.

For example, see: Application Scripting Framework

Now, if Alistair didn't know what he asked and really meant "subscriptable" objects (as edited by others), then (as mipadi also answered) this is the correct one:

A subscriptable object is any object that implements the __getitem__ special method (think lists, dictionaries).

SQL Format as of Round off removing decimals

SELECT CONVERT(INT, 11.4)

RESULT: 11

SELECT CONVERT(INT, 11.6)

RESULT: 11

Regex for allowing alphanumeric,-,_ and space

Character sets will help out a ton here. You want to create a matching set for the characters that you want to validate:

  • You can match alphanumeric with a \w, which is the same as [A-Za-z0-9_] in JavaScript (other languages can differ).
  • That leaves - and spaces, which can be combined into a matching set such as [\w\- ]. However, you may want to consider using \s instead of just the space character (\s also matches tabs, and other forms of whitespace)
    • Note that I'm escaping - as \- so that the regex engine doesn't confuse it with a character range like A-Z
  • Last up, you probably want to ensure that the entire string matches by anchoring the start and end via ^ and $

The full regex you're probably looking for is:

/^[\w\-\s]+$/

(Note that the + indicates that there must be at least one character for it to match; use a * instead, if a zero-length string is also ok)

Finally, http://www.regular-expressions.info/ is an awesome reference


Bonus Points: This regex does not match non-ASCII alphas. Unfortunately, the regex engine in most browsers does not support named character sets, but there are some libraries to help with that.

For languages/platforms that do support named character sets, you can use /^[\p{Letter}\d\_\-\s]+$/

How to take the first N items from a generator or list?

Do you mean the first N items, or the N largest items?

If you want the first:

top5 = sequence[:5]

This also works for the largest N items, assuming that your sequence is sorted in descending order. (Your LINQ example seems to assume this as well.)

If you want the largest, and it isn't sorted, the most obvious solution is to sort it first:

l = list(sequence)
l.sort(reverse=True)
top5 = l[:5]

For a more performant solution, use a min-heap (thanks Thijs):

import heapq
top5 = heapq.nlargest(5, sequence)

how to create a list of lists

First of all do not use list as a variable name- that is a builtin function.

I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-

my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))

That will create a list (a type of mutable array in python) called my_list with the output of the np.getfromtext() method in the first 2 indexes.

The first can be referenced with my_list[0] and the second with my_list[1]

Check if a string contains a number

I'm surprised that no-one mentionned this combination of any and map:

def contains_digit(s):
    isdigit = str.isdigit
    return any(map(isdigit,s))

in python 3 it's probably the fastest there (except maybe for regexes) is because it doesn't contain any loop (and aliasing the function avoids looking it up in str).

Don't use that in python 2 as map returns a list, which breaks any short-circuiting

PHP: how can I get file creation date?

Use filectime. For Windows it will return the creation time, and for Unix the change time which is the best you can get because on Unix there is no creation time (in most filesystems).

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

T-SQL XOR Operator

The xor operator is ^

For example: SELECT A ^ B where A and B are integer category data types.

Checking for empty or null List<string>

We can validate like below with Extension methods. I use them for all of my projects.

  var myList = new List<string>();
  if(!myList.HasValue())
  {
     Console.WriteLine("List has value(s)");              
  }

  if(!myList.HasValue())
  {
     Console.WriteLine("List is either null or empty");           
  }

  if(myList.HasValue())
  {
      if (!myList[0].HasValue()) 
      {
          myList.Add("new item"); 
      }
  }




/// <summary>
/// This Method will return True if List is Not Null and it's items count>0       
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns>Bool</returns>
public static bool HasValue<T>(this IEnumerable<T> items)
{
    if (items != null)
    {
        if (items.Count() > 0)
        {
            return true;
        }
    }
    return false;
}


/// <summary>
/// This Method will return True if List is Not Null and it's items count>0       
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <returns></returns>
public static bool HasValue<T>(this List<T> items)
{
    if (items != null)
    {
        if (items.Count() > 0)
        {
            return true;
        }
    }
    return false;
}


/// <summary>
///  This method returns true if string not null and not empty  
/// </summary>
/// <param name="ObjectValue"></param>
/// <returns>bool</returns>
public static bool HasValue(this string ObjectValue)
{
    if (ObjectValue != null)
    {
        if ((!string.IsNullOrEmpty(ObjectValue)) && (!string.IsNullOrWhiteSpace(ObjectValue)))
        {
            return true;
        }
    }
    return false;
}

How do I write a bash script to restart a process if it dies?

Have a look at monit (http://mmonit.com/monit/). It handles start, stop and restart of your script and can do health checks plus restarts if necessary.

Or do a simple script:

while true
do
/your/script
sleep 1
done

Add a summary row with totals

If you want to display more column values without an aggregation function use GROUPING SETS instead of ROLLUP:

SELECT
  Type = ISNULL(Type, 'Total'),
  SomeIntColumn = ISNULL(SomeIntColumn, 0),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY GROUPING SETS ((Type, SomeIntColumn ), ())
ORDER BY SomeIntColumn --Displays summary row as the first row in query result

Global variables in c#.net

Just declare the variable at the starting of a class.

e.g. for string variable:

public partial class Login : System.Web.UI.Page
{
    public string sError;

    protected void Page_Load(object sender, EventArgs e)
    {
         //Page Load Code
    }

How to set a dropdownlist item as selected in ASP.NET?

dropdownlist.ClearSelection(); //making sure the previous selection has been cleared
dropdownlist.Items.FindByValue(value).Selected = true;

Regex select all text between tags

<pre>([\r\n\s]*(?!<\w+.*[\/]*>).*[\r\n\s]*|\s*[\r\n\s]*)<code\s+(?:class="(\w+|\w+\s*.+)")>(((?!<\/code>)[\s\S])*)<\/code>[\r\n\s]*((?!<\w+.*[\/]*>).*|\s*)[\r\n\s]*<\/pre>

Decode HTML entities in Python string?

Python 3.4+

Use html.unescape():

import html
print(html.unescape('&pound;682m'))

FYI html.parser.HTMLParser.unescape is deprecated, and was supposed to be removed in 3.5, although it was left in by mistake. It will be removed from the language soon.


Python 2.6-3.3

You can use HTMLParser.unescape() from the standard library:

>>> try:
...     # Python 2.6-2.7 
...     from HTMLParser import HTMLParser
... except ImportError:
...     # Python 3
...     from html.parser import HTMLParser
... 
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

You can also use the six compatibility library to simplify the import:

>>> from six.moves.html_parser import HTMLParser
>>> h = HTMLParser()
>>> print(h.unescape('&pound;682m'))
£682m

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

How to clear gradle cache?

The gradle daemon also creates a many large text files of every single build log. They are stored here:

~/.gradle/daemon/X.X/daemon-XXXX.out.log

"X.X" is the gradle version in use, like "4.4", and "XXXX" are just random numbers, like "1234".

The total size can grow to several hundred MB in just a few months. There is no way to disable the logging, and the files are not automatically deleted and they do not really need to be retained.

But you can create a small gradle task to automatically delete them, and free up lots of disk space:

Add this to your app/build.gradle:

android {

    buildTypes {
        ...
    }

    // Delete large build log files from ~/.gradle/daemon/X.X/daemon-XXX.out.log
    // Source: https://discuss.gradle.org/t/gradle-daemon-produces-a-lot-of-logs/9905
    def gradle = project.getGradle()
    new File("${gradle.getGradleUserHomeDir().getAbsolutePath()}/daemon/${gradle.getGradleVersion()}").listFiles().each {
        if (it.getName().endsWith('.out.log')) {
            // println("Deleting gradle log file: $it") // Optional debug output
            it.delete()
        }
    }
}

To see which files are being deleted, you can see the debug output in Android Studio -> View -> Tool Windows -> Build. Then press "Toggle View" button on that window to show the text output.

Note that a Gradle Sync or any Gradle Build will trigger the file deletions.

A better way would be to automatically move the files to the Trash/Recycle Bin, or at least copy them to a Trash folder first. But I don't know how to do that.

What is <scope> under <dependency> in pom.xml for?

Scope tag is always use to limit the transitive dependencies and availability of the jar at class path level.If we don't provide any scope then the default scope will work i.e. Compile .

How to set Java classpath in Linux?

export CLASSPATH=/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar

or, if you already have some classpath set

export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar

and, if also you want to include current directory

export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar:.

Run javascript script (.js file) in mongodb including another file inside js

To call external file you can use :

load ("path\file")

Exemple: if your file.js file is on your "Documents" file (on windows OS), you can type:

load ("C:\users\user_name\Documents\file.js")

should use size_t or ssize_t

ssize_t is used for functions whose return value could either be a valid size, or a negative value to indicate an error. It is guaranteed to be able to store values at least in the range [-1, SSIZE_MAX] (SSIZE_MAX is system-dependent).

So you should use size_t whenever you mean to return a size in bytes, and ssize_t whenever you would return either a size in bytes or a (negative) error value.

See: http://pubs.opengroup.org/onlinepubs/007908775/xsh/systypes.h.html

setTimeout in React Native

Classic javascript mistake.

setTimeout(function(){this.setState({timePassed: true})}, 1000)

When setTimeout runs this.setState, this is no longer CowtanApp, but window. If you define the function with the => notation, es6 will auto-bind this.

setTimeout(() => {this.setState({timePassed: true})}, 1000)

Alternatively, you could use a let that = this; at the top of your render, then switch your references to use the local variable.

render() {
  let that = this;
  setTimeout(function(){that.setState({timePassed: true})}, 1000);

If not working, use bind.

setTimeout(
  function() {
      this.setState({timePassed: true});
  }
  .bind(this),
  1000
);

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

Jquery get form field value

You can try these lines:

$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value

C++ templates that accept only certain types

There is no keyword for such type checks, but you can put some code in that will at least fail in an orderly fashion:

(1) If you want a function template to only accept parameters of a certain base class X, assign it to a X reference in your function. (2) If you want to accept functions but not primitives or vice versa, or you want to filter classes in other ways, call a (empty) template helper function within your function that's only defined for the classes you want to accept.

You can use (1) and (2) also in member functions of a class to force these type checks on the entire class.

You can probably put it into some smart Macro to ease your pain. :)

How to use cURL to get jSON data and decode the data?

to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

then json_decode() parses JSON into a PHP object, or an array if you pass true to the second parameter. http://php.net/manual/en/function.json-decode.php

For example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

Run / Open VSCode from Mac Terminal

I moved VS Code from Downloads folder to Applications, and then i was able to run code in the terminal. I guess, it might help you too.

Create a batch file to run an .exe with an additional parameter

You can use

start "" "%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

start "" /D "%USERPROFILE%\Desktop\BGInfo" bginfo.exe dc_bginfo.bgi

or

"%USERPROFILE%\Desktop\BGInfo\bginfo.exe" "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi"

or

cd /D "%USERPROFILE%\Desktop\BGInfo"
bginfo.exe dc_bginfo.bgi

Help on commands start and cd is output by executing in a command prompt window help start or start /? and help cd or cd /?.

But I do not understand why you need a batch file at all for starting the application with the additional parameter. Create a shortcut (*.lnk) on your desktop for this application. Then right click on the shortcut, left click on Properties and append after a space character "%USERPROFILE%\Desktop\BGInfo\dc_bginfo.bgi" as parameter.

Keep only date part when using pandas.to_datetime

Just giving a more up to date answer in case someone sees this old post.

Adding "utc=False" when converting to datetime will remove the timezone component and keep only the date in a datetime64[ns] data type.

pd.to_datetime(df['Date'], utc=False)

You will be able to save it in excel without getting the error "ValueError: Excel does not support datetimes with timezones. Please ensure that datetimes are timezone unaware before writing to Excel."

enter image description here

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

There's no magical solution of displaying something outside an overflow hidden container.

A similar effect can be achieved by having an absolute positioned div that matches the size of its parent by positioning it inside your current relative container (the div you don't wish to clip should be outside this div):

#1 .mask {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 1;
  overflow: hidden;
}

Take in mind that if you only have to clip content on the x axis (which appears to be your case, as you only have set the div's width), you can use overflow-x: hidden.

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

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

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

Difference between Activity and FragmentActivity

FragmentActivity is part of the support library, while Activity is the framework's default class. They are functionally equivalent.

You should always use FragmentActivity and android.support.v4.app.Fragment instead of the platform default Activity and android.app.Fragment classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.

how to loop through rows columns in excel VBA Macro

This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.

Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.

Sub Loop3()

Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String

Application.ScreenUpdating = False

'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row              'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column         'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead))  'assigns range for automation

ReDim frmlas(1)      'array assigned to formula strings
    'VOL column formula
frmlas(0) = "VOL FORMULA"
    'CAPACITY column formula
frmlas(1) = "CAP FORMULA"

For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then         'checks for volume formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula= frmlas(0)    'inserts volume formula
    Next j
ElseIf rng(0, i).Value = "Cap" Then     'checks for capacity formula column
    For j = 1 To rng.Rows.count
        rng(j, i).Formula = frmlas(1)   'inserts capacity formula
    Next j
End If
Next i

Application.ScreenUpdating = True

End Sub

Python: json.loads returns items prefixing with 'u'

The u prefix means that those strings are unicode rather than 8-bit strings. The best way to not show the u prefix is to switch to Python 3, where strings are unicode by default. If that's not an option, the str constructor will convert from unicode to 8-bit, so simply loop recursively over the result and convert unicode to str. However, it is probably best just to leave the strings as unicode.

How do I resize a Google Map with JavaScript after it has loaded?

This is best it will do the Job done. It will re-size your Map. No need to inspect element anymore to re-size your Map. What it does it will automatically trigger re-size event .

    google.maps.event.addListener(map, "idle", function()
        {
            google.maps.event.trigger(map, 'resize');
        });

        map_array[Next].setZoom( map.getZoom() - 1 );
    map_array[Next].setZoom( map.getZoom() + 1 );

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here

Unable to open debugger port in IntelliJ

Answer is pretty simple, I also faced the problem finally I got perfect solution. Create Debug Create Remote debug with following configuration Firstly run by debug. It gives you waitng for socket 5005 then run with remote debug

Is it safe to store a JWT in localStorage with ReactJS?

A way to look at this is to consider the level of risk or harm.

Are you building an app with no users, POC/MVP? Are you a startup who needs to get to market and test your app quickly? If yes, I would probably just implement the simplest solution and maintain focus on finding product-market-fit. Use localStorage as its often easier to implement.

Are you building a v2 of an app with many daily active users or an app that people/businesses are heavily dependent on. Would getting hacked mean little or no room for recovery? If so, I would take a long hard look at your dependencies and consider storing token information in an http-only cookie.

Using both localStorage and cookie/session storage have their own pros and cons.

As stated by first answer: If your application has an XSS vulnerability, neither will protect your user. Since most modern applications have a dozen or more different dependencies, it becomes increasingly difficult to guarantee that one of your application's dependencies is not XSS vulnerable.

If your application does have an XSS vulnerability and a hacker has been able to exploit it, the hacker will be able to perform actions on behalf of your user. The hacker can perform GET/POST requests by retrieving token from localStorage or can perform POST requests if token is stored in a http-only cookie.

The only down-side of the storing your token in local storage is the hacker will be able to read your token.

Combining CSS Pseudo-elements, ":after" the ":last-child"

This works :) (I hope multi-browser, Firefox likes it)

_x000D_
_x000D_
li { display: inline; list-style-type: none; }_x000D_
li:after { content: ", "; }_x000D_
li:last-child:before { content: "and "; }_x000D_
li:last-child:after { content: "."; }
_x000D_
<html>_x000D_
  <body>_x000D_
    <ul>_x000D_
      <li>One</li>_x000D_
      <li>Two</li>_x000D_
      <li>Three</li>_x000D_
    </ul>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

Inserting string at position x of another string

Maybe it's even better if you determine position using indexOf() like this:

function insertString(a, b, at)
{
    var position = a.indexOf(at); 

    if (position !== -1)
    {
        return a.substr(0, position) + b + a.substr(position);    
    }  

    return "substring not found";
}

then call the function like this:

insertString("I want apple", "an ", "apple");

Note, that I put a space after the "an " in the function call, rather than in the return statement.

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

How do I parse command line arguments in Java?

I want to show you my implementation: ReadyCLI

Advantages:

  • for lazy programmers: a very small number of classes to learn, just see the two small examples on the README in the repository and you are already at 90% of learning; just start coding your CLI/Parser without any other knowledge; ReadyCLI allows coding CLIs in the most natural way;
  • it is designed with Developer Experience in mind; it largely uses the Builder design pattern and functional interfaces for Lambda Expressions, to allow a very quick coding;
  • it supports Options, Flags and Sub-Commands;
  • it allows to parse arguments from command-line and to build more complex and interactive CLIs;
  • a CLI can be started on Standard I/O just as easily as on any other I/O interface, such as sockets;
  • it gives great support for documentation of commands.

I developed this project as I needed new features (options, flag, sub-commands) and that could be used in the simplest possible way in my projects.

How would you do a "not in" query with LINQ?

Couldn't you do an outer join, only selecting the items from the first list if the group is empty? Something like:

Dim result = (From a In list1
              Group Join b In list2 
                  On a.Value Equals b.Value 
                  Into grp = Group
              Where Not grp.Any
              Select a)

I'm unsure whether this would work in any sort of efficient way with the Entity framework.

Getting HTTP headers with Node.js

Here is my contribution, that deals with any URL using http or https, and use Promises.

const http = require('http')
const https = require('https')
const url = require('url')

function getHeaders(myURL) {
  const parsedURL = url.parse(myURL)
  const options = {
    protocol: parsedURL.protocol,
    hostname: parsedURL.hostname,
    method: 'HEAD',
    path: parsedURL.path
  }
  let protocolHandler = (parsedURL.protocol === 'https:' ? https : http)

  return new Promise((resolve, reject) => {
    let req = protocolHandler.request(options, (res) => {
      resolve(res.headers)
    })
    req.on('error', (e) => {
      reject(e)
    })
    req.end()
  })
}

getHeaders(myURL).then((headers) => {
  console.log(headers)
})

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.

How to check for an undefined or null variable in JavaScript?

In newer JavaScript standards like ES5 and ES6 you can just say

> Boolean(0) //false
> Boolean(null)  //false
> Boolean(undefined) //false

all return false, which is similar to Python's check of empty variables. So if you want to write conditional logic around a variable, just say

if (Boolean(myvar)){
   // Do something
}

here "null" or "empty string" or "undefined" will be handled efficiently.

Substitute a comma with a line break in a cell

To replace commas with newline characters use this formula (assuming that the text to be altered is in cell A1):

=SUBSTITUTE(A1,",",CHAR(10))

You may have to then alter the row height to see all of the values in the cell

I've left a comment about the other part of your question


Edit: here's a screenshot of this working - I had to turn on "Wrap Text" in the "Format Cells" dialog.

enter image description here

PostgreSQL wildcard LIKE for any of a list of words

All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE.

Reference: https://www.postgresql.org/docs/current/functions-matching.html

Looking for a 'cmake clean' command to clear up CMake output

try to use: cmake --clean-first path-of-CMakeLists.txt-file -B output-dir

--clean-first: Build target clean first, then build.
(To clean only, use --target clean.)

How to export all data from table to an insertable sql format?

I know this is an old question, but victorio also asked if there are any other options to copy data from one table to another. There is a very short and fast way to insert all the records from one table to another (which might or might not have similar design).

If you dont have identity column in table B_table:

INSERT INTO A_db.dbo.A_table
SELECT * FROM B_db.dbo.B_table

If you have identity column in table B_table, you have to specify columns to insert. Basically you select all except identity column, which will be auto incremented by default.

In case if you dont have existing B_table in B_db

SELECT *
INTO B_db.dbo.B_table
FROM A_db.dbo.A_table

will create table B_table in database B_db with all existing values