Programs & Examples On #Brk

brk() and sbrk() change the location of the program break, which defines the end of the process's data segment (i.e., the program break is the first location after the end of the uninitialized data segment).

Visual Studio 2017 errors on standard headers

If the problem is not solved by above answer, check whether the Windows SDK version is 10.0.15063.0.

Project -> Properties -> General -> Windows SDK Version -> select 10.0.15063.0

After this rebuild the solution.  

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For more performance: A simple change is observing that after n = 3n+1, n will be even, so you can divide by 2 immediately. And n won't be 1, so you don't need to test for it. So you could save a few if statements and write:

while (n % 2 == 0) n /= 2;
if (n > 1) for (;;) {
    n = (3*n + 1) / 2;
    if (n % 2 == 0) {
        do n /= 2; while (n % 2 == 0);
        if (n == 1) break;
    }
}

Here's a big win: If you look at the lowest 8 bits of n, all the steps until you divided by 2 eight times are completely determined by those eight bits. For example, if the last eight bits are 0x01, that is in binary your number is ???? 0000 0001 then the next steps are:

3n+1 -> ???? 0000 0100
/ 2  -> ???? ?000 0010
/ 2  -> ???? ??00 0001
3n+1 -> ???? ??00 0100
/ 2  -> ???? ???0 0010
/ 2  -> ???? ???? 0001
3n+1 -> ???? ???? 0100
/ 2  -> ???? ???? ?010
/ 2  -> ???? ???? ??01
3n+1 -> ???? ???? ??00
/ 2  -> ???? ???? ???0
/ 2  -> ???? ???? ????

So all these steps can be predicted, and 256k + 1 is replaced with 81k + 1. Something similar will happen for all combinations. So you can make a loop with a big switch statement:

k = n / 256;
m = n % 256;

switch (m) {
    case 0: n = 1 * k + 0; break;
    case 1: n = 81 * k + 1; break; 
    case 2: n = 81 * k + 1; break; 
    ...
    case 155: n = 729 * k + 425; break;
    ...
}

Run the loop until n = 128, because at that point n could become 1 with fewer than eight divisions by 2, and doing eight or more steps at a time would make you miss the point where you reach 1 for the first time. Then continue the "normal" loop - or have a table prepared that tells you how many more steps are need to reach 1.

PS. I strongly suspect Peter Cordes' suggestion would make it even faster. There will be no conditional branches at all except one, and that one will be predicted correctly except when the loop actually ends. So the code would be something like

static const unsigned int multipliers [256] = { ... }
static const unsigned int adders [256] = { ... }

while (n > 128) {
    size_t lastBits = n % 256;
    n = (n >> 8) * multipliers [lastBits] + adders [lastBits];
}

In practice, you would measure whether processing the last 9, 10, 11, 12 bits of n at a time would be faster. For each bit, the number of entries in the table would double, and I excect a slowdown when the tables don't fit into L1 cache anymore.

PPS. If you need the number of operations: In each iteration we do exactly eight divisions by two, and a variable number of (3n + 1) operations, so an obvious method to count the operations would be another array. But we can actually calculate the number of steps (based on number of iterations of the loop).

We could redefine the problem slightly: Replace n with (3n + 1) / 2 if odd, and replace n with n / 2 if even. Then every iteration will do exactly 8 steps, but you could consider that cheating :-) So assume there were r operations n <- 3n+1 and s operations n <- n/2. The result will be quite exactly n' = n * 3^r / 2^s, because n <- 3n+1 means n <- 3n * (1 + 1/3n). Taking the logarithm we find r = (s + log2 (n' / n)) / log2 (3).

If we do the loop until n = 1,000,000 and have a precomputed table how many iterations are needed from any start point n = 1,000,000 then calculating r as above, rounded to the nearest integer, will give the right result unless s is truly large.

Docker - Container is not running

If it's not possible to start the main process again (for long enough), there is also the possibility to commit the container to a new image and run a new container from this image. While this is not the usual best practice workflow, I find it really useful to debug a failing script once in a while.

docker exec -it 6198ef53d943 bash
Error response from daemon: Container 6198ef53d9431a3f38e8b38d7869940f7fb803afac4a2d599812b8e42419c574 is not running

docker commit 6198ef53d943
sha256:ace7ca65e6e3fdb678d9cdfb33a7a165c510e65c3bc28fecb960ac993c37ef33

docker run -it ace7ca65e6e bash
root@72d38a8c787d:/#

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I found this MSDN forum post which suggests two solutions to your problem.

First solution (not recommended):

Find the .Net Framework 3.5 and 2.0 folder

Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder

Add the reference to these two assemblies

Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work

Second solution (Use a different class / library):

The user who had posted the question claimed that Uri.EscapeUriString and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer.

You could also try to use Json.Net. It's a third party library and pretty powerful.

How to convert image into byte array and byte array to base64 String in android?

Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

How is malloc() implemented internally?

The sbrksystem call moves the "border" of the data segment. This means it moves a border of an area in which a program may read/write data (letting it grow or shrink, although AFAIK no malloc really gives memory segments back to the kernel with that method). Aside from that, there's also mmap which is used to map files into memory but is also used to allocate memory (if you need to allocate shared memory, mmap is how you do it).

So you have two methods of getting more memory from the kernel: sbrk and mmap. There are various strategies on how to organize the memory that you've got from the kernel.

One naive way is to partition it into zones, often called "buckets", which are dedicated to certain structure sizes. For example, a malloc implementation could create buckets for 16, 64, 256 and 1024 byte structures. If you ask malloc to give you memory of a given size it rounds that number up to the next bucket size and then gives you an element from that bucket. If you need a bigger area malloc could use mmap to allocate directly with the kernel. If the bucket of a certain size is empty malloc could use sbrk to get more space for a new bucket.

There are various malloc designs and there is propably no one true way of implementing malloc as you need to make a compromise between speed, overhead and avoiding fragmentation/space effectiveness. For example, if a bucket runs out of elements an implementation might get an element from a bigger bucket, split it up and add it to the bucket that ran out of elements. This would be quite space efficient but would not be possible with every design. If you just get another bucket via sbrk/mmap that might be faster and even easier, but not as space efficient. Also, the design must of course take into account that "free" needs to make space available to malloc again somehow. You don't just hand out memory without reusing it.

If you're interested, the OpenSER/Kamailio SIP proxy has two malloc implementations (they need their own because they make heavy use of shared memory and the system malloc doesn't support shared memory). See: https://github.com/OpenSIPS/opensips/tree/master/mem

Then you could also have a look at the GNU libc malloc implementation, but that one is very complicated, IIRC.

Viewing full output of PS command

Using the auxww flags, you will see the full path to output in both your terminal window and from shell scripts.

darragh@darraghserver ~ $uname -a
SunOS darraghserver 5.10 Generic_142901-13 i86pc i386 i86pc

darragh@darraghserver ~ $which ps
/usr/bin/ps<br>

darragh@darraghserver ~ $/usr/ucb/ps auxww | grep ps
darragh 13680  0.0  0.0 3872 3152 pts/1    O 14:39:32  0:00 /usr/ucb/ps -auxww
darragh 13681  0.0  0.0 1420  852 pts/1    S 14:39:32  0:00 grep ps

ps aux lists all processes executed by all users. See man ps for details. The ww flag sets unlimited width.

-w         Wide output. Use this option twice for unlimited width.
w          Wide output. Use this option twice for unlimited width.

I found the answer on the following blog:
http://www.snowfrog.net/2010/06/10/solaris-ps-output-truncated-at-80-columns/

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

I continue to suspect that your customer/user has some kernel module or driver loaded which is interfering with the clone() system call (perhaps some obscure security enhancement, something like LIDS but more obscure?) or is somehow filling up some of the kernel data structures that are necessary for fork()/clone() to operate (process table, page tables, file descriptor tables, etc).

Here's the relevant portion of the fork(2) man page:

ERRORS
       EAGAIN fork() cannot allocate sufficient memory to copy the parent's page tables and allocate a task  structure  for  the
              child.

       EAGAIN It  was not possible to create a new process because the caller's RLIMIT_NPROC resource limit was encountered.  To
              exceed this limit, the process must have either the CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability.

       ENOMEM fork() failed to allocate the necessary kernel structures because memory is tight.

I suggest having the user try this after booting into a stock, generic kernel and with only a minimal set of modules and drivers loaded (minimum necessary to run your application/script). From there, assuming it works in that configuration, they can perform a binary search between that and the configuration which exhibits the issue. This is standard sysadmin troubleshooting 101.

The relevant line in your strace is:

clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0xb7f12708) = -1 ENOMEM (Cannot allocate memory)

... I know others have talked about swap and memory availability (and I would recommend that you set up at least a small swap partition, ironically even if it's on a RAM disk ... the code paths through the Linux kernel when it has even a tiny bit of swap available have been exercised far more extensively than those (exception handling paths) in which there is zero swap available.

However I suspect that this is still a red herring.

The fact that free is reporting 0 (ZERO) memory in use by the cache and buffers is very disturbing. I suspect that the free output ... and possibly your application issue here, are caused by some proprietary kernel module which is interfering with the memory allocation in some way.

According to the man pages for fork()/clone() the fork() system call should return EAGAIN if your call would cause a resource limit violation (RLIMIT_NPROC) ... however, it doesn't say if EAGAIN is to be returned by other RLIMIT* violations. In any event if your target/host has some sort of weird Vormetric or other security settings (or even if your process is running under some weird SELinux policy) then it might be causing this -ENOMEM failure.

It's pretty unlikely to be a normal run-of-the-mill Linux/UNIX issue. You've got something non-standard going on there.

How can I execute PHP code from the command line?

Using PHP from the command line

Use " instead of ' on Windows when using the CLI version with -r:

php -r "echo 1;"

-- correct

php -r 'echo 1;'

-- incorrect

  PHP Parse error:  syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1

Don't forget the semicolon to close the line.

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

ORA-12170: TNS:Connect timeout occurred

I was getting the same error while connecting my "hr" user of ORCLPDB which is a pluggable database.

First, get hostname and port number by typing a command lsnrctl status on windows command prompt. In my case, it was 127.0.0.1 with port number as 1521

Second, enter the below command with your hostname and port number:

sqlplus username/password@HostName:Port Number/PluggableDatabaseName.

For example:

sqlplus hr/[email protected]:1521/ORCLPDB.

How to Increase Import Size Limit in phpMyAdmin

1:nano /etc/php5/apache2/php.ini
you can find your php.ini location by uploading a file called phpinfo.php with the following contents<?php phpinfo();?> and access it by visiting yourdomain.com/phpinfo.php ,you will see the results

2:change the desired value to upload_max_filesize and post_max_size such as : upload_max_filesize = 200M post_max_size = 300M then it will become 200M.

3:restart your apache

bootstrap 4 file input doesn't show the file name

This works with Bootstrap 4.1.3:

<script>
    $("input[type=file]").change(function () {
        var fieldVal = $(this).val();

        // Change the node's value by removing the fake path (Chrome)
        fieldVal = fieldVal.replace("C:\\fakepath\\", "");

        if (fieldVal != undefined || fieldVal != "") {
            $(this).next(".custom-file-label").attr('data-content', fieldVal);
            $(this).next(".custom-file-label").text(fieldVal);
        }
    });
</script>

WPF Binding to parent DataContext

I dont know about XamGrid but that's what i'll do with a standard wpf DataGrid:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
            <DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

Since the TextBlock and the TextBox specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.

Getting the SQL from a Django QuerySet

This middleware will output every SQL query to your console, with color highlighting and execution time, it's been invaluable for me in optimizing some tricky requests

http://djangosnippets.org/snippets/290/

how to rotate a bitmap 90 degrees

By default the rotation point is the Canvas's (0,0) point, and my guess is that you may want to rotate it around the center. I did that:

protected void renderImage(Canvas canvas)
{
    Rect dest,drawRect ;

    drawRect = new Rect(0,0, mImage.getWidth(), mImage.getHeight());
    dest = new Rect((int) (canvas.getWidth() / 2 - mImage.getWidth() * mImageResize / 2), // left
                    (int) (canvas.getHeight()/ 2 - mImage.getHeight()* mImageResize / 2), // top
                    (int) (canvas.getWidth() / 2 + mImage.getWidth() * mImageResize / 2), //right
                    (int) (canvas.getWidth() / 2 + mImage.getHeight()* mImageResize / 2));// bottom

    if(!mRotate) {
        canvas.drawBitmap(mImage, drawRect, dest, null);
    } else {
        canvas.save(Canvas.MATRIX_SAVE_FLAG); //Saving the canvas and later restoring it so only this image will be rotated.
        canvas.rotate(90,canvas.getWidth() / 2, canvas.getHeight()/ 2);
        canvas.drawBitmap(mImage, drawRect, dest, null);
        canvas.restore();
    }
}

c# dictionary one key many values

As of .net3.5+ instead of using a Dictionary<IKey, List<IValue>> you can use a Lookup from the Linq namespace:

// lookup Order by payment status (1:m) 
// would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
IEnumerable<Order> payedOrders = byPayment[false];

From msdn:

A Lookup resembles a Dictionary. The difference is that a Dictionary maps keys to single values, whereas a Lookup maps keys to collections of values.

You can create an instance of a Lookup by calling ToLookup on an object that implements IEnumerable.

You may also want to read this answer to a related question. For more info, consult msdn.

Full example:

using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqLookupSpike
{
    class Program
    {
        static void Main(String[] args)
        {
            // init 
            var orderList = new List<Order>();
            orderList.Add(new Order(1, 1, 2010, true));//(orderId, customerId, year, isPayed)
            orderList.Add(new Order(2, 2, 2010, true));
            orderList.Add(new Order(3, 1, 2010, true));
            orderList.Add(new Order(4, 2, 2011, true));
            orderList.Add(new Order(5, 2, 2011, false));
            orderList.Add(new Order(6, 1, 2011, true));
            orderList.Add(new Order(7, 3, 2012, false));

            // lookup Order by its id (1:1, so usual dictionary is ok)
            Dictionary<Int32, Order> orders = orderList.ToDictionary(o => o.OrderId, o => o);

            // lookup Order by customer (1:n) 
            // would need something like Dictionary<Int32, IEnumerable<Order>> orderIdByCustomer
            ILookup<Int32, Order> byCustomerId = orderList.ToLookup(o => o.CustomerId);
            foreach (var customerOrders in byCustomerId)
            {
                Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
                foreach (var order in customerOrders)
                {
                    Console.WriteLine("    Order {0} is payed: {1}", order.OrderId, order.IsPayed);
                }
            }

            // the same using old fashioned Dictionary
            Dictionary<Int32, List<Order>> orderIdByCustomer;
            orderIdByCustomer = byCustomerId.ToDictionary(g => g.Key, g => g.ToList());
            foreach (var customerOrders in orderIdByCustomer)
            {
                Console.WriteLine("Customer {0} ordered:", customerOrders.Key);
                foreach (var order in customerOrders.Value)
                {
                    Console.WriteLine("    Order {0} is payed: {1}", order.OrderId, order.IsPayed);
                }
            }

            // lookup Order by payment status (1:m) 
            // would need something like Dictionary<Boolean, IEnumerable<Order>> orderIdByIsPayed
            ILookup<Boolean, Order> byPayment = orderList.ToLookup(o => o.IsPayed);
            IEnumerable<Order> payedOrders = byPayment[false];
            foreach (var payedOrder in payedOrders)
            {
                Console.WriteLine("Order {0} from Customer {1} is not payed.", payedOrder.OrderId, payedOrder.CustomerId);
            }
        }

        class Order
        {
            // key properties
            public Int32 OrderId { get; private set; }
            public Int32 CustomerId { get; private set; }
            public Int32 Year { get; private set; }
            public Boolean IsPayed { get; private set; }

            // additional properties
            // private List<OrderItem> _items;

            public Order(Int32 orderId, Int32 customerId, Int32 year, Boolean isPayed)
            {
                OrderId = orderId;
                CustomerId = customerId;
                Year = year;
                IsPayed = isPayed;
            }
        }
    }
}

Remark on Immutability

By default, Lookups are kind of immutable and accessing the internals would involve reflection. If you need mutability and don't want to write your own wrapper, you could use MultiValueDictionary (formerly known as MultiDictionary) from corefxlab (formerly part ofMicrosoft.Experimental.Collections which isn't updated anymore).

How to set NODE_ENV to production/development in OS X

It might be a chance that you have made two instances of sequelize object

for example : var con1=new Sequelize(); var con2=new Sequelize();

than also same error will occur

How to enable PHP short tags?

If you are using Ubuntu with Apache+php5, then on current versions there are 2 places where you need to change to short_open_tag = On

  1. /etc/php5/apache2/php.ini - this is for the pages loaded through your web server (Apache)
  2. /etc/php5/cli/php.ini - this configuration is used when you launch your php files from command line, like: php yourscript.php - that goes for manually or cronjob executed php files directly on the server.

Add a default value to a column through a migration

For Rails 4+, use change_column_default

def change
  change_column_default :table, :column, value
end

Is there a macro to conditionally copy rows to another worksheet?

The way I would do this manually is:

  • Use Data - AutoFilter
  • Apply a custom filter based on a date range
  • Copy the filtered data to the relevant month sheet
  • Repeat for every month

Listed below is code to do this process via VBA.

It has the advantage of handling monthly sections of data rather than individual rows. Which can result in quicker processing for larger sets of data.

    Sub SeperateData()

    Dim vMonthText As Variant
    Dim ExcelLastCell As Range
    Dim intMonth As Integer

   vMonthText = Array("January", "February", "March", "April", "May", _
 "June", "July", "August", "September", "October", "November", "December")

        ThisWorkbook.Worksheets("Sharepoint").Select
        Range("A1").Select

    RowCount = ThisWorkbook.Worksheets("Sharepoint").UsedRange.Rows.Count
'Forces excel to determine the last cell, Usually only done on save
    Set ExcelLastCell = ThisWorkbook.Worksheets("Sharepoint"). _
     Cells.SpecialCells(xlLastCell)
'Determines the last cell with data in it


        Selection.EntireColumn.Insert
        Range("A1").FormulaR1C1 = "Month No."
        Range("A2").FormulaR1C1 = "=MONTH(RC[1])"
        Range("A2").Select
        Selection.Copy
        Range("A3:A" & ExcelLastCell.Row).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Calculate
    'Insert a helper column to determine the month number for the date

        For intMonth = 1 To 12
            Range("A1").CurrentRegion.Select
            Selection.AutoFilter Field:=1, Criteria1:="" & intMonth
            Selection.Copy
            ThisWorkbook.Worksheets("" & vMonthText(intMonth - 1)).Select
            Range("A1").Select
            ActiveSheet.Paste
            Columns("A:A").Delete Shift:=xlToLeft
            Cells.Select
            Cells.EntireColumn.AutoFit
            Range("A1").Select
            ThisWorkbook.Worksheets("Sharepoint").Select
            Range("A1").Select
            Application.CutCopyMode = False
        Next intMonth
    'Filter the data to a particular month
    'Convert the month number to text
    'Copy the filtered data to the month sheet
    'Delete the helper column
    'Repeat for each month

        Selection.AutoFilter
        Columns("A:A").Delete Shift:=xlToLeft
 'Get rid of the auto-filter and delete the helper column

    End Sub

Autonumber value of last inserted row - MS Access / VBA

In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:

  Dim query As String
  Dim newRow As Long  ' note change of data type
  Dim db As DAO.Database

  query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
  Set db = CurrentDB
  db.Execute(query)
  newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
  Set db = Nothing

I used to do INSERTs by opening an AddOnly recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO.

Chrome extension: accessing localStorage in content script

Update 2016:

Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html

It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.

    // Save it using the Chrome extension storage API.
    chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
      console.log('Settings saved');
    });

    // Read it using the storage API
    chrome.storage.sync.get(['foo', 'bar'], function(items) {
      message('Settings retrieved', items);
    });

To use it, make sure you define it in the manifest:

    "permissions": [
      "storage"
    ],

There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"

Using native localStorage (old reply from 2011)

Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.

Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.

The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});

You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.

I hope that helped solve your problem.

To be fancy and generic ...

contentscript.js

chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});

javax vs java package

java.* packages are the core Java language packages, meaning that programmers using the Java language had to use them in order to make any worthwhile use of the java language.

javax.* packages are optional packages, which provides a standard, scalable way to make custom APIs available to all applications running on the Java platform.

NOW() function in PHP

In PHP the logic equivalent of the MySQL's function now() is time().

But time() return a Unix timestamp that is different from a MySQL DATETIME.

So you must convert the Unix timestamp returned from time() in the MySQL format.

You do it with: date("Y-m-d H:i:s");

But where is time() in the date() function? It's the second parameter: infact you should provide to date() a timestamp as second parameter, but if it is omissed it is defaulted to time().

This is the most complete answer I can imagine.

Greetings.

How do you make a deep copy of an object?

One very easy and simple approach is to use Jackson JSON to serialize complex Java Object to JSON and read it back.

From https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator :

JsonFactory f = mapper.getFactory(); // may alternatively construct directly too

// First: write simple JSON output
File jsonFile = new File("test.json");
JsonGenerator g = f.createGenerator(jsonFile);
// write JSON: { "message" : "Hello world!" }
g.writeStartObject();
g.writeStringField("message", "Hello world!");
g.writeEndObject();
g.close();

// Second: read file back
JsonParser p = f.createParser(jsonFile);

JsonToken t = p.nextToken(); // Should be JsonToken.START_OBJECT
t = p.nextToken(); // JsonToken.FIELD_NAME
if ((t != JsonToken.FIELD_NAME) || !"message".equals(p.getCurrentName())) {
   // handle error
}
t = p.nextToken();
if (t != JsonToken.VALUE_STRING) {
   // similarly
}
String msg = p.getText();
System.out.printf("My message to you is: %s!\n", msg);
p.close();

How to force child div to be 100% of parent div's height without specifying parent's height?

NOTE: This answer is applicable to legacy browsers without support for the Flexbox standard. For a modern approach, see: https://stackoverflow.com/a/23300532/1155721


I suggest you take a look at Equal Height Columns with Cross-Browser CSS and No Hacks.

Basically, doing this with CSS in a browser compatible way is not trivial (but trivial with tables) so find yourself an appropriate pre-packaged solution.

Also, the answer varies on whether you want 100% height or equal height. Usually it's equal height. If it's 100% height the answer is slightly different.

How do I get a specific range of numbers from rand()?

rand() will return numbers between 0 and RAND_MAX, which is at least 32767.

If you want to get a number within a range, you can just use modulo.

int value = rand() % 66; // 0-65

For more accuracy, check out this article. It discusses why modulo is not necessarily good (bad distributions, particularly on the high end), and provides various options.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Please see my working sample application on Github and compare with your set up.

How do I export (and then import) a Subversion repository?

The tool to do that would be

svnadmin dump

But for this to work, you need filesystem-access to the repository. And once you have that (and provided the repository is in FSFS format), you can just copy the repository to its new location (if it's in BDB format, dump/load is strongly recommended).

If you do not have filesystem access, you would have to ask your repository provider to provide the dump for you (and make them delete their repository - and hope they comply)

Angular 5 Button Submit On Enter Key Press

You could also use a dummy form arround it like:

<mat-card-footer>
<form (submit)="search(ref, id, forename, surname, postcode)" action="#">
  <button mat-raised-button type="submit" class="successButton" id="invSearch" title="Click to perform search." >Search</button>
</form>
</mat-card-footer>

the search function has to return false to make sure that the action doesn't get executed.
Just make sure the form is focused (should be when you have the input in the form) when you press enter.

How to install PIP on Python 3.6?

If pip doesn't come with your installation of python 3.6, this may work:

wget https://bootstrap.pypa.io/get-pip.py
sudo python3.6 get-pip.py

then you can python -m install

Select NOT IN multiple columns

You should probably use NOT EXISTS for multiple columns.

ng is not recognized as an internal or external command

I also tried to play with cmd by setting environment variable path & etc, but simple answer is use nodejs command prompt.

So you no need to set environment variable path or anything. When you insalled nodejs it will give it's command prompt, by using that you us "ng" command, without any settings.

How do I debug "Error: spawn ENOENT" on node.js?

in windows, simply adding shell: true option solved my problem:

incorrect:

const { spawn } = require('child_process');
const child = spawn('dir');

correct:

const { spawn } = require('child_process');
const child = spawn('dir', [], {shell: true});

AngularJS: ng-model not binding to ng-checked for checkboxes

ngModel and ngChecked are not meant to be used together.

ngChecked is expecting an expression, so by saying ng-checked="true", you're basically saying that the checkbox will always be checked by default.

You should be able to just use ngModel, tied to a boolean property on your model. If you want something else, then you either need to use ngTrueValue and ngFalseValue (which only support strings right now), or write your own directive.

What is it exactly that you're trying to do? If you just want the first checkbox to be checked by default, you should change your model -- item1: true,.

Edit: You don't have to submit your form to debug the current state of the model, btw, you can just dump {{testModel}} into your HTML (or <pre>{{testModel|json}}</pre>). Also your ngModel attributes can be simplified to ng-model="testModel.item1".

http://plnkr.co/edit/HtdOok8aieBjT5GFZOb3?p=preview

Insert 2 million rows into SQL Server quickly

I ran into this scenario recently (well over 7 million rows) and eneded up using sqlcmd via powershell (after parsing raw data into SQL insert statements) in segments of 5,000 at a time (SQL can't handle 7 million lines in one lump job or even 500,000 lines for that matter unless its broken down into smaller 5K pieces. You can then run each 5K script one after the other.) as I needed to leverage the new sequence command in SQL Server 2012 Enterprise. I couldn't find a programatic way to insert seven million rows of data quickly and efficiently with said sequence command.

Secondly, one of the things to look out for when inserting a million rows or more of data in one sitting is the CPU and memory consumption (mostly memory) during the insert process. SQL will eat up memory/CPU with a job of this magnitude without releasing said processes. Needless to say if you don't have enough processing power or memory on your server you can crash it pretty easily in a short time (which I found out the hard way). If you get to the point to where your memory consumption is over 70-75% just reboot the server and the processes will be released back to normal.

I had to run a bunch of trial and error tests to see what the limits for my server was (given the limited CPU/Memory resources to work with) before I could actually have a final execution plan. I would suggest you do the same in a test environment before rolling this out into production.

How do I rename a column in a SQLite database table?

As mentioned before, there is a tool SQLite Database Browser, which does this. Lyckily, this tool keeps a log of all operations performed by the user or the application. Doing this once and looking at the application log, you will see the code involved. Copy the query and paste as required. Worked for me. Hope this helps

Onclick on bootstrap button

You can use 'onclick' attribute like this :

<a ... href="javascript: onclick();" ...>...</a>

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

Two problems:

1 - You never told Git to start tracking any file

You write that you ran

git init
git commit -m "first commit"

and that, at that stage, you got

nothing added to commit but untracked files present (use "git add" to track).

Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):

Hey Git, you see that README.md file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...

For that you need to stage the files of interest, using

git add README.md

before running

git commit -m "some descriptive message"

2 - You haven't set up the remote repository

You then ran

git remote add origin https://github.com/VijayNew/NewExample.git

After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists! However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get

enter image description here

Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with

git push -u origin master

Deep cloning objects

In general, you implement the ICloneable interface and implement Clone yourself. C# objects have a built-in MemberwiseClone method that performs a shallow copy that can help you out for all the primitives.

For a deep copy, there is no way it can know how to automatically do it.

How to check whether a Storage item is set?

You can also try this if you want to check for undefined:

if (localStorage.user === undefined) {
    localStorage.user = "username";
}

getItem is a method which returns null if value is not found.

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Tag your action:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

For ASP.NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Tag a whole API controller:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

For Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code

Netbeans - class does not have a main method

Exceute the program by pressing SHIFT+F6, instead of clicking the RUN button on the window. This might be silly, bt the error main class not found is not occurring, the project is executing well...

Capitalize the first letter of string in AngularJs

You can try to split your String into two parts and manage their case separately.

{{ (Name.charAt(0) | uppercase) + "" + (Name.slice(1, element.length) | lowercase) }}

or

{{ Name.charAt(0) | uppercase }} {{ Name.slice(1, element.length) | lowercase  }}

Multiple WHERE Clauses with LINQ extension methods

If you working with in-memory data (read "collections of POCO") you may also stack your expressions together using PredicateBuilder like so:

// initial "false" condition just to start "OR" clause with
var predicate = PredicateBuilder.False<YourDataClass>();

if (condition1)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Tom");
}

if (condition2)
{
    predicate = predicate.Or(d => d.SomeStringProperty == "Alex");
}

if (condition3)
{
    predicate = predicate.And(d => d.SomeIntProperty >= 4);
}

return originalCollection.Where<YourDataClass>(predicate.Compile());

The full source of mentioned PredicateBuilder is bellow (but you could also check the original page with a few more examples):

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;

public static class PredicateBuilder
{
  public static Expression<Func<T, bool>> True<T> ()  { return f => true;  }
  public static Expression<Func<T, bool>> False<T> () { return f => false; }

  public static Expression<Func<T, bool>> Or<T> (this Expression<Func<T, bool>> expr1,
                                                      Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
  }

  public static Expression<Func<T, bool>> And<T> (this Expression<Func<T, bool>> expr1,
                                                       Expression<Func<T, bool>> expr2)
  {
    var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast<Expression> ());
    return Expression.Lambda<Func<T, bool>>
          (Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
  }
}

Note: I've tested this approach with Portable Class Library project and have to use .Compile() to make it work:

Where(predicate .Compile() );

How to fix: Error device not found with ADB.exe

Don't forget to go to your device and enable Settings->Developer Options->USB debugging.

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

angularjs getting previous route path

Just to document:

The callback argument previousRoute is having a property called $route which is much similar to the $route service. Unfortunately currentRoute argument, is not having much information about the current route.

To overcome this i have tried some thing like this.

$routeProvider.
   when('/', {
    controller:...,
    templateUrl:'...',
    routeName:"Home"
  }).
  when('/menu', {
    controller:...,
    templateUrl:'...',
    routeName:"Site Menu"
  })

Please note that in the above routes config a custom property called routeName is added.

app.run(function($rootScope, $route){
    //Bind the `$routeChangeSuccess` event on the rootScope, so that we dont need to 
    //bind in induvidual controllers.
    $rootScope.$on('$routeChangeSuccess', function(currentRoute, previousRoute) {
        //This will give the custom property that we have defined while configuring the routes.
        console.log($route.current.routeName)
    })
})

How to run a Maven project from Eclipse?

(Alt + Shift + X) , then M to Run Maven Build. You will need to specify the Maven goals you want on Run -> Run Configurations

Creating a BAT file for python script

c:\python27\python.exe c:\somescript.py %*

How to print an exception in Python?

Python 3: logging

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)

Logging an exception can be done with the module-level function logging.exception() like so:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

Output:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

Notes:

  • the function logging.exception() should only be called from an exception handler

  • the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)


Alternative log-levels

It's also possible to log the exception with another log-level by using the keyword argument exc_info=True like so:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

Nullable property to entity field, Entity Framework through Code First

Just omit the [Required] attribute from the string somefield property. This will make it create a NULLable column in the db.

To make int types allow NULLs in the database, they must be declared as nullable ints in the model:

// an int can never be null, so it will be created as NOT NULL in db
public int someintfield { get; set; }

// to have a nullable int, you need to declare it as an int?
// or as a System.Nullable<int>
public int? somenullableintfield { get; set; }
public System.Nullable<int> someothernullableintfield { get; set; }

Matplotlib transparent line plots

It really depends on what functions you're using to plot the lines, but try see if the on you're using takes an alpha value and set it to something like 0.5. If that doesn't work, try get the line objects and set their alpha values directly.

Converting List<String> to String[] in Java

You want

String[] strarray = strlist.toArray(new String[0]);

See here for the documentation and note that you can also call this method in such a way that it populates the passed array, rather than just using it to work out what type to return. Also note that maybe when you print your array you'd prefer

System.out.println(Arrays.toString(strarray));

since that will print the actual elements.

Counting in a FOR loop using Windows Batch script

Here is a batch file that generates all 10.x.x.x addresses

@echo off

SET /A X=0
SET /A Y=0
SET /A Z=0

:loop
SET /A X+=1
echo 10.%X%.%Y%.%Z%
IF "%X%" == "256" (
 GOTO end
 ) ELSE (
 GOTO loop2
 GOTO loop
 )


:loop2
SET /A Y+=1
echo 10.%X%.%Y%.%Z%
IF "%Y%" == "256" (
  SET /A Y=0
  GOTO loop
  ) ELSE (
   GOTO loop3
   GOTO loop2
 )


:loop3

SET /A Z+=1
echo 10.%X%.%Y%.%Z%
IF "%Z%" == "255" (
  SET /A Z=0
  GOTO loop2
 ) ELSE (
   GOTO loop3
 )

:end

java.lang.RuntimeException: Unable to start activity ComponentInfo

I had the same issue, I cleaned and rebuilt the project and it worked.

How to use foreach with a hash reference?

As others have stated, you have to dereference the reference. The keys function requires that its argument starts with a %:

My preference:

foreach my $key (keys %{$ad_grp_ref}) {

According to Conway:

foreach my $key (keys %{ $ad_grp_ref }) {

Guess who you should listen to...

You might want to read through the Perl Reference Documentation.

If you find yourself doing a lot of stuff with references to hashes and hashes of lists and lists of hashes, you might want to start thinking about using Object Oriented Perl. There's a lot of nice little tutorials in the Perl documentation.

java.lang.IllegalArgumentException: contains a path separator

The solution is:

FileInputStream fis = new FileInputStream (new File(NAME_OF_FILE));  // 2nd line

The openFileInput method doesn't accept path separators.

Don't forget to

fis.close();

at the end.

cut or awk command to print first field of first row

You could use the head instead of cat:

head -n1 /etc/*release | awk '{print $1}'

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

For anyone else wondering how to achieve this, here is my extended EditText class EditTextNumeric.

.setMaxLength(int) - sets maximum number of digits

.setMaxValue(int) - limit maximum integer value

.setMin(int) - limit minimum integer value

.getValue() - get integer value

import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;

public class EditTextNumeric extends EditText {
    protected int max_value = Integer.MAX_VALUE;
    protected int min_value = Integer.MIN_VALUE;

    // constructor
    public EditTextNumeric(Context context) {
        super(context);
        this.setInputType(InputType.TYPE_CLASS_NUMBER);
    }

    // checks whether the limits are set and corrects them if not within limits
    @Override
    protected void onTextChanged(CharSequence text, int start, int before, int after) {
        if (max_value != Integer.MAX_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) > max_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(max_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        if (min_value != Integer.MIN_VALUE) {
            try {
                if (Integer.parseInt(this.getText().toString()) < min_value) {
                    // change value and keep cursor position
                    int selection = this.getSelectionStart();
                    this.setText(String.valueOf(min_value));
                    if (selection >= this.getText().toString().length()) {
                        selection = this.getText().toString().length();
                    }
                    this.setSelection(selection);
                }
            } catch (NumberFormatException exception) {
                super.onTextChanged(text, start, before, after);
            }
        }
        super.onTextChanged(text, start, before, after);
    }

    // set the max number of digits the user can enter
    public void setMaxLength(int length) {
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(length);
        this.setFilters(FilterArray);
    }

    // set the maximum integer value the user can enter.
    // if exeeded, input value will become equal to the set limit
    public void setMaxValue(int value) {
        max_value = value;
    }
    // set the minimum integer value the user can enter.
    // if entered value is inferior, input value will become equal to the set limit
    public void setMinValue(int value) {
        min_value = value;
    }

    // returns integer value or 0 if errorous value
    public int getValue() {
        try {
            return Integer.parseInt(this.getText().toString());
        } catch (NumberFormatException exception) {
            return 0;
        }
    }
}

Example usage:

final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);

All other methods and attributes that apply to EditText, of course work too.

TextView bold via xml file?

I have a project in which I have the following TextView :

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textStyle="bold"
    android:text="@string/app_name"
    android:layout_gravity="center" 
/>

So, I'm guessing you need to use android:textStyle

Calling functions in a DLL from C++

You can either go the LoadLibrary/GetProcAddress route (as Harper mentioned in his answer, here's link to the run-time dynamic linking MSDN sample again) or you can link your console application to the .lib produced from the DLL project and include the hea.h file with the declaration of your function (as described in the load-time dynamic linking MSDN sample)

In both cases, you need to make sure your DLL exports the function you want to call properly. The easiest way to do it is by using __declspec(dllexport) on the function declaration (as shown in the creating a simple dynamic-link library MSDN sample), though you can do it also through the corresponding .def file in your DLL project.

For more information on the topic of DLLs, you should browse through the MSDN About Dynamic-Link Libraries topic.

How can I update npm on Windows?

I was also facing similar issues. I followed below mentioned steps and it worked for me:

  • go to Windows > Start > Node.js

    • right click on Node.js command prompt
    • click on Run as administrator
  • ping registry.npmjs.org

  • npm view npm version

  • cd %ProgramFiles%\nodejs

  • npm install npm@latest

and npm updated successfully. Earlier I was trying for CMD and that was throwing error. may be some path issue that got resolved by running NodeJs Command Prompt. hope it'll work for you. try this.

Console.WriteLine and generic List

        List<int> a = new List<int>() { 1, 2, 3, 4, 5 };
        a.ForEach(p => Console.WriteLine(p));

edit: ahhh he beat me to it.

C compile error: Id returned 1 exit status

I may guess, the old instance of your program is still running. Windows does not allow to change the files which are currently "in use" and your linker cannot write the new .exe on the top of the running one. Try stopping/killing your program.

How to create a 100% screen width div inside a container in bootstrap?

2019's answer as this is still actively seen today

You should likely change the .container to .container-fluid, which will cause your container to stretch the entire screen. This will allow any div's inside of it to naturally stretch as wide as they need.

original hack from 2015 that still works in some situations

You should pull that div outside of the container. You're asking a div to stretch wider than its parent, which is generally not recommended practice.

If you cannot pull it out of the div for some reason, you should change the position style with this css:

.full-width-div {
    position: absolute;
    width: 100%;
    left: 0;
}

Instead of absolute, you could also use fixed, but then it will not move as you scroll.

Could not load file or assembly '' or one of its dependencies

Try checking if the "Copy to Local" property for the reference is set to true and the specific version is set to true. This is relevant for applications in Visual Studio.

How to update record using Entity Framework 6?

This if for Entity Framework 6.2.0.

If you have a specific DbSet and an item that needs to be either updated or created:

var name = getNameFromService();

var current = _dbContext.Names.Find(name.BusinessSystemId, name.NameNo);
if (current == null)
{
    _dbContext.Names.Add(name);
}
else
{
    _dbContext.Entry(current).CurrentValues.SetValues(name);
}
_dbContext.SaveChanges();

However this can also be used for a generic DbSet with a single primary key or a composite primary key.

var allNames = NameApiService.GetAllNames();
GenericAddOrUpdate(allNames, "BusinessSystemId", "NameNo");

public virtual void GenericAddOrUpdate<T>(IEnumerable<T> values, params string[] keyValues) where T : class
{
    foreach (var value in values)
    {
        try
        {
            var keyList = new List<object>();

            //Get key values from T entity based on keyValues property
            foreach (var keyValue in keyValues)
            {
                var propertyInfo = value.GetType().GetProperty(keyValue);
                var propertyValue = propertyInfo.GetValue(value);
                keyList.Add(propertyValue);
            }

            GenericAddOrUpdateDbSet(keyList, value);
            //Only use this when debugging to catch save exceptions
            //_dbContext.SaveChanges();
        }
        catch
        {
            throw;
        }
    }
    _dbContext.SaveChanges();
}

public virtual void GenericAddOrUpdateDbSet<T>(List<object> keyList, T value) where T : class
{
    //Get a DbSet of T type
    var someDbSet = Set(typeof(T));

    //Check if any value exists with the key values
    var current = someDbSet.Find(keyList.ToArray());
    if (current == null)
    {
        someDbSet.Add(value);
    }
    else
    {
        Entry(current).CurrentValues.SetValues(value);
    }
}

How to change the status bar background color and text color on iOS 7?

iTroid23 solution worked for me. I missed the Swift solution. So maybe this is helpful:

1) In my plist I had to add this:

<key>UIViewControllerBasedStatusBarAppearance</key>
<true/>

2) I didn't need to call "setNeedsStatusBarAppearanceUpdate".

3) In swift I had to add this to my UIViewController:

override func preferredStatusBarStyle() -> UIStatusBarStyle {
    return UIStatusBarStyle.LightContent
}

Can I simultaneously declare and assign a variable in VBA?

In some cases the whole need for declaring a variable can be avoided by using With statement.

For example,

    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogSaveAs)
    If fd.Show Then
        'use fd.SelectedItems(1)
    End If

this can be rewritten as

    With Application.FileDialog(msoFileDialogSaveAs)
      If .Show Then
        'use .SelectedItems(1)
      End If
    End With

Serialize form data to JSON

Using jQuery and avoiding serializeArray, the following code serializes and sends the form data in JSON format:

$("#commentsForm").submit(function(event){
    var formJqObj = $("#commentsForm");
    var formDataObj = {};
    (function(){
        formJqObj.find(":input").not("[type='submit']").not("[type='reset']").each(function(){
            var thisInput = $(this);
            formDataObj[thisInput.attr("name")] = thisInput.val();
        });
    })();
    $.ajax({
        type: "POST",
        url: YOUR_URL_HERE,
        data: JSON.stringify(formDataObj),
        contentType: "application/json"
    })
    .done(function(data, textStatus, jqXHR){
        console.log("Ajax completed: " + data);
    })
    .fail(function(jqXHR, textStatus, errorThrown){
        console.log("Ajax problem: " + textStatus + ". " + errorThrown);
    });
    event.preventDefault();
});

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

RE error: illegal byte sequence on Mac OS X

Add the following lines to your ~/.bash_profile or ~/.zshrc file(s).

export LC_CTYPE=C 
export LANG=C

Is there a difference between `continue` and `pass` in a for loop in python?

continue will jump back to the top of the loop. pass will continue processing.

if pass is at the end for the loop, the difference is negligible as the flow would just back to the top of the loop anyway.

How to bind RadioButtons to an enum?

For UWP, it is not so simple: You must jump through an extra hoop to pass a field value as a parameter.

Example 1

Valid for both WPF and UWP.

<MyControl>
    <MyControl.MyProperty>
        <Binding Converter="{StaticResource EnumToBooleanConverter}" Path="AnotherProperty">
            <Binding.ConverterParameter>
                <MyLibrary:MyEnum>Field</MyLibrary:MyEnum>
            </Binding.ConverterParameter>
        </MyControl>
    </MyControl.MyProperty>
</MyControl>

Example 2

Valid for both WPF and UWP.

...
<MyLibrary:MyEnum x:Key="MyEnumField">Field</MyLibrary:MyEnum>
...

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={StaticResource MyEnumField}}"/>

Example 3

Valid only for WPF!

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static MyLibrary:MyEnum.Field}}"/>

UWP doesn't support x:Static so Example 3 is out of the question; assuming you go with Example 1, the result is more verbose code. Example 2 is slightly better, but still not ideal.

Solution

public abstract class EnumToBooleanConverter<TEnum> : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;

        if (Parameter == null)
            return DependencyProperty.UnsetValue;

        if (Enum.IsDefined(typeof(TEnum), value) == false)
            return DependencyProperty.UnsetValue;

        return Enum.Parse(typeof(TEnum), Parameter).Equals(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;
        return Parameter == null ? DependencyProperty.UnsetValue : Enum.Parse(typeof(TEnum), Parameter);
    }
}

Then, for each type you wish to support, define a converter that boxes the enum type.

public class MyEnumToBooleanConverter : EnumToBooleanConverter<MyEnum>
{
    //Nothing to do!
}

The reason it must be boxed is because there's seemingly no way to reference the type in the ConvertBack method; the boxing takes care of that. If you go with either of the first two examples, you can just reference the parameter type, eliminating the need to inherit from a boxed class; if you wish to do it all in one line and with least verbosity possible, the latter solution is ideal.

Usage resembles Example 2, but is, in fact, less verbose.

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource MyEnumToBooleanConverter}, ConverterParameter=Field}"/>

The downside is you must define a converter for each type you wish to support.

How to render a PDF file in Android

Since API Level 21 (Lollipop) Android provides a PdfRenderer class:

// create a new renderer
 PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());

 // let us just render all pages
 final int pageCount = renderer.getPageCount();
 for (int i = 0; i < pageCount; i++) {
     Page page = renderer.openPage(i);

     // say we render for showing on the screen
     page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);

     // do stuff with the bitmap

     // close the page
     page.close();
 }

 // close the renderer
 renderer.close();

For more information see the sample app.

For older APIs I recommend Android PdfViewer library, it is very fast and easy to use, licensed under Apache License 2.0:

pdfView.fromAsset(String)
  .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
  .enableSwipe(true)
  .swipeHorizontal(false)
  .enableDoubletap(true)
  .defaultPage(0)
  .onDraw(onDrawListener)
  .onLoad(onLoadCompleteListener)
  .onPageChange(onPageChangeListener)
  .onPageScroll(onPageScrollListener)
  .onError(onErrorListener)
  .enableAnnotationRendering(false)
  .password(null)
  .scrollHandle(null)
  .load();

How to create web service (server & Client) in Visual Studio 2012?

  1. Create a new empty Asp.NET Web Application.
  2. Solution Explorer right click on the project root.
  3. Choose the menu item Add-> Web Service

Display unescaped HTML in Vue.js

Starting with Vue2, the triple braces were deprecated, you are to use v-html.

<div v-html="task.html_content"> </div>

It is unclear from the documentation link as to what we are supposed to place inside v-html, your variables goes inside v-html.

Also, v-html works only with <div> or <span> but not with <template>.

If you want to see this live in an app, click here.

How does RewriteBase work in .htaccess

AFAIK, RewriteBase is only used to fix cases where mod_rewrite is running in a .htaccess file not at the root of a site and it guesses the wrong web path (as opposed to filesystem path) for the folder it is running in. So if you have a RewriteRule in a .htaccess in a folder that maps to http://example.com/myfolder you can use:

RewriteBase myfolder

If mod_rewrite isn't working correctly.

Trying to use it to achieve something unusual, rather than to fix this problem sounds like a recipe to getting very confused.

Format date as dd/MM/yyyy using pipes

You can achieve this using by a simple custom pipe.

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({
    name: 'dateFormatPipe',
})
export class dateFormatPipe implements PipeTransform {
    transform(value: string) {
       var datePipe = new DatePipe("en-US");
        value = datePipe.transform(value, 'dd/MM/yyyy');
        return value;
    }
}


{{currentDate | dateFormatPipe }}

Advantage of using a custom pipe is that, if you want to update the date format in future, you can go and update your custom pipe and it will reflect every where.

Custom Pipe examples

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

In app store connect now if we are using ads in our app then we will answer as yes to Does this app use the Advertising Identifier (IDFA)?

further 3 questions will be asked as

enter image description here

if your using just admob then check the first one and leave other two unchecked. Other two options (2nd , 3rd ) will be checked if your using app flyer to show ads. all options are explained with detail here

How to calculate a mod b in Python?

A = [3, 1, 2, 4]
for a in A:
    print(a % 2)

output:

1
1
0
0

assign headers based on existing row in dataframe in R

The key here is to unlist the row first.

colnames(DF) <- as.character(unlist(DF[1,]))
DF = DF[-1, ]

How to convert interface{} to string?

You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)

Latest version of Docopt returns Opts object that has methods for conversion:

host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port

CodeIgniter: How to get Controller, Action, URL information

$this->router->fetch_class(); 

// fecth class the class in controller $this->router->fetch_method();

// method

add new row in gridview after binding C#, ASP.net

If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:

adapter.Fill(ds);
ds.Tables(0).Rows.Add();

How can I open a Shell inside a Vim Window?

I am currently using tmux.

Installation: sudo apt-get install tmux Run it: tmux

Ctrl + b followed by Ctr + % : it splits your terminal window in two vertical halves.

Ctrl + "arrow left | arrow right" : moves between terminals.

How do you create a read-only user in PostgreSQL?

I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.

How to list running screen sessions?

In most cases a screen -RRx $username/ will suffice :)

If you still want to list all screens then put the following script in your path and call it screen or whatever you like:

#!/bin/bash
if [[ "$1" != "-ls-all" ]]; then
    exec /usr/bin/screen "$@"
else
    shopt -s nullglob
    screens=(/var/run/screen/S-*/*)
    if (( ${#screens[@]} == 0 )); then
        echo "no screen session found in /var/run/screen"
    else
        echo "${screens[@]#*S-}"
    fi
fi

It will behave exactly like screen except for showing all screen sessions, when giving the option -ls-all as first parameter.

About catching ANY exception

Very simple example, similar to the one found here:

http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

In the above example, you'd see output in this order:

1) Performing an action which may throw an exception.

2) Finally is called directly after executing the try statement whether an exception is thrown or not.

3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.

Hope this helps!

"This SqlTransaction has completed; it is no longer usable."... configuration error?

In my case , I've some codes which needs to execute after committing the transaction at the same try catch block.One of the code threw an error then try block handed over the error to it's catch block which contains the transaction rollback. It will show the similar error. For example look at the code structure below :

SqlTransaction trans = null;

try{
 trans = Con.BeginTransaction();
// your codes

  trans.Commit();
//your codes having errors

}
catch(Exception ex)
{
     trans.Rollback(); //transaction roll back
    // error message
}

finally
{ 
    // connection close
}

Hope it will someone :)

What is the difference between & vs @ and = in angularJS

I would like to explain the concepts from the perspective of JavaScript prototype inheritance. Hopefully help to understand.

There are three options to define the scope of a directive:

  1. scope: false: Angular default. The directive's scope is exactly the one of its parent scope (parentScope).
  2. scope: true: Angular creates a scope for this directive. The scope prototypically inherits from parentScope.
  3. scope: {...}: isolated scope is explained below.

Specifying scope: {...} defines an isolatedScope. An isolatedScope does not inherit properties from parentScope, although isolatedScope.$parent === parentScope. It is defined through:

app.directive("myDirective", function() {
    return {
        scope: {
            ... // defining scope means that 'no inheritance from parent'.
        },
    }
})

isolatedScope does not have direct access to parentScope. But sometimes the directive needs to communicate with the parentScope. They communicate through @, = and &. The topic about using symbols @, = and & are talking about scenarios using isolatedScope.

It is usually used for some common components shared by different pages, like Modals. An isolated scope prevents polluting the global scope and is easy to share among pages.

Here is a basic directive: http://jsfiddle.net/7t984sf9/5/. An image to illustrate is:

enter image description here

@: one-way binding

@ simply passes the property from parentScope to isolatedScope. It is called one-way binding, which means you cannot modify the value of parentScope properties. If you are familiar with JavaScript inheritance, you can understand these two scenarios easily:

  • If the binding property is a primitive type, like interpolatedProp in the example: you can modify interpolatedProp, but parentProp1 would not be changed. However, if you change the value of parentProp1, interpolatedProp will be overwritten with the new value (when angular $digest).

  • If the binding property is some object, like parentObj: since the one passed to isolatedScope is a reference, modifying the value will trigger this error:

    TypeError: Cannot assign to read only property 'x' of {"x":1,"y":2}

=: two-way binding

= is called two-way binding, which means any modification in childScope will also update the value in parentScope, and vice versa. This rule works for both primitives and objects. If you change the binding type of parentObj to be =, you will find that you can modify the value of parentObj.x. A typical example is ngModel.

&: function binding

& allows the directive to call some parentScope function and pass in some value from the directive. For example, check JSFiddle: & in directive scope.

Define a clickable template in the directive like:

<div ng-click="vm.onCheck({valueFromDirective: vm.value + ' is from the directive'})">

And use the directive like:

<div my-checkbox value="vm.myValue" on-check="vm.myFunction(valueFromDirective)"></div>

The variable valueFromDirective is passed from the directive to the parent controller through {valueFromDirective: ....

Reference: Understanding Scopes

Remove duplicates from an array of objects in JavaScript

I think the best approach is using reduce and Map object. This is a single line solution.

_x000D_
_x000D_
const data = [
  {id: 1, name: 'David'},
  {id: 2, name: 'Mark'},
  {id: 2, name: 'Lora'},
  {id: 4, name: 'Tyler'},
  {id: 4, name: 'Donald'},
  {id: 5, name: 'Adrian'},
  {id: 6, name: 'Michael'}
]

const uniqueData = [...data.reduce((map, obj) => map.set(obj.id, obj), new Map()).values()];

console.log(uniqueData)

/*
  in `map.set(obj.id, obj)`
  
  'obj.id' is key. (don't worry. we'll get only values using the .values() method)
  'obj' is whole object.
*/
_x000D_
_x000D_
_x000D_

Set maxlength in Html Textarea

resize:none; This property fix your text area and bound it. you use this css property id your textarea.gave text area an id and on the behalf of that id you can use this css property.

Returning boolean if set is empty

"""
This function check if set is empty or not.
>>> c = set([])
>>> set_is_empty(c)
True

:param some_set: set to check if he empty or not.
:return True if empty, False otherwise.
"""
def set_is_empty(some_set):
    return some_set == set()

json.net has key method?

JObject.ContainsKey(string propertyName) has been made as public method in 11.0.1 release

Documentation - https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm

Accessing Google Spreadsheets with C# using Google Data API

(Jun-Nov 2016) The question and its answers are now out-of-date as: 1) GData APIs are the previous generation of Google APIs. While not all GData APIs have been deprecated, all the latest Google APIs do not use the Google Data Protocol; and 2) there is a new Google Sheets API v4 (also not GData).

Moving forward from here, you need to get the Google APIs Client Library for .NET and use the latest Sheets API, which is much more powerful and flexible than any previous API. Here's a C# code sample to help get you started. Also check the .NET reference docs for the Sheets API and the .NET Google APIs Client Library developers guide.

If you're not allergic to Python (if you are, just pretend it's pseudocode ;) ), I made several videos with slightly longer, more "real-world" examples of using the API you can learn from and migrate to C# if desired:

Run a string as a command within a Bash script

your_command_string="..."
output=$(eval "$your_command_string")
echo "$output"

Align text in a table header

Try using style for th

th {text-align:center}

How to write a simple Java program that finds the greatest common divisor between two numbers?

You can also do it in a three line method:

public static int gcd(int x, int y){
  return (y == 0) ? x : gcd(y, x % y);
}

Here, if y = 0, x is returned. Otherwise, the gcd method is called again, with different parameter values.

How to find GCD, LCM on a set of numbers

There is an Euclid's algorithm for GCD,

public int GCF(int a, int b) {
    if (b == 0) return a;
    else return (GCF (b, a % b));
}

By the way, a and b should be greater or equal 0, and LCM = |ab| / GCF(a, b)

How can I select rows by range?

Assuming id is the primary key of table :

SELECT * FROM table WHERE id BETWEEN 10 AND 50

For first 20 results

SELECT * FROM table order by id limit 20;

Get the closest number out of an array

For sorted arrays (linear search)

All answers so far concentrate on searching through the whole array. Considering your array is sorted already and you really only want the nearest number this is probably the fastest solution:

_x000D_
_x000D_
var a = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362];_x000D_
var target = 90000;_x000D_
_x000D_
/**_x000D_
 * Returns the closest number from a sorted array._x000D_
 **/_x000D_
function closest(arr, target) {_x000D_
  if (!(arr) || arr.length == 0)_x000D_
    return null;_x000D_
  if (arr.length == 1)_x000D_
    return arr[0];_x000D_
_x000D_
  for (var i = 1; i < arr.length; i++) {_x000D_
    // As soon as a number bigger than target is found, return the previous or current_x000D_
    // number depending on which has smaller difference to the target._x000D_
    if (arr[i] > target) {_x000D_
      var p = arr[i - 1];_x000D_
      var c = arr[i]_x000D_
      return Math.abs(p - target) < Math.abs(c - target) ? p : c;_x000D_
    }_x000D_
  }_x000D_
  // No number in array is bigger so return the last._x000D_
  return arr[arr.length - 1];_x000D_
}_x000D_
_x000D_
// Trying it out_x000D_
console.log(closest(a, target));
_x000D_
_x000D_
_x000D_

Note that the algorithm can be vastly improved e.g. using a binary tree.

foreach for JSON array , syntax

You can do something like

for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values. However, if you have a nested structure, you will need to use

typeof result[k] === "object"

to determine if you have to loop over the nested objects. Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary. However, I suppose it's possible that this expectation is not good for all cases.

Remove portion of a string after a certain character

Why...

This is likely overkill for most people's needs, but, it addresses a number of things that each individual answer above does not. Of the items it addresses, three of them were needed for my needs. With tight bracketing and dropping the comments, this could still remain readable at only 13 lines of code.

This addresses the following:

  • Performance impact of using REGEX vs strrpos/strstr/strripos/stristr.
  • Using strripos/strrpos when character/string not found in string.
  • Removing from left or right side of string (first or last occurrence) .
  • CaSe Sensitivity.
  • Wanting the ability to return back the original string unaltered if search char/string not found.

Usage:

Send original string, search char/string, "R"/"L" for start on right or left side, true/false for case sensitivity. For example, search for "here" case insensitive, in string, start right side.

echo TruncStringAfterString("Now Here Are Some Words Here Now","here","R",false);

Output would be "Now Here Are Some Words ". Changing the "R" to an "L" would output: "Now ".

Here's the function:

function TruncStringAfterString($origString,$truncChar,$startSide,$caseSensitive)
{
    if ($caseSensitive==true && strstr($origString,$truncChar)!==false)
    {
        // IF START RIGHT SIDE:
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strrpos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return strstr($origString,$truncChar,true);
        }           
    }
    elseif ($caseSensitive==false && stristr($origString,$truncChar)!==false)
    {           
        // IF START RIGHT SIDE: 
        if (strtoupper($startSide)=="R" || $startSide==false)
        {   // Found, strip off all chars from truncChar to end
            return substr($origString,0,strripos($origString,$truncChar));
        }

        // IF START LEFT SIDE: 
        elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
        {   // Found, strip off all chars from truncChar to end
            return stristr($origString,$truncChar,true);
        }
    }       
    else
    {   // NOT found - return origString untouched
        return $origString;     // Nothing to do here
    }           

}

How to upload file using Selenium WebDriver in Java

If you have a text box to type the file path, just use sendkeys to input the file path and click on submit button. If there is no text box to type the file path and only able to click on browse button and to select the file from windows popup, you can use AutoIt tool, see the step below to use AutoIt for the same,

  1. Download and Install Autoit tool from http://www.autoitscript.com/site/autoit/

  2. Open Programs -> Autoit tool -> SciTE Script Editor.

  3. Paste the following code in Autoit editor and save it as “filename.exe “(eg: new.exe)

    Then compile and build the file to make it exe. (Tools ? Compile)

Autoit Code:

WinWaitActive("File Upload"); Name of the file upload window (Windows Popup Name: File Upload)    
Send("logo.jpg"); File name    
Send("{ENTER}")

Then Compile and Build from Tools menu of the Autoit tool -> SciTE Script Editor.

Paste the below Java code in Eclipse editor and save

Java Code:

driver.findElement(By.id("uploadbutton")).click; // open the Upload window using selenium    
Thread.sleep("20000"); // wait for page load    
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:\\Documents and Settings\\new.exe"); // Give  path where the exe is saved.

What's the difference between primitive and reference types?

As many have stated more or less correctly what reference and primitive types are, one might be interested that we have some more relevant types in Java. Here is the complete lists of types in java (as far as I am aware of (JDK 11)).

Primitive Type

Describes a value (and not a type).

11

Reference Type

Describes a concrete type which instances extend Object (interface, class, enum, array). Furthermore TypeParameter is actually a reference type!

Integer

Note: The difference between primitive and reference type makes it necessary to rely on boxing to convert primitives in Object instances and vise versa.

Note2: A type parameter describes a type having an optional lower or upper bound and can be referenced by name within its context (in contrast to the wild card type). A type parameter typically can be applied to parameterized types (classes/interfaces) and methods. The parameter type defines a type identifier.

Wildcard Type

Expresses an unknown type (like any in TypeScript) that can have a lower or upper bound by using super or extend.

? extends List<String>
? super ArrayList<String>

Void Type

Nothingness. No value/instance possible.

void method();

Null Type

The only representation is 'null'. It is used especially during type interference computations. Null is a special case logically belonging to any type (can be assigned to any variable of any type) but is actual not considered an instance of any type (e.g. (null instanceof Object) == false).

null

Union Type

A union type is a type that is actual a set of alternative types. Sadly in Java it only exists for the multi catch statement.

catch(IllegalStateException | IOException e) {}

Interference Type

A type that is compatibile to multiple types. Since in Java a class has at most one super class (Object has none), interference types allow only the first type to be a class and every other type must be an interface type.

void method(List<? extends List<?> & Comparable> comparableList) {}

Unknown Type

The type is unknown. That is the case for certain Lambda definitions (not enclosed in brackets, single parameter).

list.forEach(element -> System.out.println(element.toString)); //element is of unknown type

Var Type

Unknown type introduced by a variable declaration spotting the 'var' keyword.

var variable = list.get(0);

Node.js: how to consume SOAP XML web service

I used the node net module to open a socket to the webservice.

/* on Login request */
socket.on('login', function(credentials /* {username} {password} */){   
    if( !_this.netConnected ){
        _this.net.connect(8081, '127.0.0.1', function() {
            logger.gps('('+socket.id + ') '+credentials.username+' connected to: 127.0.0.1:8081');
            _this.netConnected = true;
            _this.username = credentials.username;
            _this.password = credentials.password;
            _this.m_RequestId = 1;
            /* make SOAP Login request */
            soapGps('', _this, 'login', credentials.username);              
        });         
    } else {
        /* make SOAP Login request */
        _this.m_RequestId = _this.m_RequestId +1;
        soapGps('', _this, 'login', credentials.username);          
    }
});

Send soap requests

/* SOAP request func */
module.exports = function soapGps(xmlResponse, client, header, data) {
    /* send Login request */
    if(header == 'login'){
        var SOAP_Headers =  "POST /soap/gps/login HTTP/1.1\r\nHost: soap.example.com\r\nUser-Agent: SOAP-client/SecurityCenter3.0\r\n" +
                            "Content-Type: application/soap+xml; charset=\"utf-8\"";        
        var SOAP_Envelope=  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                            "<env:Envelope xmlns:env=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:SOAP-ENC=\"http://www.w3.org/2003/05/soap-encoding\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:n=\"http://www.example.com\"><env:Header><n:Request>" +
                            "Login" +
                            "</n:Request></env:Header><env:Body>" +
                            "<n:RequestLogin xmlns:n=\"http://www.example.com.com/gps/soap\">" +
                            "<n:Name>"+data+"</n:Name>" +
                            "<n:OrgID>0</n:OrgID>" +                                        
                            "<n:LoginEntityType>admin</n:LoginEntityType>" +
                            "<n:AuthType>simple</n:AuthType>" +
                            "</n:RequestLogin></env:Body></env:Envelope>";

        client.net.write(SOAP_Headers + "\r\nContent-Length:" + SOAP_Envelope.length.toString() + "\r\n\r\n");
        client.net.write(SOAP_Envelope);
        return;
    }

Parse soap response, i used module - xml2js

var parser = new xml2js.Parser({
    normalize: true,
    trim: true,
    explicitArray: false
});
//client.net.setEncoding('utf8');

client.net.on('data', function(response) {
    parser.parseString(response);
});

parser.addListener('end', function( xmlResponse ) {
    var response = xmlResponse['env:Envelope']['env:Header']['n:Response']._;
    /* handle Login response */
    if (response == 'Login'){
        /* make SOAP LoginContinue request */
        soapGps(xmlResponse, client, '');
    }
    /* handle LoginContinue response */
    if (response == 'LoginContinue') {
        if(xmlResponse['env:Envelope']['env:Body']['n:ResponseLoginContinue']['n:ErrCode'] == "ok") {           
            var nTimeMsecServer = xmlResponse['env:Envelope']['env:Body']['n:ResponseLoginContinue']['n:CurrentTime'];
            var nTimeMsecOur = new Date().getTime();
        } else {
            /* Unsuccessful login */
            io.to(client.id).emit('Error', "invalid login");
            client.net.destroy();
        }
    }
});

Hope it helps someone

Android Layout Weight

android:Layout_weight can be used when you don't attach a fix value to your width already like fill_parent etc.

Do something like this :

<Button>

Android:layout_width="0dp"
Android:layout_weight=1

-----other parameters
</Button>

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

mysql data directory location

If you install MySQL via homebrew on MacOS, you might need to delete your old data directory /usr/local/var/mysql. Otherwise, it will fail during the initialization process with the following error:

==> /usr/local/Cellar/mysql/8.0.16/bin/mysqld --initialize-insecure --user=hohoho --basedir=/usr/local/Cellar/mysql/8.0.16 --datadir=/usr/local/var/mysql --tmpdir=/tmp
2019-07-17T16:30:51.828887Z 0 [System] [MY-013169] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld (mysqld 8.0.16) initializing of server in progress as process 93487
2019-07-17T16:30:51.830375Z 0 [ERROR] [MY-010457] [Server] --initialize specified but the data directory has files in it. Aborting.
2019-07-17T16:30:51.830381Z 0 [ERROR] [MY-013236] [Server] Newly created data directory /usr/local/var/mysql/ is unusable. You can safely remove it.
2019-07-17T16:30:51.830410Z 0 [ERROR] [MY-010119] [Server] Aborting
2019-07-17T16:30:51.830540Z 0 [System] [MY-010910] [Server] /usr/local/Cellar/mysql/8.0.16/bin/mysqld: Shutdown complete (mysqld 8.0.16)  Homebrew.

Skip first entry in for loop in python?

The more_itertools project extends itertools.islice to handle negative indices.

Example

import more_itertools as mit

iterable = 'ABCDEFGH'
list(mit.islice_extended(iterable, 1, -1))
# Out: ['B', 'C', 'D', 'E', 'F', 'G']

Therefore, you can elegantly apply it slice elements between the first and last items of an iterable:

for car in mit.islice_extended(cars, 1, -1):
    # do something

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

Check if multiple strings exist in another string

I would use this kind of function for speed:

def check_string(string, substring_list):
    for substring in substring_list:
        if substring in string:
            return True
    return False

addEventListener in Internet Explorer

I'm using this solution and works in IE8 or greater.

if (typeof Element.prototype.addEventListener === 'undefined') {
    Element.prototype.addEventListener = function (e, callback) {
      e = 'on' + e;
      return this.attachEvent(e, callback);
    };
  }

And then:

<button class="click-me">Say Hello</button>

<script>
  document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
    console.log('Hello');
  });
</script>

This will work both IE8 and Chrome, Firefox, etc.

Removing index column in pandas when reading a csv

When reading to and from your CSV file include the argument index=False so for example:

 df.to_csv(filename, index=False)

and to read from the csv

df.read_csv(filename, index=False)  

This should prevent the issue so you don't need to fix it later.

Maven package/install without test (skip tests)

You can pass the maven.test.skip flag as a JVM argument, to skip running tests when the package phase (and the previous ones in the default lifecycle) is run:

mvn package -Dmaven.test.skip=true

You can also pass the skipTests flag alone to the mvn executable. If you want to include this information in your POM, you can create a new profile where you can configure the maven-surefire-plugin to skip tests.

How can the size of an input text box be defined in HTML?

The size attribute works, as well

<input size="25" type="text">

Using sudo with Python script

Please try module pexpect. Here is my code:

import pexpect
remove = pexpect.spawn('sudo dpkg --purge mytool.deb')
remove.logfile = open('log/expect-uninstall-deb.log', 'w')
remove.logfile.write('try to dpkg --purge mytool\n')
if remove.expect(['(?i)password.*']) == 0:
    # print "successfull"
    remove.sendline('mypassword')
    time.sleep(2)
    remove.expect(pexpect.EOF,5)
else:
    raise AssertionError("Fail to Uninstall deb package !")

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

What is the right way to POST multipart/form-data using curl?

The following syntax fixes it for you:

curl -v -F key1=value1 -F upload=@localfilename URL

Border length smaller than div width?

The border is given the whole html element. If you want half bottom border, you can wrap it with some other identifiable block like span.

HTML code:

<div> <span>content here </span></div>

CSS as below:

 div{
    width:200px;
    height:50px;   
    }
 span{
        width:100px;
        border-bottom:1px solid magenta;   
    } 

How to put a link on a button with bootstrap?

Combining the above answers i find a simply solution that probably will help you too:

<button type="submit" onclick="location.href = 'your_link';">Login</button>

by just adding inline JS code you can transform a button in a link and keeping his design.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

How to clear a textbox using javascript

use sth like

<input type="text" name="yourName" placeholder="A new value" />

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

setTimeout() function it's use to delay a process in JavaScript.

w3schools has an easy tutorial about this function.

Entity Framework rollback and remove bad migration

For those using EF Core with ASP.NET Core v1.0.0 I had a similar problem and used the following commands to correct it (@DavidSopko's post pointed me in the right direction, but the details are slightly different for EF Core):

Update-Database <Name of last good migration>
Remove-Migration

For example, in my current development the command became

PM> Update-Database CreateInitialDatabase
Done.
PM> Remove-Migration
Done.
PM> 

The Remove-Migration will remove the last migration you applied. If you have a more complex scenario with multiple migrations to remove (I only had 2, the initial and the bad one), I suggest you test the steps in a dummy project.

There doesn't currently appear to be a Get-Migrations command in EF Core (v1.0.0) so you must look in your migrations folder and be familiar with what you have done. However, there is a nice help command:

PM> get-help entityframework

Refreshing dastabase in VS2015 SQL Server Object Explorer, all of my data was preserved and the migration that I wanted to revert was gone :)

Initially I tried Remove-Migration by itself and found the error command confusing:

System.InvalidOperationException: The migration '...' has already been applied to the database. Unapply it and try again. If the migration has been applied to other databases, consider reverting its changes using a new migration.

There are already suggestions on improving this wording, but I'd like the error to say something like this:

Run Update-Database (last good migration name) to revert the database schema back to to that state. This command will unapply all migrations that occurred after the migration specified to Update-Database. You may then run Remove-Migration (migration name to remove)

Output from the EF Core help command follows:

 PM> get-help entityframework
                     _/\__
               ---==/    \\
         ___  ___   |.    \|\
        | __|| __|  |  )   \\\
        | _| | _|   \_/ |  //|\\
        |___||_|       /   \\\/\\

TOPIC
    about_EntityFrameworkCore

SHORT DESCRIPTION
    Provides information about Entity Framework Core commands.

LONG DESCRIPTION
    This topic describes the Entity Framework Core commands. See https://docs.efproject.net for information on Entity Framework Core.

    The following Entity Framework cmdlets are included.

        Cmdlet                      Description
        --------------------------  ---------------------------------------------------
        Add-Migration               Adds a new migration.

        Remove-Migration            Removes the last migration.

        Scaffold-DbContext          Scaffolds a DbContext and entity type classes for a specified database.

        Script-Migration            Generates a SQL script from migrations.

        Update-Database             Updates the database to a specified migration.

        Use-DbContext               Sets the default DbContext to use.

SEE ALSO
    Add-Migration
    Remove-Migration
    Scaffold-DbContext
    Script-Migration
    Update-Database
    Use-DbContext

how to check the jdk version used to compile a .class file

You're looking for this on the command line (for a class called MyClass):

On Unix/Linux:

javap -verbose MyClass | grep "major"

On Windows:

javap -verbose MyClass | findstr "major"

You want the major version from the results. Here are some example values:

  • Java 1.2 uses major version 46
  • Java 1.3 uses major version 47
  • Java 1.4 uses major version 48
  • Java 5 uses major version 49
  • Java 6 uses major version 50
  • Java 7 uses major version 51
  • Java 8 uses major version 52
  • Java 9 uses major version 53
  • Java 10 uses major version 54
  • Java 11 uses major version 55

Spring Data JPA - "No Property Found for Type" Exception

I had a similiar problem that caused me some hours of headache.

My repository method was:

public List<ResultClass> findAllByTypeAndObjects(String type, List<Object> objects);

I got the error, that the property type was not found for type ResultClass.

The solution was, that jpa/hibernate does not support plurals? Nevertheless, removing the 's' solved the problem:

public List<ResultClass> findAllByTypeAndObject(String type, List<Object>

Put content in HttpResponseMessage object?

No doubt that you are correct Florin. I was working on this project, and found that this piece of code:

product = await response.Content.ReadAsAsync<Product>();

Could be replaced with:

response.Content = new StringContent(string product);

Select row on click react-table

I am not familiar with, react-table, so I do not know it has direct support for selecting and deselecting (it would be nice if it had).

If it does not, with the piece of code you already have you can install the onCLick handler. Now instead of trying to attach style directly to row, you can modify state, by for instance adding selected: true to row data. That would trigger rerender. Now you only have to override how are rows with selected === true rendered. Something along lines of:

// Any Tr element will be green if its (row.age > 20) 
<ReactTable
  getTrProps={(state, rowInfo, column) => {
    return {
      style: {
        background: rowInfo.row.selected ? 'green' : 'red'
      }
    }
  }}
/>

Trigger change event of dropdown

Try this:

$('#id').change();

Works for me.

On one line together with setting the value: $('#id').val(16).change();

Decimal number regular expression, where digit after decimal is optional

Try this regex:

\d+\.?\d*

\d+ digits before optional decimal
.? optional decimal(optional due to the ? quantifier)
\d* optional digits after decimal

Iframe positioning

Try adding the css style property

position:relative;

to the div tag , it works ,

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Requires PHP5.3:

$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("l Y-m-d H:i:s\n");
}

This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod.

What is the difference between SessionState and ViewState?

Usage: If you're going to store information that you want to access on different web pages, you can use SessionState

If you want to store information that you want to access from the same page, then you can use Viewstate

Storage The Viewstate is stored within the page itself (in encrypted text), while the Sessionstate is stored in the server.

The SessionState will clear in the following conditions

  1. Cleared by programmer
  2. Cleared by user
  3. Timeout

Insert multiple values using INSERT INTO (SQL Server 2005)

In SQL Server 2008,2012,2014 you can insert multiple rows using a single SQL INSERT statement.

 INSERT INTO TableName ( Column1, Column2 ) VALUES
    ( Value1, Value2 ), ( Value1, Value2 )

Another way

INSERT INTO TableName (Column1, Column2 )
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2
UNION ALL
SELECT Value1 ,Value2

How do I convert a String to an int in Java?

This is a complete program with all conditions positive and negative without using a library

import java.util.Scanner;


public class StringToInt {

    public static void main(String args[]) {
        String inputString;
        Scanner s = new Scanner(System.in);
        inputString = s.nextLine();

        if (!inputString.matches("([+-]?([0-9]*[.])?[0-9]+)")) {
            System.out.println("Not a Number");
        }
        else {
            Double result2 = getNumber(inputString);
            System.out.println("result = " + result2);
        }
    }


    public static Double getNumber(String number) {
        Double result = 0.0;
        Double beforeDecimal = 0.0;
        Double afterDecimal = 0.0;
        Double afterDecimalCount = 0.0;
        int signBit = 1;
        boolean flag = false;

        int count = number.length();
        if (number.charAt(0) == '-') {
            signBit = -1;
            flag = true;
        }
        else if (number.charAt(0) == '+') {
            flag = true;
        }
        for (int i = 0; i < count; i++) {
            if (flag && i == 0) {
                continue;
            }
            if (afterDecimalCount == 0.0) {
                if (number.charAt(i) - '.' == 0) {
                    afterDecimalCount++;
                }
                else {
                    beforeDecimal = beforeDecimal * 10 + (number.charAt(i) - '0');
                }
            }
            else {
                afterDecimal = afterDecimal * 10 + number.charAt(i) - ('0');
                afterDecimalCount = afterDecimalCount * 10;
            }
        }
        if (afterDecimalCount != 0.0) {
            afterDecimal = afterDecimal / afterDecimalCount;
            result = beforeDecimal + afterDecimal;
        }
        else {
            result = beforeDecimal;
        }
        return result * signBit;
    }
}

Best way to format integer as string with leading zeros?

Python 3.6 f-strings allows us to add leading zeros easily:

number = 5
print(f' now we have leading zeros in {number:02d}')

Have a look at this good post about this feature.

Count the number of occurrences of a string in a VARCHAR field?

In SQL SERVER, this is the answer

Declare @t table(TITLE VARCHAR(100), DESCRIPTION VARCHAR(100))

INSERT INTO @t SELECT 'test1', 'value blah blah value' 
INSERT INTO @t SELECT 'test2','value test' 
INSERT INTO @t SELECT 'test3','test test test' 
INSERT INTO @t SELECT 'test4','valuevaluevaluevaluevalue' 


SELECT TITLE,DESCRIPTION,Count = (LEN(DESCRIPTION) - LEN(REPLACE(DESCRIPTION, 'value', '')))/LEN('value') 

FROM @t

Result

TITLE   DESCRIPTION               Count
test1   value blah blah value        2
test2   value test                   1
test3   test test test               0
test4   valuevaluevaluevaluevalue    5

I don't have MySQL install, but goggled to find the Equivalent of LEN is LENGTH while REPLACE is same.

So the equivalent query in MySql should be

SELECT TITLE,DESCRIPTION, (LENGTH(DESCRIPTION) - LENGTH(REPLACE(DESCRIPTION, 'value', '')))/LENGTH('value') AS Count
FROM <yourTable>

Please let me know if it worked for you in MySql also.

Make a Bash alias that takes a parameter?

NB: In case the idea isn't obvious, it is a bad idea to use aliases for anything but aliases, the first one being the 'function in an alias' and the second one being the 'hard to read redirect/source'. Also, there are flaws (which i thought would be obvious, but just in case you are confused: I do not mean them to actually be used... anywhere!)

................................................................................................................................................

I've answered this before, and it has always been like this in the past:

alias foo='__foo() { unset -f $0; echo "arg1 for foo=$1"; }; __foo()'

which is fine and good, unless you are avoiding the use of functions all together. in which case you can take advantage of bash's vast ability to redirect text:

alias bar='cat <<< '\''echo arg1 for bar=$1'\'' | source /dev/stdin'

They are both about the same length give or take a few characters.

The real kicker is the time difference, the top being the 'function method' and the bottom being the 'redirect-source' method. To prove this theory, the timing speaks for itself:

arg1 for foo=FOOVALUE
 real 0m0.011s user 0m0.004s sys 0m0.008s  # <--time spent in foo
 real 0m0.000s user 0m0.000s sys 0m0.000s  # <--time spent in bar
arg1 for bar=BARVALUE
ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
 real 0m0.010s user 0m0.004s sys 0m0.004s
 real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE
ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
 real 0m0.011s user 0m0.000s sys 0m0.012s
 real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE
ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
 real 0m0.012s user 0m0.004s sys 0m0.004s
 real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE
ubuntu@localhost /usr/bin# time foo FOOVALUE; time bar BARVALUE
arg1 for foo=FOOVALUE
 real 0m0.010s user 0m0.008s sys 0m0.004s
 real 0m0.000s user 0m0.000s sys 0m0.000s
arg1 for bar=BARVALUE

This is the bottom part of about 200 results, done at random intervals. It seems that function creation/destruction takes more time than redirection. Hopefully this will help future visitors to this question (didn't want to keep it to myself).

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Conversion failed when converting the nvarchar value ... to data type int

You got this Error because you tried to convert column DataType from String to int which is

leagal if and only if

you dont have row in that table with string content inside that column

so just make sure your previously inserted Rows is compatible with the new changes

jQuery get value of selected radio button

HTML Markup :

<div class="form-group">
  <input id="rdMale" type="radio" class="clsGender" value="Male" name="rdGender" /> Male
  <input id="rdFemale" type="radio" class="clsGender" value="Female" name="rdGender" /> Female
 </div>

Get selected value by radio button Id:

 $("input[name='rdGender']").click(function () {
     alert($("#rdMale").val());
});

Get value by radiobutton Classname

 $(".clsGender").click(function () {
       alert($(this).val());
            //or
      alert($(".clsGender:checked").val());
   });

Get value by name

   $("input[name='rdGender']").click(function () {
          var rdVaule = $("input[name='rdGender']:checked").val();
          alert(rdVaule);
   });

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

The solution no one tells is that in Mysql v5.5 and later InnoDB is the default storage engine which does not have this problem but in many cases like mine there are some old mysql ini configuration files which are using old MYISAM storage engine like below.

default-storage-engine=MYISAM

which is creating all these problems and the solution is to change default-storage-engine to InnoDB in the Mysql's ini configuration file once and for all instead of doing temporary hacks.

default-storage-engine=InnoDB

And if you are on MySql v5.5 or later then InnoDB is the default engine so you do not need to set it explicitly like above, just remove the default-storage-engine=MYISAM if it exist from your ini file and you are good to go.

Creating a button in Android Toolbar

ToolBar with Button Tutorial

1 - Add library compatibility inside build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
}

2 - Create a file name color.xml to define the Toolbar colors

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="ColorPrimary">#FF5722</color>
    <color name="ColorPrimaryDark">#E64A19</color>
</resources>

3 - Modify your style.xml file

<resources>     
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="colorPrimary">@color/ColorPrimary</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <!-- Customize your theme here. -->
    </style>     
</resources>

4 - Create a xml file like tool_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
 xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/colorPrimary"
    android:elevation="4dp" />

5 - Include the Toolbar into your main_activity.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar" />

    <TextView
        android:layout_below="@+id/tool_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/TextDimTop"
        android:text="@string/hello_world" />

</RelativeLayout>

6 - Then, put it inside your MainActivity class

package com.example.hp1.materialtoolbar;

import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

/* When using AppCompat support library                                                             
 * (you need to extend Main Activity to                                                            
 * ActionBarActivity)
 * ActionBarActivity has deprecated, use AppCompatActivity
 */
public class MainActivity extends ActionBarActivity { 
    // Declaring the Toolbar Object
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        // Attaching the layout to the toolbar object
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        // Setting toolbar as the ActionBar with setSupportActionBar() call
        setSupportActionBar(toolbar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

7 - And finally, add your "Button Items" to the menu_main.xml inside of /res/menu/ directory

<?xml version="1.0" encoding="utf-8"?>
   <menu
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        tools:context=".MainActivity">
        <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:title="@string/action_settings"
            app:showAsAction="never" />
        <item
            android:id="@+id/action_search"
            android:orderInCategory="200"
            android:title="Search"
            android:icon="@drawable/ic_search"
            app:showAsAction="ifRoom"/>                
        <item
            android:id="@+id/action_user"
            android:orderInCategory="300"
            android:title="User"
            android:icon="@drawable/ic_user"
            app:showAsAction="ifRoom" />        
    </menu>

Deleting an object in C++

Just an update of James' answer.

Isn't this the normal way to free the memory associated with an object?

Yes. It is the normal way to free memory. But new/delete operator always leads to memory leak problem.

Since c++17 already removed auto_ptr auto_ptr. I suggest shared_ptr or unique_ptr to handle the memory problems.

void test()
{
    std::shared_ptr<Object1> obj1(new Object1);

} // The object is automatically deleted when the scope ends or reference counting reduces to 0.
  • The reason for removing auto_ptr is that auto_ptr is not stable in case of coping semantics
  • If you are sure about no coping happening during the scope, a unique_ptr is suggested.
  • If there is a circular reference between the pointers, I suggest having a look at weak_ptr.

How can I embed a YouTube video on GitHub wiki pages?

Complete Example

Expanding on @MGA's Answer

While it's not possible to embed a video in Markdown you can "fake it" by including a valid linked image in your markup file, using this format:

[![IMAGE ALT TEXT](http://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](http://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE "Video Title")

Explanation of the Markdown

If this markup snippet looks complicated, break it down into two parts:

an image
![image alt text](https://example.com/link-to-image)
wrapped in a link
[link text](https://example.com/my-link "link title")

Example using Valid Markdown and YouTube Thumbnail:

Everything Is AWESOME

We are sourcing the thumbnail image directly from YouTube and linking to the actual video, so when the person clicks the image/thumbnail they will be taken to the video.

Code:

[![Everything Is AWESOME](https://img.youtube.com/vi/StTqXEQ2l-Y/0.jpg)](https://www.youtube.com/watch?v=StTqXEQ2l-Y "Everything Is AWESOME")

OR If you want to give readers a visual cue that the image/thumbnail is actually a playable video, take your own screenshot of the video in YouTube and use that as the thumbnail instead.

Example using Screenshot with Video Controls as Visual Cue:

Everything Is AWESOME

Code:

[![Everything Is AWESOME](http://i.imgur.com/Ot5DWAW.png)](https://youtu.be/StTqXEQ2l-Y?t=35s "Everything Is AWESOME")

 Clear Advantages

While this requires a couple of extra steps (a) taking the screenshot of the video and (b) uploading it so you can use the image as your thumbnail it does have 3 clear advantages:

  1. The person reading your markdown (or resulting html page) has a visual cue telling them they can watch the video (video controls encourage clicking)
  2. You can chose a specific frame in the video to use as the thumbnail (thus making your content more engaging)
  3. You can link to a specific time in the video from which play will start when the linked-image is clicked. (in our case from 35 seconds)

Taking and uploading a screenshot takes a few seconds but has a big payoff.

Works Everywhere!

Since this is standard markdown, it works everywhere. try it on GitHub, Reddit, Ghost, and here on Stack Overflow.

Vimeo

This approach also works with Vimeo videos

Example

Little red riding hood

Code

[![Little red riding hood](http://i.imgur.com/7YTMFQp.png)](https://vimeo.com/3514904 "Little red riding hood - Click to Watch!")

Notes:

Meaning of delta or epsilon argument of assertEquals for double values

Note that if you're not doing math, there's nothing wrong with asserting exact floating point values. For instance:

public interface Foo {
    double getDefaultValue();
}

public class FooImpl implements Foo {
    public double getDefaultValue() { return Double.MIN_VALUE; }
}

In this case, you want to make sure it's really MIN_VALUE, not zero or -MIN_VALUE or MIN_NORMAL or some other very small value. You can say

double defaultValue = new FooImpl().getDefaultValue();
assertEquals(Double.MIN_VALUE, defaultValue);

but this will get you a deprecation warning. To avoid that, you can call assertEquals(Object, Object) instead:

// really you just need one cast because of autoboxing, but let's be clear
assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);

And, if you really want to look clever:

assertEquals(
    Double.doubleToLongBits(Double.MIN_VALUE), 
    Double.doubleToLongBits(defaultValue)
);

Or you can just use Hamcrest fluent-style assertions:

// equivalent to assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);
assertThat(defaultValue, is(Double.MIN_VALUE));

If the value you're checking does come from doing some math, though, use the epsilon.

How to easily map c++ enums to strings

in the header:

enum EFooOptions
 {
FooOptionsA = 0, EFooOptionsMin = 0,
FooOptionsB,
FooOptionsC,
FooOptionsD 
EFooOptionsMax
};
extern const wchar* FOO_OPTIONS[EFooOptionsMax];

in the .cpp file:

const wchar* FOO_OPTIONS[] = {
    L"One",
    L"Two",
    L"Three",
    L"Four"
};

Caveat: Don't handle bad array index. :) But you can easily add a function to verify the enum before getting the string from the array.

How to write both h1 and h2 in the same line?

In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.

<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>

Will give you:

What the...heck is going on?

and not

What the... 
heck is going on?

How to define a relative path in java

Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:

resources/wsdl/WebServiceFile.wsdl

To get the path from some method to this file you can do the following:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();

Force IE compatibility mode off using tags

The meta tag solution wasn't working for us but setting it in the response header did:

header('X-UA-Compatible: IE=edge,chrome=1');

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

How to print React component on click of a button?

Just sharing what worked in my case as someone else might find it useful. I have a modal and just wanted to print the body of the modal which could be several pages on paper.

Other solutions I tried just printed one page and only what was on screen. Emil's accepted solution worked for me:

https://stackoverflow.com/a/30137174/3123109

This is what the component ended up looking like. It prints everything in the body of the modal.

import React, { Component } from 'react';
import {
    Button,
    Modal,
    ModalBody,
    ModalHeader
} from 'reactstrap';

export default class TestPrint extends Component{
    constructor(props) {
        super(props);
        this.state = {
            modal: false,
            data: [
                'test', 'test', 'test', 'test', 'test', 'test', 
                'test', 'test', 'test', 'test', 'test', 'test', 
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test',
                'test', 'test', 'test', 'test', 'test', 'test'            
            ]
        }
        this.toggle = this.toggle.bind(this);
        this.print = this.print.bind(this);
    }

    print() {
        var content = document.getElementById('printarea');
        var pri = document.getElementById('ifmcontentstoprint').contentWindow;
        pri.document.open();
        pri.document.write(content.innerHTML);
        pri.document.close();
        pri.focus();
        pri.print();
    }

    renderContent() {
        var i = 0;
        return this.state.data.map((d) => {
            return (<p key={d + i++}>{i} - {d}</p>)
        });
    }

    toggle() {
        this.setState({
            modal: !this.state.modal
        })
    }

    render() {
        return (
            <div>
                <Button 
                    style={
                        {
                            'position': 'fixed',
                            'top': '50%',
                            'left': '50%',
                            'transform': 'translate(-50%, -50%)'
                        }
                    } 
                    onClick={this.toggle}
                >
                    Test Modal and Print
                </Button>         
                <Modal 
                    size='lg' 
                    isOpen={this.state.modal} 
                    toggle={this.toggle} 
                    className='results-modal'
                >  
                    <ModalHeader toggle={this.toggle}>
                        Test Printing
                    </ModalHeader>
                    <iframe id="ifmcontentstoprint" style={{
                        height: '0px',
                        width: '0px',
                        position: 'absolute'
                    }}></iframe>      
                    <Button onClick={this.print}>Print</Button>
                    <ModalBody id='printarea'>              
                        {this.renderContent()}
                    </ModalBody>
                </Modal>
            </div>
        )
    }
}

Note: However, I am having difficulty getting styles to be reflected in the iframe.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

Here's a proof by induction, considering N terms, but it's the same for N - 1:

For N = 0 the formula is obviously true.

Suppose 1 + 2 + 3 + ... + N = N(N + 1) / 2 is true for some natural N.

We'll prove 1 + 2 + 3 + ... + N + (N + 1) = (N + 1)(N + 2) / 2 is also true by using our previous assumption:

1 + 2 + 3 + ... + N + (N + 1) = (N(N + 1) / 2) + (N + 1) = (N + 1)((N / 2) + 1) = (N + 1)(N + 2) / 2.

So the formula holds for all N.

Getting Git to work with a proxy server - fails with "Request timed out"

For the git protocol (git://...), install socat and write a script such as:

#!/bin/sh

exec socat - socks4:your.company.com:$1:$2

make it executable, put it in your path, and in your ~/.gitconfig set core.gitproxy to the name of that script.

How do I prevent Conda from activating the base environment by default?

There're 3 ways to achieve this after conda 4.6. (The last method has the highest priority.)

  1. Use sub-command conda config to change the setting.

    conda config --set auto_activate_base false
    
  2. In fact, the former conda config sub-command is changing configuration file .condarc. We can modify .condarc directly. Add following content into .condarc under your home directory,

    # auto_activate_base (bool)
    #   Automatically activate the base environment during shell
    #   initialization. for `conda init`
    auto_activate_base: false
    
  3. Set environment variable CONDA_AUTO_ACTIVATE_BASE in the shell's init file. (.bashrc for bash, .zshrc for zsh)

    CONDA_AUTO_ACTIVATE_BASE=false
    

    To convert from the condarc file-based configuration parameter name to the environment variable parameter name, make the name all uppercase and prepend CONDA_. For example, conda’s always_yes configuration parameter can be specified using a CONDA_ALWAYS_YES environment variable.

    The environment settings take precedence over corresponding settings in .condarc file.

References

How can I plot with 2 different y-axes?

I too suggests, twoord.stackplot() in the plotrix package plots with more of two ordinate axes.

data<-read.table(text=
"e0AL fxAL e0CO fxCO e0BR fxBR anos
 51.8  5.9 50.6  6.8 51.0  6.2 1955
 54.7  5.9 55.2  6.8 53.5  6.2 1960
 57.1  6.0 57.9  6.8 55.9  6.2 1965
 59.1  5.6 60.1  6.2 57.9  5.4 1970
 61.2  5.1 61.8  5.0 59.8  4.7 1975
 63.4  4.5 64.0  4.3 61.8  4.3 1980
 65.4  3.9 66.9  3.7 63.5  3.8 1985
 67.3  3.4 68.0  3.2 65.5  3.1 1990
 69.1  3.0 68.7  3.0 67.5  2.6 1995
 70.9  2.8 70.3  2.8 69.5  2.5 2000
 72.4  2.5 71.7  2.6 71.1  2.3 2005
 73.3  2.3 72.9  2.5 72.1  1.9 2010
 74.3  2.2 73.8  2.4 73.2  1.8 2015
 75.2  2.0 74.6  2.3 74.2  1.7 2020
 76.0  2.0 75.4  2.2 75.2  1.6 2025
 76.8  1.9 76.2  2.1 76.1  1.6 2030
 77.6  1.9 76.9  2.1 77.1  1.6 2035
 78.4  1.9 77.6  2.0 77.9  1.7 2040
 79.1  1.8 78.3  1.9 78.7  1.7 2045
 79.8  1.8 79.0  1.9 79.5  1.7 2050
 80.5  1.8 79.7  1.9 80.3  1.7 2055
 81.1  1.8 80.3  1.8 80.9  1.8 2060
 81.7  1.8 80.9  1.8 81.6  1.8 2065
 82.3  1.8 81.4  1.8 82.2  1.8 2070
 82.8  1.8 82.0  1.7 82.8  1.8 2075
 83.3  1.8 82.5  1.7 83.4  1.9 2080
 83.8  1.8 83.0  1.7 83.9  1.9 2085
 84.3  1.9 83.5  1.8 84.4  1.9 2090
 84.7  1.9 83.9  1.8 84.9  1.9 2095
 85.1  1.9 84.3  1.8 85.4  1.9 2100", header=T)

require(plotrix)
twoord.stackplot(lx=data$anos, rx=data$anos, 
                 ldata=cbind(data$e0AL, data$e0BR, data$e0CO),
                 rdata=cbind(data$fxAL, data$fxBR, data$fxCO),
                 lcol=c("black","red", "blue"),
                 rcol=c("black","red", "blue"), 
                 ltype=c("l","o","b"),
                 rtype=c("l","o","b"), 
                 lylab="Años de Vida", rylab="Hijos x Mujer", 
                 xlab="Tiempo",
                 main="Mortalidad/Fecundidad:1950–2100",
                 border="grey80")
legend("bottomright", c(paste("Proy:", 
                      c("A. Latina", "Brasil", "Colombia"))), cex=1,
        col=c("black","red", "blue"), lwd=2, bty="n",  
        lty=c(1,1,2), pch=c(NA,1,1) )

convert double to int

The best way is to simply use Convert.ToInt32. It is fast and also rounds correctly.

Why make it more complicated?

Using sed to mass rename files

First, I should say that the easiest way to do this is to use the prename or rename commands.

On Ubuntu, OSX (Homebrew package rename, MacPorts package p5-file-rename), or other systems with perl rename (prename):

rename s/0000/000/ F0000*

or on systems with rename from util-linux-ng, such as RHEL:

rename 0000 000 F0000*

That's a lot more understandable than the equivalent sed command.

But as for understanding the sed command, the sed manpage is helpful. If you run man sed and search for & (using the / command to search), you'll find it's a special character in s/foo/bar/ replacements.

  s/regexp/replacement/
         Attempt  to match regexp against the pattern space.  If success-
         ful,  replace  that  portion  matched  with  replacement.    The
         replacement may contain the special character & to refer to that
         portion of the pattern space  which  matched,  and  the  special
         escapes  \1  through  \9  to refer to the corresponding matching
         sub-expressions in the regexp.

Therefore, \(.\) matches the first character, which can be referenced by \1. Then . matches the next character, which is always 0. Then \(.*\) matches the rest of the filename, which can be referenced by \2.

The replacement string puts it all together using & (the original filename) and \1\2 which is every part of the filename except the 2nd character, which was a 0.

This is a pretty cryptic way to do this, IMHO. If for some reason the rename command was not available and you wanted to use sed to do the rename (or perhaps you were doing something too complex for rename?), being more explicit in your regex would make it much more readable. Perhaps something like:

ls F00001-0708-*|sed 's/F0000\(.*\)/mv & F000\1/' | sh

Being able to see what's actually changing in the s/search/replacement/ makes it much more readable. Also it won't keep sucking characters out of your filename if you accidentally run it twice or something.

Java system properties and environment variables

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

How to prune local tracking branches that do not exist on remote anymore

Windows Solution

For Microsoft Windows Powershell:

git checkout master; git remote update origin --prune; git branch -vv | Select-String -Pattern ": gone]" | % { $_.toString().Trim().Split(" ")[0]} | % {git branch -d $_}

Explaination

git checkout master switches to the master branch

git remote update origin --prune prunes remote branches

git branch -vv gets a verbose output of all branches (git reference)

Select-String -Pattern ": gone]" gets only the records where they have been removed from remote.

% { $_.toString().Split(" ")[0]} get the branch name

% {git branch -d $_} deletes the branch

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

Change background color of iframe issue

just building on what Chetabahana wrote, I found that adding a short delay to the JS function helped on a site I was working on. It meant that the function kicked in after the iframe loaded. You can play around with the delay.

var delayInMilliseconds = 500; // half a second

setTimeout(function() { 

   var iframe = document.getElementsByTagName('iframe')[0];
   iframe.style.background = 'white';
   iframe.contentWindow.document.body.style.backgroundColor = 'white';

}, delayInMilliseconds);

I hope this helps!

SQL Server Regular expressions in T-SQL

How about the PATINDEX function?

The pattern matching in TSQL is not a complete regex library, but it gives you the basics.

(From Books Online)

Wildcard  Meaning  
% Any string of zero or more characters.

_ Any single character.

[ ] Any single character within the specified range 
    (for example, [a-f]) or set (for example, [abcdef]).

[^] Any single character not within the specified range 
    (for example, [^a - f]) or set (for example, [^abcdef]).

Check synchronously if file/directory exists in Node.js

Some answers here says that fs.exists and fs.existsSync are both deprecated. According to the docs this is no more true. Only fs.exists is deprected now:

Note that fs.exists() is deprecated, but fs.existsSync() is not. (The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.)

So you can safely use fs.existsSync() to synchronously check if a file exists.

INNER JOIN vs INNER JOIN (SELECT . FROM)

You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.

My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries. Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID WHERE p.isactive = 1

The better version of this query is :

SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1

(Assuming isactive is a field in product table which represents the active/inactive products).

How to push a docker image to a private repository

Following are the steps to push Docker Image to Private Repository of DockerHub

1- First check Docker Images using command

docker images

2- Check Docker Tag command Help

docker tag help

3- Now Tag a name to your created Image

docker tag localImgName:tagName DockerHubUser\Private-repoName:tagName(tag name is optional. Default name is latest)

4- Before pushing Image to DockerHub Private Repo, first login to DockerHub using command

docker login [provide dockerHub username and Password to login]

5- Now push Docker Image to your private Repo using command

docker push [options] ImgName[:tag] e.g docker push DockerHubUser\Private-repoName:tagName

6- Now navigate to the DockerHub Private Repo and you will see Docker image is pushed on your private Repository with name written as TagName in previous steps

SyntaxError: Cannot use import statement outside a module

Recently have the issue. The fix which work for me was to added this to babel.config.json in the plugins section

["@babel/plugin-transform-modules-commonjs", {
    "allowTopLevelThis": true,
    "loose": true,
    "lazy": true
  }],

I had some imported module with // and the error "cannot use import outside a module".

Private vs Protected - Visibility Good-Practice Concern

I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.

  1. Make all classes final unless you need to subclass them right away.
  2. Make all methods final unless you need to subclass and override them right away.
  3. Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.

Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.

If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.

Disclaimer: I don't program much in Java :)

Send JSON data with jQuery

I wrote a short convenience function for posting JSON.

$.postJSON = function(url, data, success, args) {
  args = $.extend({
    url: url,
    type: 'POST',
    data: JSON.stringify(data),
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    success: success
  }, args);
  return $.ajax(args);
};

$.postJSON('test/url', data, function(result) {
  console.log('result', result);
});

Getting started with Haskell

These are my favorite

Haskell: Functional Programming with Types

Joeri van Eekelen, et al. | Wikibooks
       Published in 2012, 597 pages

Real World Haskell

   B. O'Sullivan, J. Goerzen, D. Stewart | OReilly Media, Inc.
   Published in 2008, 710 pages

How to bring an activity to foreground (top of stack)?

if you are using the "Google Cloud Message" to receive push notifications with "PendingIntent" class, the following code displays the notification in the action bar only.

Clicking the notification no activity will be created, the last active activity is restored retaining current state without problems.

Intent notificationIntent = new Intent(this, ActBase.class); **notificationIntent.setAction(Intent.ACTION_MAIN); notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);** PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_launcher) .setContentTitle("Localtaxi") .setVibrate(vibrate) .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) .setAutoCancel(true) .setOnlyAlertOnce(true) .setContentText(msg);

mBuilder.setContentIntent(contentIntent);

NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

Ciao!

Postgres: SQL to list table foreign keys

This query works correct with composite keys also:

select c.constraint_name
    , x.table_schema as schema_name
    , x.table_name
    , x.column_name
    , y.table_schema as foreign_schema_name
    , y.table_name as foreign_table_name
    , y.column_name as foreign_column_name
from information_schema.referential_constraints c
join information_schema.key_column_usage x
    on x.constraint_name = c.constraint_name
join information_schema.key_column_usage y
    on y.ordinal_position = x.position_in_unique_constraint
    and y.constraint_name = c.unique_constraint_name
order by c.constraint_name, x.ordinal_position

How do I increase modal width in Angular UI Bootstrap?

You can do this in very simple way using size property of angular modal.

var modal = $modal.open({
                    templateUrl: "/partials/welcome",
                    controller: "welcomeCtrl",
                    backdrop: "static",
                    scope: $scope,
                    size:'lg' // you can try different width like 'sm', 'md'
                });

Get value from input (AngularJS)

If you want to get values in Javascript on frontend, you can use the native way to do it by using :

document.getElementsByName("movie")[0].value;

Where "movie" is the name of your input <input type="text" name="movie">

If you want to get it on angular.js controller, you can use;

$scope.movie

SecurityException during executing jnlp file (Missing required Permissions manifest attribute in main jar)

JAR File Manifest Attributes for Security

The JAR file manifest contains information about the contents of the JAR file, including security and configuration information.

Add the attributes to the manifest before the JAR file is signed.
See Modifying a Manifest File in the Java Tutorial for information on adding attributes to the JAR manifest file.

Permissions Attribute

The Permissions attribute is used to verify that the permissions level requested by the RIA when it runs matches the permissions level that was set when the JAR file was created.

Use this attribute to help prevent someone from re-deploying an application that is signed with your certificate and running it at a different privilege level. Set this attribute to one of the following values:

  • sandbox - runs in the security sandbox and does not require additional permissions.

  • all-permissions - requires access to the user's system resources.

Changes to Security Slider:

The following changes to Security Slider were included in this release(7u51):

  • Block Self-Signed and Unsigned applets on High Security Setting
  • Require Permissions Attribute for High Security Setting
  • Warn users of missing Permissions Attributes for Medium Security Setting

For more information, see Java Control Panel documentation.

enter image description here

sample MANIFEST.MF

Manifest-Version: 1.0
Ant-Version: Apache Ant 1.8.3
Created-By: 1.7.0_51-b13 (Oracle Corporation)
Trusted-Only: true
Class-Path: lib/plugin.jar
Permissions: sandbox
Codebase: http://myweb.de http://www.myweb.de
Application-Name: summary-applet

Oracle - Insert New Row with Auto Incremental ID

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

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

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

HTML - Arabic Support

This is the answer that was required but everybody answered only part one of many.

  • Step 1 - You cannot have the multilingual characters in unicode document.. convert the document to UTF-8 document

advanced editors don't make it simple for you... go low level...
use notepad to save the document as meName.html & change the encoding
type to UTF-8

  • Step 2 - Mention in your html page that you are going to use such characters by

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    
  • Step 3 - When you put in some characters make sure your container tags have the following 2 properties set

    dir='rtl'
    lang='ar'
    
  • Step 4 - Get the characters from some specific tool\editor or online editor like i did with Arabic-Keyboard.org

example

<p dir="rtl" lang="ar" style="color:#e0e0e0;font-size:20px;">????? ??????? ??????</p>

NOTE: font type, font family, font face setting will have no effect on special characters

Get sum of MySQL column in PHP

$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);

$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
    $qty += $num['ColumnName'];
}
echo $qty;

Get url without querystring

var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();

Repository access denied. access via a deployment key is read-only

All you need - add another key and use it.

As i've found first key - always Deployment Key.

How to access component methods from “outside” in ReactJS?

As mentioned in some of the comments, ReactDOM.render no longer returns the component instance. You can pass a ref callback in when rendering the root of the component to get the instance, like so:

// React code (jsx)
function MyWidget(el, refCb) {
    ReactDOM.render(<MyComponent ref={refCb} />, el);
}
export default MyWidget;

and:

// vanilla javascript code
var global_widget_instance;

MyApp.MyWidget(document.getElementById('my_container'), function(widget) {
    global_widget_instance = widget;
});

global_widget_instance.myCoolMethod();

What's the correct way to communicate between controllers in AngularJS?

You can do it by using angular events that is $emit and $broadcast. As per our knowledge this is the best, efficient and effective way.

First we call a function from one controller.

var myApp = angular.module('sample', []);
myApp.controller('firstCtrl', function($scope) {
    $scope.sum = function() {
        $scope.$emit('sumTwoNumber', [1, 2]);
    };
});
myApp.controller('secondCtrl', function($scope) {
    $scope.$on('sumTwoNumber', function(e, data) {
        var sum = 0;
        for (var a = 0; a < data.length; a++) {
            sum = sum + data[a];
        }
        console.log('event working', sum);

    });
});

You can also use $rootScope in place of $scope. Use your controller accordingly.

oracle plsql: how to parse XML and insert into table

select *  
FROM XMLTABLE('/person/row'  
         PASSING   
            xmltype('
                <person>
                   <row>
                       <name>Tom</name>
                       <Address>
                           <State>California</State>
                           <City>Los angeles</City>
                       </Address>
                   </row>
                   <row>
                       <name>Jim</name>
                       <Address>
                           <State>California</State>
                           <City>Los angeles</City>
                       </Address>
                   </row>
                </person>
            ')
         COLUMNS  
            --describe columns and path to them:  
            name  varchar2(20)    PATH './name',  
            state varchar2(20)    PATH './Address/State',  
            city  varchar2(20)    PATH './Address/City'
     ) xmlt  
;  

Iterate through every file in one directory

To skip . & .., you can use Dir::each_child.

Dir.each_child('/path/to/dir') do |filename|
  puts filename
end

Dir::children returns an array of the filenames.

Sorting int array in descending order

If it's not a big/long array just mirror it:

for( int i = 0; i < arr.length/2; ++i ) 
{ 
  temp = arr[i]; 
  arr[i] = arr[arr.length - i - 1]; 
  arr[arr.length - i - 1] = temp; 
}

How can I safely create a nested directory?

On Python = 3.5, use pathlib.Path.mkdir:

from pathlib import Path
Path("/my/directory").mkdir(parents=True, exist_ok=True)

For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:

Try os.path.exists, and consider os.makedirs for the creation.

import os
if not os.path.exists(directory):
    os.makedirs(directory)

As noted in comments and elsewhere, there's a race condition – if the directory is created between the os.path.exists and the os.makedirs calls, the os.makedirs will fail with an OSError. Unfortunately, blanket-catching OSError and continuing is not foolproof, as it will ignore a failure to create the directory due to other factors, such as insufficient permissions, full disk, etc.

One option would be to trap the OSError and examine the embedded error code (see Is there a cross-platform way of getting information from Python’s OSError):

import os, errno

try:
    os.makedirs(directory)
except OSError as e:
    if e.errno != errno.EEXIST:
        raise

Alternatively, there could be a second os.path.exists, but suppose another created the directory after the first check, then removed it before the second one – we could still be fooled.

Depending on the application, the danger of concurrent operations may be more or less than the danger posed by other factors such as file permissions. The developer would have to know more about the particular application being developed and its expected environment before choosing an implementation.

Modern versions of Python improve this code quite a bit, both by exposing FileExistsError (in 3.3+)...

try:
    os.makedirs("path/to/directory")
except FileExistsError:
    # directory already exists
    pass

...and by allowing a keyword argument to os.makedirs called exist_ok (in 3.2+).

os.makedirs("path/to/directory", exist_ok=True)  # succeeds even if directory exists.

Easiest way to open a download window without navigating away from the page

I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.

Removing input background colour for Chrome autocomplete?

As mentioned before, inset -webkit-box-shadow for me works best.

/* Code witch overwrites input background-color */
input:-webkit-autofill {
     -webkit-box-shadow: 0 0 0px 1000px #fbfbfb inset;
}

Also code snippet to change text color:

input:-webkit-autofill:first-line {
     color: #797979;
}

get all characters to right of last dash

string atest = "9586-202-10072";
int indexOfHyphen = atest.LastIndexOf("-");

if (indexOfHyphen >= 0)
{
    string contentAfterLastHyphen = atest.Substring(indexOfHyphen + 1);
    Console.WriteLine(contentAfterLastHyphen );
}

How to detect if javascript files are loaded?

Further to @T.J. Crowder 's answer, I've added a recursive outer loop that allows one to iterate through all the scripts in an array and then execute a function once all the scripts are loaded:

loadList([array of scripts], 0, function(){// do your post-scriptload stuff})

function loadList(list, i, callback)
{
    {
        loadScript(list[i], function()
        {
            if(i < list.length-1)
            {
                loadList(list, i+1, callback);  
            }
            else
            {
                callback();
            }
        })
    }
}

Of course you can make a wrapper to get rid of the '0' if you like:

function prettyLoadList(list, callback)
{
    loadList(list, 0, callback);
}

Nice work @T.J. Crowder - I was cringing at the 'just add a couple seconds delay before running the callback' I saw in other threads.

Why does python use 'else' after for and while loops?

I agree, it's more like an 'elif not [condition(s) raising break]'.

I know this is an old thread, but I am looking into the same question right now, and I'm not sure anyone has captured the answer to this question in the way I understand it.

For me, there are three ways of "reading" the else in For... else or While... else statements, all of which are equivalent, are:

  1. else == if the loop completes normally (without a break or error)
  2. else == if the loop does not encounter a break
  3. else == else not (condition raising break) (presumably there is such a condition, or you wouldn't have a loop)

So, essentially, the "else" in a loop is really an "elif ..." where '...' is (1) no break, which is equivalent to (2) NOT [condition(s) raising break].

I think the key is that the else is pointless without the 'break', so a for...else includes:

for:
    do stuff
    conditional break # implied by else
else not break:
    do more stuff

So, essential elements of a for...else loop are as follows, and you would read them in plainer English as:

for:
    do stuff
    condition:
        break
else: # read as "else not break" or "else not condition"
    do more stuff

As the other posters have said, a break is generally raised when you are able to locate what your loop is looking for, so the else: becomes "what to do if target item not located".

Example

You can also use exception handling, breaks, and for loops all together.

for x in range(0,3):
    print("x: {}".format(x))
    if x == 2:
        try:
            raise AssertionError("ASSERTION ERROR: x is {}".format(x))
        except:
            print(AssertionError("ASSERTION ERROR: x is {}".format(x)))
            break
else:
    print("X loop complete without error")

Result

x: 0
x: 1
x: 2
ASSERTION ERROR: x is 2
----------
# loop not completed (hit break), so else didn't run

Example

Simple example with a break being hit.

for y in range(0,3):
    print("y: {}".format(y))
    if y == 2: # will be executed
        print("BREAK: y is {}\n----------".format(y))
        break
else: # not executed because break is hit
    print("y_loop completed without break----------\n")

Result

y: 0
y: 1
y: 2
BREAK: y is 2
----------
# loop not completed (hit break), so else didn't run

Example

Simple example where there no break, no condition raising a break, and no error are encountered.

for z in range(0,3):
     print("z: {}".format(z))
     if z == 4: # will not be executed
         print("BREAK: z is {}\n".format(y))
         break
     if z == 4: # will not be executed
         raise AssertionError("ASSERTION ERROR: x is {}".format(x))
else:
     print("z_loop complete without break or error\n----------\n")

Result

z: 0
z: 1
z: 2
z_loop complete without break or error
----------

Border Height on CSS

table {
 border-spacing: 10px 0px;
}

.rightborder {
border-right: 1px solid #fff;
}

Then with your code you can:

<td class="rightborder">whatever</td>

Hope that helps!

merge two object arrays with Angular 2 and TypeScript?

I think that you should use rather the following:

data => {
  this.results = this.results.concat(data.results);
  this._next = data.next;
},

From the concat doc:

The concat() method returns a new array comprised of the array on which it is called joined with the array(s) and/or value(s) provided as arguments.

PostgreSQL Autoincrement

In the context of the asked question and in reply to the comment by @sereja1c, creating SERIAL implicitly creates sequences, so for the above example-

CREATE TABLE foo (id SERIAL,bar varchar);

CREATE TABLE would implicitly create sequence foo_id_seq for serial column foo.id. Hence, SERIAL [4 Bytes] is good for its ease of use unless you need a specific datatype for your id.

Load properties file in JAR?

The problem is that you are using getSystemResourceAsStream. Use simply getResourceAsStream. System resources load from the system classloader, which is almost certainly not the class loader that your jar is loaded into when run as a webapp.

It works in Eclipse because when launching an application, the system classloader is configured with your jar as part of its classpath. (E.g. java -jar my.jar will load my.jar in the system class loader.) This is not the case with web applications - application servers use complex class loading to isolate webapplications from each other and from the internals of the application server. For example, see the tomcat classloader how-to, and the diagram of the classloader hierarchy used.

EDIT: Normally, you would call getClass().getResourceAsStream() to retrieve a resource in the classpath, but as you are fetching the resource in a static initializer, you will need to explicitly name a class that is in the classloader you want to load from. The simplest approach is to use the class containing the static initializer, e.g.

[public] class MyClass {
  static
  {
    ...
    props.load(MyClass.class.getResourceAsStream("/someProps.properties"));
  }
}

Counting lines, words, and characters within a text file using Python

Try this:

fname = "feed.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += 1
        num_words += len(words)
        num_chars += len(line)

Back to your code:

fname = "feed.txt"
fname = open('feed.txt', 'r')

what's the point of this? fname is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.

for line in feed:
    lines = line.split('\n')

line is one line from the file. It does not make sense to split('\n') it.

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

Adding a file, and then deleting it is the kind of operation that's considered an error - and so SVN is telling you. You told it to expect some file data and then don't supply it when you commit, the red lights flash and the sirens go off!

The answer is to undo your add, alternatively commit the file and then use 'svn rm' to remove it from the filesystem and the repo.

Spring MVC @PathVariable with dot (.) is getting truncated

adding the ":.+" worked for me, but not until I removed outer curly brackets.

value = {"/username/{id:.+}"} didn't work

value = "/username/{id:.+}" works

Hope I helped someone :)