Programs & Examples On #Etl

ETL is an acronym for Extract, Transform, and Load. It refers to a process of extracting data from source systems, transforming the data in some way (manipulating it, filtering it, combining it with other sources), and finally loading the transformed data to target system(s).

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

The proper data type for "2010-12-20 00:00:00.0000000" value is DATETIME2(7) / DT_DBTIME2 ().

But used data type for CYCLE_DATE field is DATETIME - DT_DATE. This means milliseconds precision with accuracy down to every third millisecond (yyyy-mm-ddThh:mi:ss.mmL where L can be 0,3 or 7).

The solution is to change CYCLE_DATE date type to DATETIME2 - DT_DBTIME2.

C# Dictionary get item by index

you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

MySQL - Rows to Columns

My solution :

select h.hostid, sum(ifnull(h.A,0)) as A, sum(ifnull(h.B,0)) as B, sum(ifnull(h.C,0)) as  C from (
select
hostid,
case when itemName = 'A' then itemvalue end as A,
case when itemName = 'B' then itemvalue end as B,
case when itemName = 'C' then itemvalue end as C
  from history 
) h group by hostid

It produces the expected results in the submitted case.

Import Excel spreadsheet columns into SQL Server database

This may sound like the long way around, but you may want to look at using Excel to generate INSERT SQL code that you can past into Query Analyzer to create your table.

Works well if you cant use the wizards because the excel file isn't on the server

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

Exit code 137 (128+9) indicates that your program exited due to receiving signal 9, which is SIGKILL. This also explains the killed message. The question is, why did you receive that signal?

The most likely reason is probably that your process crossed some limit in the amount of system resources that you are allowed to use. Depending on your OS and configuration, this could mean you had too many open files, used too much filesytem space or something else. The most likely is that your program was using too much memory. Rather than risking things breaking when memory allocations started failing, the system sent a kill signal to the process that was using too much memory.

As I commented earlier, one reason you might hit a memory limit after printing finished counting is that your call to counter.items() in your final loop allocates a list that contains all the keys and values from your dictionary. If your dictionary had a lot of data, this might be a very big list. A possible solution would be to use counter.iteritems() which is a generator. Rather than returning all the items in a list, it lets you iterate over them with much less memory usage.

So, I'd suggest trying this, as your final loop:

for key, value in counter.iteritems():
    writer.writerow([key, value])

Note that in Python 3, items returns a "dictionary view" object which does not have the same overhead as Python 2's version. It replaces iteritems, so if you later upgrade Python versions, you'll end up changing the loop back to the way it was.

Mismatched anonymous define() module

Per the docs:

If you manually code a script tag in HTML to load a script with an anonymous define() call, this error can occur.

Also seen if you manually code a script tag in HTML to load a script that has a few named modules, but then try to load an anonymous module that ends up having the same name as one of the named modules in the script loaded by the manually coded script tag.

Finally, if you use the loader plugins or anonymous modules (modules that call define() with no string ID) but do not use the RequireJS optimizer to combine files together, this error can occur. The optimizer knows how to name anonymous modules correctly so that they can be combined with other modules in an optimized file.

To avoid the error:

  • Be sure to load all scripts that call define() via the RequireJS API. Do not manually code script tags in HTML to load scripts that have define() calls in them.

  • If you manually code an HTML script tag, be sure it only includes named modules, and that an anonymous module that will have the same name as one of the modules in that file is not loaded.

  • If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer.

Given an array of numbers, return array of products of all other numbers (no division)

    int[] arr1 = { 1, 2, 3, 4, 5 };
    int[] product = new int[arr1.Length];              

    for (int i = 0; i < arr1.Length; i++)
    {
        for (int j = 0; j < product.Length; j++)
        {
            if (i != j)
            {
                product[j] = product[j] == 0 ? arr1[i] : product[j] * arr1[i];
            }
        }
    }

curl usage to get header

google.com is not responding to HTTP HEAD requests, which is why you are seeing a hang for the first command.

It does respond to GET requests, which is why the third command works.

As for the second, curl just prints the headers from a standard request.

How to manually install an artifact in Maven 2?

I had to add packaging, so:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true \
  -Dpackaging=jar

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

Passing Variable through JavaScript from one html page to another page

Your best option here, is to use the Query String to 'send' the value.

how to get query string value using javascript

  • So page 1 redirects to page2.html?someValue=ABC
  • Page 2 can then read the query string and specifically the key 'someValue'

If this is anything more than a learning exercise you may want to consider the security implications of this though.

Global variables wont help you here as once the page is re-loaded they are destroyed.

Batch - If, ElseIf, Else

Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.

@Echo on
rem Using flags to control command execution

SET ExecuteSection1=0
SET ExecuteSection2=1

@echo off

IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here

:EndSection1

IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2

List of Python format characters

In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")

The chart lists 16 types and some following notes.

My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.

Create dynamic variable name

C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QuickTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, int> names = new Dictionary<string,int>();


            for (int i = 0; i < 10; i++)
            {
                names.Add(String.Format("name{0}", i.ToString()), i);
            }

            var xx1 = names["name1"];
            var xx2 = names["name2"];
            var xx3 = names["name3"];
        }
    }
}

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

How to use Ajax.ActionLink?

For me this worked after I downloaded AJAX Unobtrusive library via NuGet :

 Search and install via NuGet Packages:   Microsoft.jQuery.Unobtrusive.Ajax

Than add in the view the references to jquery and AJAX Unobtrusive:

@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>

Accessing localhost of PC from USB connected Android mobile device

I very much liked John's answer, but I'd like to give it with some changes to those that want to test some client//server configuration by running a client TCP on the USB connected Mobile and a server on the local PC.

First it's quite obvious that the 10.0.2.2 won't work because this is a REAL hardware mobile and not a simulator.

So Follow John's instructions:

  • Unplug all network cables on PC and turn off wifi.
  • Turn off wifi on the android device
  • Connect android device to pc via USB
  • Turn on the "USB Tethering" (USB Modem/ USB Cellular Modem / USB ????? ????? ??????) in the android menu. (Under networks->more...->Tethering and portable hotspot")

    • This USB connection will act as a DHCP server for you single PC connection, so it'll assign your PC a dedicated (dynamic) IP in its local USB network. Now all you have to do is tell the client application this IP and port.
  • Get the IP of your PC (that has been assigned by the USB tether cable.) (open command prompt and type "ipconfig" then look for the IP that the USB network adapter has assigned, in Linux its ifconfig or Ubuntu's "Connection information" etc..)

  • Tell the application to connect to that IP (i.e. 192.168.42.87) with something like (Java - client side):

    String        serverIP      = "192.168.42.87";
    int           serverPort    = 5544;
    InetAddress   serverAddress = InetAddress.getByName(serverIP);
    Socket        socket         = new Socket(serverAddress, serverPort);
    ...
    

    Enjoy..

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

Yes, mysql_fetch_array() only returns one result. If you want to retrieve more than one row, you need to put the function call in a while loop.

Two examples:

This will only return the first row

$row = mysql_fetch_array($result);

This will return one row on each loop, until no more rows are available from the result set

while($row = mysql_fetch_array($result))
{
    //Do stuff with contents of $row
}

How can I get this ASP.NET MVC SelectList to work?

It seems if you have a strongly typed view you need to change the ID of the dropdown so that it is NOT the name of a property on the inherrited class. You then need to put some logic in your edit (POST) method to pull off the selected value from the FORMCollection and put it on to your instance before committing your changes.

This is certainly a little strange, but i tried it and it works.

So if you class has a field called CountryId say, and you're displaying a list of country names, make the dropdown have an id of CountryName rather than CountryId, then in the post, you can do something with Collection["CountryName"].

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

Had the same problem and thanks to you mentioning that the real problem was related to CSS I found the issue:

Having position:relative instead of position:absolute in your .ui-dialog CSS rule makes the dialog and width:'auto' behave strangely.

.ui-dialog { position: absolute;}

Destroy or remove a view in Backbone.js

You could use the way to solve the problem!

initialize:function(){
    this.trigger('remove-compnents-cart');
    var _this = this;
    Backbone.View.prototype.on('remove-compnents-cart',function(){
        //Backbone.View.prototype.remove;
        Backbone.View.prototype.off();
        _this.undelegateEvents();
    })
}

Another way:Create a global variable,like this:_global.routerList

initialize:function(){
    this.routerName = 'home';
    _global.routerList.push(this);
}
/*remove it in memory*/
for (var i=0;i<_global.routerList.length;i++){
    Backbone.View.prototype.remove.call(_global.routerList[i]);
}

How to check if Location Services are enabled?

public class LocationUtil {
private static final String TAG = LocationUtil.class.getSimpleName();

public static LocationManager getLocationManager(final Context context) {
    return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}

public static boolean isNetworkProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

public static boolean isGpsProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.GPS_PROVIDER);
}

// Returns true even if the location services are disabled. Do not use this method to detect location services are enabled.
private static boolean isPassiveProviderEnabled(final Context context) {
    return getLocationManager(context).isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
}

public static boolean isLocationModeOn(final Context context) throws Exception {
    int locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
    return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}

public static boolean isLocationEnabled(final Context context) {
    try {
        return isNetworkProviderEnabled(context) || isGpsProviderEnabled(context)  || isLocationModeOn(context);
    } catch (Exception e) {
        Log.e(TAG, "[isLocationEnabled] error:", e);
    }
    return false;
}

public static void gotoLocationSettings(final Activity activity, final int requestCode) {
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    activity.startActivityForResult(intent, requestCode);
}

public static String getEnabledProvidersLogMessage(final Context context){
    try{
        return "[getEnabledProvidersLogMessage] isNetworkProviderEnabled:"+isNetworkProviderEnabled(context) +
                ", isGpsProviderEnabled:" + isGpsProviderEnabled(context) +
                ", isLocationModeOn:" + isLocationModeOn(context) +
                ", isPassiveProviderEnabled(ignored):" + isPassiveProviderEnabled(context);
    }catch (Exception e){
        Log.e(TAG, "[getEnabledProvidersLogMessage] error:", e);
        return "provider error";
    }
}

}

Use isLocationEnabled method to detect the location services are enabled.

https://github.com/Polidea/RxAndroidBle/issues/327# page will give more information why not to use passive provider, instead use location mode.

Angular 2 @ViewChild annotation returns undefined

For me using ngAfterViewInit instead of ngOnInit fixed the issue :

export class AppComponent implements OnInit {
  @ViewChild('video') video;
  ngOnInit(){
    // <-- in here video is undefined
  }
  public ngAfterViewInit()
  {
    console.log(this.video.nativeElement) // <-- you can access it here
  }
}

How to run html file on localhost?

You can try installing one of the following localhost softwares:

  1. xampp
  2. wamp
  3. ammps server
  4. laragon

There are many more such softwares but the best among them are the ones mentioned above. they also allow domain names (for example: example.com)

How to change fontFamily of TextView in Android

There is a nice library available for this

    implementation 'uk.co.chrisjenx:calligraphy:2.3.0'

how to always round up to the next integer

(list.Count() + 9) / 10

Everything else here is either overkill or simply wrong (except for bestsss' answer, which is awesome). We do not want the overhead of a function call (Math.Truncate(), Math.Ceiling(), etc.) when simple math is enough.


OP's question generalizes (pigeonhole principle) to:

How many boxes do I need to store x objects if only y objects fit into each box?

The solution:

  1. derives from the realization that the last box might be partially empty, and
  2. is (x + y - 1) ÷ y using integer division.

You'll recall from 3rd grade math that integer division is what we're doing when we say 5 ÷ 2 = 2.

Floating-point division is when we say 5 ÷ 2 = 2.5, but we don't want that here.

Many programming languages support integer division. In languages derived from C, you get it automatically when you divide int types (short, int, long, etc.). The remainder/fractional part of any division operation is simply dropped, thus:

5 / 2 == 2

Replacing our original question with x = 5 and y = 2 we have:

How many boxes do I need to store 5 objects if only 2 objects fit into each box?

The answer should now be obvious: 3 boxes -- the first two boxes hold two objects each and the last box holds one.

(x + y - 1) ÷ y =
(5 + 2 - 1) ÷ 2 =
6 ÷ 2 =
3

So for the original question, x = list.Count(), y = 10, which gives the solution using no additional function calls:

(list.Count() + 9) / 10

Load json from local file with http.get() in angular 2

try: this.navItems = this.http.get("data/navItems.json");

Using HTML and Local Images Within UIWebView

After having read a couple of chapters in the iOS 6 Programming Cookbok and started to learn objective-c and iOS programming, I would just like to add, that if one is going to load resources from a custom bundle and use that in a web view, it can be accomplished like this:

NSString *resourcesBundlePath = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
NSBundle *resourcesBundle = [NSBundle bundleWithPath:resourcesBundlePath];
[self.outletWebView loadHTMLString:[html description] baseURL:[resourcesBundle bundleURL]];

Then, in your html you can refer to a resource using the "custom" bundle as your base path:

body {
    background-image:url('img/myBg.png');
}

Easiest way to split a string on newlines in .NET?

I did not know about Environment.Newline, but I guess this is a very good solution.

My try would have been:

        string str = "Test Me\r\nTest Me\nTest Me";
        var splitted = str.Split('\n').Select(s => s.Trim()).ToArray();

The additional .Trim removes any \r or \n that might be still present (e. g. when on windows but splitting a string with os x newline characters). Probably not the fastest method though.

EDIT:

As the comments correctly pointed out, this also removes any whitespace at the start of the line or before the new line feed. If you need to preserve that whitespace, use one of the other options.

Writing an input integer into a cell

I've done this kind of thing with a form that contains a TextBox.

So if you wanted to put this in say cell H1, then use:

ActiveSheet.Range("H1").Value = txtBoxName.Text

Inserting multiple rows in a single SQL query?

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

Example:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

How to split a string with angularJS

Thx guys, I finally found the solution, a really basic one.. In my controller I have

$scope.mySplit = function(string, nb) {
    var array = string.split(',');
    return array[nb];
}

and in my view

{{mySplit(string,0)}}

Popup window in PHP?

if (isset($_POST['Register']))
    {
        $ErrorArrays = array (); //Empty array for input errors 

        $Input_Username = $_POST['Username'];
        $Input_Password = $_POST['Password'];
        $Input_Confirm = $_POST['ConfirmPass'];
        $Input_Email = $_POST['Email'];

        if (empty($Input_Username))
        {
            $ErrorArrays[] = "Username Is Empty";
        }
        if (empty($Input_Password))
        {
            $ErrorArrays[] = "Password Is Empty";
        }
        if ($Input_Password !== $Input_Confirm)
        {
            $ErrorArrays[] = "Passwords Do Not Match!";
        }
        if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

        if (count($ErrorArrays) == 0)
        {
            // No Errors
        }
        else
        {
            foreach ($ErrorArrays AS $Errors)
            {
                echo "<font color='red'><b>".$Errors."</font></b><br>";
            }
        }
    }

?>

    <form method="POST"> 
        Username: <input type='text' name='Username'> <br>
        Password: <input type='password' name='Password'><br>
        Confirm Password: <input type='password' name='ConfirmPass'><br>
        Email: <input type='text' name='Email'> <br><br>

        <input type='submit' name='Register' value='Register'>


    </form> 

This is a very basic PHP Form validation. This could be put in a try block, but for basic reference, I see this fit following our conversation in the comment box.

What this script will do, is process each of the post elements, and act accordingly, for example:

    if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

This will check:

if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.

Further down the script, you will see:

    if (count($ErrorArrays) == 0)
    {
        // No Errors
    }
    else
    {
        foreach ($ErrorArrays AS $Errors)
        {
            echo "<font color='red'><b>".$Errors."</font></b><br>";
        }
    }

Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.

Remember, this is a reference based on our conversation in the comment box, and should be used as such.

Live-stream video from one android phone to another over WiFi

If you do not need the recording and playback functionality in your app, using off-the-shelf streaming app and player is a reasonable choice.

If you do need them to be in your app, however, you will have to look into MediaRecorder API (for the server/camera app) and MediaPlayer (for client/player app).

Quick sample code for the server:

// this is your network socket
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mCamera = getCameraInstance();
mMediaRecorder = new MediaRecorder();
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// this is the unofficially supported MPEG2TS format, suitable for streaming (Android 3.0+)
mMediaRecorder.setOutputFormat(8);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
mediaRecorder.setOutputFile(pfd.getFileDescriptor());
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
mMediaRecorder.prepare();
mMediaRecorder.start();

On the player side it is a bit tricky, you could try this:

// this is your network socket, connected to the server
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(pfd.getFileDescriptor());
mMediaPlayer.prepare();
mMediaPlayer.start();

Unfortunately mediaplayer tends to not like this, so you have a couple of options: either (a) save data from socket to file and (after you have a bit of data) play with mediaplayer from file, or (b) make a tiny http proxy that runs locally and can accept mediaplayer's GET request, reply with HTTP headers, and then copy data from the remote server to it. For (a) you would create the mediaplayer with a file path or file url, for (b) give it a http url pointing to your proxy.

See also:

Stream live video from phone to phone using socket fd

MediaPlayer stutters at start of mp3 playback

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You need to use dynamic SQL to achieve this; something like:

DECLARE
    TYPE cur_type IS REF CURSOR;

    CURSOR client_cur IS
        SELECT DISTING username
        FROM all_users
        WHERE length(username) = 3;

    emails_cur cur_type;
    l_cur_string VARCHAR2(128);
    l_email_id <type>;
    l_name <type>;
BEGIN
    FOR client IN client_cur LOOP
        dbms_output.put_line('Client is '|| client.username);
        l_cur_string := 'SELECT id, name FROM '
            || client.username || '.org';
        OPEN emails_cur FOR l_cur_string;
        LOOP
            FETCH emails_cur INTO l_email_id, l_name;
            EXIT WHEN emails_cur%NOTFOUND;
            dbms_output.put_line('Org id is ' || l_email_id
                || ' org name ' || l_name);
        END LOOP;
        CLOSE emails_cur;
    END LOOP;
END;
/

Edited to correct two errors, and to add links to 10g documentation for OPEN-FOR and an example. Edited to make the inner cursor query a string variable.

dbms_lob.getlength() vs. length() to find blob size in oracle

length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

How do I free my port 80 on localhost Windows?

Identify the real process programmatically

(when the process ID is shown as 4)

The answers here, as usual, expect a level of interactivity.

The problem is when something is listening through HTTP.sys; then, the PID is always 4 and, as most people find, you need some tool to find the real owner.

Here's how to identify the offending process programmatically. No TcpView, etc (as good as those tools are). Does rely on netsh; but then, the problem is usually related to HTTP.sys.

$Uri = "http://127.0.0.1:8989"    # for example


# Shows processes that have registered URLs with HTTP.sys
$QueueText = netsh http show servicestate view=requestq verbose=yes | Out-String

# Break into text chunks; discard the header
$Queues    = $QueueText -split '(?<=\n)(?=Request queue name)' | Select-Object -Skip 1

# Find the chunk for the request queue listening on your URI
$Queue     = @($Queues) -match [regex]::Escape($Uri -replace '/$')


if ($Queue.Count -eq 1)
{
    # Will be null if could not pick out exactly one PID
    $ProcessId = [string]$Queue -replace '(?s).*Process IDs:\s+' -replace '(?s)\s.*' -as [int]

    if ($ProcessId)
    {
        Write-Verbose "Identified process $ProcessId as the HTTP listener. Killing..."
        Stop-Process -Id $ProcessId -Confirm
    }
}

Originally posted here: https://stackoverflow.com/a/65852847/6274530

How do you list volumes in docker containers?

From Docker Documentation here

.Mounts Names of the volumes mounted in this container.

docker ps -a --no-trunc --format "{{.ID}}\t{{.Names}}\t{{.Mounts}}"

should work

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Default value in an asp.net mvc view model

What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

If you load the search criteria from elsewhere, then you should probably have some mapping logic.

How, in general, does Node.js handle 10,000 concurrent requests?

Adding to slebetman answer: When you say Node.JS can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.

Internally, event loop of Node.JS is handling a thread pool, where each thread handles a non-blocking request and event loop continues to listen to more request after delegating work to one of the thread of the thread pool. When one of the thread completes the work, it send a signal to the event loop that it has finished aka callback. Event loop then process this callback and send the response back.

As you are new to NodeJS, do read more about nextTick to understand how event loop works internally. Read blogs on http://javascriptissexy.com, they were really helpful for me when I started with JavaScript/NodeJS.

How to compile c# in Microsoft's new Visual Studio Code?

SHIFT+CTRL+B should work

However sometimes an issue can happen in a locked down non-adminstrator evironment:

If you open an existing C# application from the folder you should have a .sln (solution file) etc..

Commonly you can get these message in VS Code

Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!

Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'

Finished
Failed to spawn 'dotnet --info'  //this is a possible issue

To which then you will be asked to install .NET CLI tools

If impossible to get SDK installed with no admin privilege - then use other solution.

Convert DataSet to List

Try the above which will run with any list type.

  public DataTable ListToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection props =
            TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for (int i = 0; i < props.Count; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item);
            }
            table.Rows.Add(values);
        }
        return table;
    }

Does --disable-web-security Work In Chrome Anymore?

Check your windows task manager and make sure you kill all chrome processes before running the command.

How to give a delay in loop execution using Qt

EDIT (removed wrong solution). EDIT (to add this other option):

Another way to use it would be subclass QThread since it has protected *sleep methods.

QThread::usleep(unsigned long microseconds);
QThread::msleep(unsigned long milliseconds);
QThread::sleep(unsigned long second);

Here's the code to create your own *sleep method.

#include <QThread>    

class Sleeper : public QThread
{
public:
    static void usleep(unsigned long usecs){QThread::usleep(usecs);}
    static void msleep(unsigned long msecs){QThread::msleep(msecs);}
    static void sleep(unsigned long secs){QThread::sleep(secs);}
};

and you call it by doing this:

Sleeper::usleep(10);
Sleeper::msleep(10);
Sleeper::sleep(10);

This would give you a delay of 10 microseconds, 10 milliseconds or 10 seconds, accordingly. If the underlying operating system timers support the resolution.

Position an element relative to its container

You are right that CSS positioning is the way to go. Here's a quick run down:

position: relative will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).

However, you're most likely interested in position: absolute which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative or position: absolute set on it, then it will act as the parent for positioning coordinates for its children.

To demonstrate:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  border: 1px solid red;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="box">absolute</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In that example, the top left corner of #box would be 100px down and 50px left of the top left corner of #container. If #container did not have position: relative set, the coordinates of #box would be relative to the top left corner of the browser view port.

Get Absolute URL from Relative path (refactored method)

With ASP.NET, you need to consider the reference point for a "relative URL" - is it relative to the page request, a user control, or if it is "relative" simply by virtue of using "~/"?

The Uri class contains a simple way to convert a relative URL to an absolute URL (given an absolute URL as the reference point for the relative URL):

var uri = new Uri(absoluteUrl, relativeUrl);

If relativeUrl is in fact an abolute URL, then the absoluteUrl is ignored.

The only question then remains what the reference point is, and whether "~/" URLs are allowed (the Uri constructor does not translate these).

Command-line Git on Windows

If you have installed GitHubDesktop in Windows 10, then press Ctrl + '. or in the menu go to Repository>Open in command prompt.

In case git is not installed in your machine, you should get a prompt to install git.(I came to know from this that GitHubDesktop and git are different applications). Install git, close your command prompt and open it again.

You can test your installation by typing in git at the command prompt.

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

I know the question doesn't state SQL Server express, but its worth pointing out that the SQL Server Express editions don't come with the profiler (very annoying), and I suspect that they also don't come with the query analyzer.

How to read a single char from the console in Java (as the user types it)?

I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.

  • On Windows it uses _kbhit() and _getwch() from msvcrt.dll.
  • On Unix it uses tcsetattr() to switch the console to non-canonical mode, System.in.available() to check whether data is available and System.in.read() to read bytes from the console. A CharsetDecoder is used to convert bytes to characters.

It supports non-blocking input and mixing raw mode and normal line mode input.

How to trigger event when a variable's value is changed?

A simple method involves using the get and set functions on the variable


    using System;
    public string Name{
    get{
     return name;
    }
    
    set{
     name= value;
     OnVarChange?.Invoke();
    }
    }
    private string name;
    
    public event System.Action OnVarChange;

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

public static String getCurrentTimezoneOffset() {

    TimeZone tz = TimeZone.getDefault();  
    Calendar cal = GregorianCalendar.getInstance(tz);
    int offsetInMillis = tz.getOffset(cal.getTimeInMillis());

    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
    offset = (offsetInMillis >= 0 ? "+" : "-") + offset;

    return offset;
}

How to check if pytorch is using the GPU?

After you start running the training loop, if you want to manually watch it from the terminal whether your program is utilizing the GPU resources and to what extent, then you can simply use watch as in:

$ watch -n 2 nvidia-smi

This will continuously update the usage stats for every 2 seconds until you press ctrl+c


If you need more control on more GPU stats you might need, you can use more sophisticated version of nvidia-smi with --query-gpu=.... Below is a simple illustration of this:

$ watch -n 3 nvidia-smi --query-gpu=index,gpu_name,memory.total,memory.used,memory.free,temperature.gpu,pstate,utilization.gpu,utilization.memory --format=csv

which would output the stats something like:

enter image description here

Note: There should not be any space between the comma separated query names in --query-gpu=.... Else those values will be ignored and no stats are returned.


Also, you can check whether your installation of PyTorch detects your CUDA installation correctly by doing:

In [13]: import  torch

In [14]: torch.cuda.is_available()
Out[14]: True

True status means that PyTorch is configured correctly and is using the GPU although you have to move/place the tensors with necessary statements in your code.


If you want to do this inside Python code, then look into this module:

https://github.com/jonsafari/nvidia-ml-py or in pypi here: https://pypi.python.org/pypi/nvidia-ml-py/

Difference between Fact table and Dimension table?

In the simplest form, I think a dimension table is something like a 'Master' table - that keeps a list of all 'items', so to say.

A fact table is a transaction table which describes all the transactions. In addition, aggregated (grouped) data like total sales by sales person, total sales by branch - such kinds of tables also might exist as independent fact tables.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Can .NET load and parse a properties file equivalent to Java Properties class?

Yeah there's no built in classes to do this that I'm aware of.

But that shouldn't really be an issue should it? It looks easy enough to parse just by storing the result of Stream.ReadToEnd() in a string, splitting based on new lines and then splitting each record on the = character. What you'd be left with is a bunch of key value pairs which you can easily toss into a dictionary.

Here's an example that might work for you:

public static Dictionary<string, string> GetProperties(string path)
{
    string fileData = "";
    using (StreamReader sr = new StreamReader(path))
    {
        fileData = sr.ReadToEnd().Replace("\r", "");
    }
    Dictionary<string, string> Properties = new Dictionary<string, string>();
    string[] kvp;
    string[] records = fileData.Split("\n".ToCharArray());
    foreach (string record in records)
    {
        kvp = record.Split("=".ToCharArray());
        Properties.Add(kvp[0], kvp[1]);
    }
    return Properties;
}

Here's an example of how to use it:

Dictionary<string,string> Properties = GetProperties("data.txt");
Console.WriteLine("Hello: " + Properties["Hello"]);
Console.ReadKey();

Java String new line

Example

System.out.printf("I %n am %n a %n boy");

Output

I 
 am 
 a 
 boy

Explanation

It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()

Why to use %n, because on each OS, new line refers to a different set of character(s);

Unix and modern Mac's   :   LF     (\n)
Windows                 :   CR LF  (\r\n)
Older Macintosh Systems :   CR     (\r)

LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n is OS agnostic, it is portable. It stands for \n on Unix systems or \r\n on Windows systems and so on. Thus, Do not use \n, instead use %n.

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Replacing server=localhost with server=.\SQLEXPRESS might do the job.

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

If you added (or have) a CSS class or id to the parent element, then you can do something like this:

<div id="parent">
  <div>
  </div>
</div>

JavaScript:
document.getElementById("parent").onmouseout = function(e) {
  e = e ? e : window.event //For IE
  if(e.target.id == "parent") {
    //Do your stuff
  }
}

So stuff only gets executed when the event is on the parent div.

CodeIgniter - How to return Json response from controller

//do the edit in your javascript

$('.signinform').submit(function() { 
   $(this).ajaxSubmit({ 
       type : "POST",
       //set the data type
       dataType:'json',
       url: 'index.php/user/signin', // target element(s) to be updated with server response 
       cache : false,
       //check this in Firefox browser
       success : function(response){ console.log(response); alert(response)},
       error: onFailRegistered
   });        
   return false; 
}); 


//controller function

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    

   //add the header here
    header('Content-Type: application/json');
    echo json_encode( $arr );
}

How to pass parameters or arguments into a gradle task

If the task you want to pass parameters to is of type JavaExec and you are using Gradle 5, for example the application plugin's run task, then you can pass your parameters through the --args=... command line option. For example gradle run --args="foo --bar=true".

Otherwise there is no convenient builtin way to do this, but there are 3 workarounds.

1. If few values, task creation function

If the possible values are few and are known in advance, you can programmatically create a task for each of them:

void createTask(String platform) {
   String taskName = "myTask_" + platform;
   task (taskName) {
      ... do what you want
   }
}

String[] platforms = ["macosx", "linux32", "linux64"];
for(String platform : platforms) {
    createTask(platform);
}

You would then call your tasks the following way:

./gradlew myTask_macosx

2. Standard input hack

A convenient hack is to pass the arguments through standard input, and have your task read from it:

./gradlew myTask <<<"arg1 arg2 arg\ in\ several\ parts"

with code below:

String[] splitIntoTokens(String commandLine) {
    String regex = "(([\"']).*?\\2|(?:[^\\\\ ]+\\\\\\s+)+[^\\\\ ]+|\\S+)";
    Matcher matcher = Pattern.compile(regex).matcher(commandLine);
    ArrayList<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(matcher.group());
    }
    return result.toArray();   
}

task taskName, {
        doFirst {
            String typed = new Scanner(System.in).nextLine();
            String[] parsed = splitIntoTokens(typed);
            println ("Arguments received: " + parsed.join(" "))
            ... do what you want
        } 
 }

You will also need to add the following lines at the top of your build script:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;

3. -P parameters

The last option is to pass a -P parameter to Gradle:

./gradlew myTask -PmyArg=hello

You can then access it as myArg in your build script:

task myTask {
    doFirst {
       println myArg
       ... do what you want
    }
}

Credit to @789 for his answer on splitting arguments into tokens

Difference between virtual and abstract methods

Abstract Method:

  • If an abstract method is defined in a class, then the class should declare as an abstract class.

  • An abstract method should contain only method definition, should not Contain the method body/implementation.

  • An abstract method must be over ride in the derived class.

Virtual Method:

  • Virtual methods can be over ride in the derived class but not mandatory.
  • Virtual methods must have the method body/implementation along with the definition.

Example:

public abstract class baseclass
        {
            public abstract decimal getarea(decimal Radius);

            public virtual decimal interestpermonth(decimal amount)
            {
                return amount*12/100;
            }

            public virtual decimal totalamount(decimal Amount,decimal principleAmount)
            {
                return Amount + principleAmount;
            }
        }

        public class derivedclass:baseclass
        {
            public override decimal getarea(decimal Radius)
            {
                return 2 * (22 / 7) * Radius;
            }

            public override decimal interestpermonth(decimal amount)
            {
                return amount * 14 / 100;
            }
        }

Correct MySQL configuration for Ruby on Rails Database.yml file

You also can do like this:

default: &default
  adapter: mysql2
  encoding: utf8
  username: root
  password:
  host: 127.0.0.1
  port: 3306

development:
  <<: *default
  database: development_db_name

test:
  <<: *default
  database: test_db_name

production:
  <<: *default
  database: production_db_name

Adding an item to an associative array

I know this is an old question but you can use:

array_push($data, array($category => $question));

This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:

array_push($data,$question);

How to split a line into words separated by one or more spaces in bash?

s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...

how to realize countifs function (excel) in R

library(matrixStats)
> data <- rbind(c("M", "F", "M"), c("Student", "Analyst", "Analyst"))
> rowCounts(data, value = 'M') # output = 2 0
> rowCounts(data, value = 'F') # output = 1 0

Create comma separated strings C#?

Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.

Pros - More flexible than an array.

Cons - You can't pass a string containing a comma.

CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();

list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");

string s = list.ToString(); //Huey,Dewey,Louie

How to capture multiple repeated groups?

Just to provide additional example of paragraph 2 in the answer. I'm not sure how critical it is for you to get three groups in one match rather than three matches using one group. E.g., in groovy:

def subject = "HELLO,THERE,WORLD"
def pat = "([A-Z]+)"
def m = (subject =~ pat)
m.eachWithIndex{ g,i ->
  println "Match #$i: ${g[1]}"
}

Match #0: HELLO
Match #1: THERE
Match #2: WORLD

What is the iPhone 4 user-agent?

  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en_us) AppleWebKit/525.18.1 (KHTML, like Gecko)
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5

...for now

What's the difference between implementation and compile in Gradle?

+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| Name               | Role                 | Consumable? | Resolveable? | Description                             |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| api                | Declaring            |      no     |      no      | This is where you should declare        |
|                    | API                  |             |              | dependencies which are transitively     |
|                    | dependencies         |             |              | exported to consumers, for compile.     |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| implementation     | Declaring            |      no     |      no      | This is where you should                |
|                    | implementation       |             |              | declare dependencies which are          |
|                    | dependencies         |             |              | purely internal and not                 |
|                    |                      |             |              | meant to be exposed to consumers.       |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| compileOnly        | Declaring compile    |     yes     |      yes     | This is where you should                |
|                    | only                 |             |              | declare dependencies                    |
|                    | dependencies         |             |              | which are only required                 |
|                    |                      |             |              | at compile time, but should             |
|                    |                      |             |              | not leak into the runtime.              |
|                    |                      |             |              | This typically includes dependencies    |
|                    |                      |             |              | which are shaded when found at runtime. |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| runtimeOnly        | Declaring            |      no     |      no      | This is where you should                |
|                    | runtime              |             |              | declare dependencies which              |
|                    | dependencies         |             |              | are only required at runtime,           |
|                    |                      |             |              | and not at compile time.                |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testImplementation | Test dependencies    |      no     |      no      | This is where you                       |
|                    |                      |             |              | should declare dependencies             |
|                    |                      |             |              | which are used to compile tests.        |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testCompileOnly    | Declaring test       |     yes     |      yes     | This is where you should                |
|                    | compile only         |             |              | declare dependencies                    |
|                    | dependencies         |             |              | which are only required                 |
|                    |                      |             |              | at test compile time,                   |
|                    |                      |             |              | but should not leak into the runtime.   |
|                    |                      |             |              | This typically includes dependencies    |
|                    |                      |             |              | which are shaded when found at runtime. |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+
| testRuntimeOnly    | Declaring test       |      no     |      no      | This is where you should                |
|                    | runtime dependencies |             |              | declare dependencies which              |
|                    |                      |             |              | are only required at test               |
|                    |                      |             |              | runtime, and not at test compile time.  |
+--------------------+----------------------+-------------+--------------+-----------------------------------------+

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

trace a particular IP and port

Firstly, check the IP address that your application has bound to. It could only be binding to a local address, for example, which would mean that you'd never see it from a different machine regardless of firewall states.

You could try using a portscanner like nmap to see if the port is open and visible externally... it can tell you if the port is closed (there's nothing listening there), open (you should be able to see it fine) or filtered (by a firewall, for example).

How can I upgrade NumPy?

When you already have an older version of NumPy, use this:

pip install numpy --upgrade

If it still doesn't work, try:

pip install numpy --upgrade --ignore-installed

SQL query to get most recent row for each instance of a given key

Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.

To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.

I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!

Using StringWriter for XML Serialization

<TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/> to the string, then declaring the SqlParameter to be of type SqlDbType.Xml or SqlDbType.NVarChar would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16, you were clearly inserting a VARCHAR string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).

The fix should have been as simple as:

  1. In the first case, when adding the declaration stating encoding="utf-8": simply don't add the XML declaration.
  2. In the second case, when adding the declaration stating encoding="utf-16": either
    1. simply don't add the XML declaration, OR
    2. simply add an "N" to the input parameter type: SqlDbType.NVarChar instead of SqlDbType.VarChar :-) (or possibly even switch to using SqlDbType.Xml)

(Detailed response is below)


All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.

It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve “unable to switch the encoding” error when inserting XML into SQL Server, but the basics are:

  1. The XML declaration is optional
  2. The XML datatype stores strings always as UCS-2 / UTF-16 LE
  3. If your XML is UCS-2 / UTF-16 LE, then you:
    1. pass in the data as either NVARCHAR(MAX) or XML / SqlDbType.NVarChar (maxsize = -1) or SqlDbType.Xml, or if using a string literal then it must be prefixed with an upper-case "N".
    2. if specifying the XML declaration, it must be either "UCS-2" or "UTF-16" (no real difference here)
  4. If your XML is 8-bit encoded (e.g. "UTF-8" / "iso-8859-1" / "Windows-1252"), then you:
    1. need to specify the XML declaration IF the encoding is different than the code page specified by the default Collation of the database
    2. you must pass in the data as VARCHAR(MAX) / SqlDbType.VarChar (maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".
    3. Whatever 8-bit encoding is used, the "encoding" noted in the XML declaration must match the actual encoding of the bytes.
    4. The 8-bit encoding will be converted into UTF-16 LE by the XML datatype

With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:

Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?

No, your StringWriter code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).

Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?

It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR (i.e. SqlDbType.NVarChar) or XML (i.e. SqlDbType.Xml). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR (i.e. SqlDbType.VarChar). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.

On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar or SqlDbType.Xml. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8, Windows-1252, iso-8859-1, etc), then you must pass in as SqlDbType.VarChar. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.

For example, using your StringWriter-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter does not have an option to OmitXmlDeclaration like XmlWriter does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:

-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
SELECT @Xml;
-- <string>Test ?</string>

As you can see, it even handles characters beyond standard ASCII, given that ? is BMP Code Point U+1234, and is Supplementary Character Code Point U+1F638. However, the following:

-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';

results in the following error:

Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding

Ergo, all of that explanation aside, the full solution to your original question is:

You were clearly passing the string in as SqlDbType.VarChar. Switch to SqlDbType.NVarChar and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:

-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ?</string>';
SELECT @Xml2;
-- <string>Test ???</string>

As you can see, there is no error this time, but now there is data-loss 🙀.

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

I think the best solution, though not exactly the same as Eclipse/Netbeans, is to change the 'Optimize Imports' settings.

Under Preferences > Editor > General > Auto Import

Set Add unambiguous imports on the fly

Edit: Using this method, when there are ambiguous imports, IntelliJ will let you know, and you can then use Alt + Enter method outlined in the answer by Wuaner

I find that, almost always, the most appropriate Import is at the top of the list.

VBA - how to conditionally skip a for loop iteration

Continue For isn't valid in VBA or VB6.

From this MSDN page it looks to have been introduced into VB.Net in VS 2005./Net 2.

As the others have said there's not really an option other than to use Goto or an Else.

Pandas: rolling mean by time interval

user2689410's code was exactly what I needed. Providing my version (credits to user2689410), which is faster due to calculating mean at once for whole rows in the DataFrame.

Hope my suffix conventions are readable: _s: string, _i: int, _b: bool, _ser: Series and _df: DataFrame. Where you find multiple suffixes, type can be both.

import pandas as pd
from datetime import datetime, timedelta
import numpy as np

def time_offset_rolling_mean_df_ser(data_df_ser, window_i_s, min_periods_i=1, center_b=False):
    """ Function that computes a rolling mean

    Credit goes to user2689410 at http://stackoverflow.com/questions/15771472/pandas-rolling-mean-by-time-interval

    Parameters
    ----------
    data_df_ser : DataFrame or Series
         If a DataFrame is passed, the time_offset_rolling_mean_df_ser is computed for all columns.
    window_i_s : int or string
         If int is passed, window_i_s is the number of observations used for calculating
         the statistic, as defined by the function pd.time_offset_rolling_mean_df_ser()
         If a string is passed, it must be a frequency string, e.g. '90S'. This is
         internally converted into a DateOffset object, representing the window_i_s size.
    min_periods_i : int
         Minimum number of observations in window_i_s required to have a value.

    Returns
    -------
    Series or DataFrame, if more than one column

    >>> idx = [
    ...     datetime(2011, 2, 7, 0, 0),
    ...     datetime(2011, 2, 7, 0, 1),
    ...     datetime(2011, 2, 7, 0, 1, 30),
    ...     datetime(2011, 2, 7, 0, 2),
    ...     datetime(2011, 2, 7, 0, 4),
    ...     datetime(2011, 2, 7, 0, 5),
    ...     datetime(2011, 2, 7, 0, 5, 10),
    ...     datetime(2011, 2, 7, 0, 6),
    ...     datetime(2011, 2, 7, 0, 8),
    ...     datetime(2011, 2, 7, 0, 9)]
    >>> idx = pd.Index(idx)
    >>> vals = np.arange(len(idx)).astype(float)
    >>> ser = pd.Series(vals, index=idx)
    >>> df = pd.DataFrame({'s1':ser, 's2':ser+1})
    >>> time_offset_rolling_mean_df_ser(df, window_i_s='2min')
                          s1   s2
    2011-02-07 00:00:00  0.0  1.0
    2011-02-07 00:01:00  0.5  1.5
    2011-02-07 00:01:30  1.0  2.0
    2011-02-07 00:02:00  2.0  3.0
    2011-02-07 00:04:00  4.0  5.0
    2011-02-07 00:05:00  4.5  5.5
    2011-02-07 00:05:10  5.0  6.0
    2011-02-07 00:06:00  6.0  7.0
    2011-02-07 00:08:00  8.0  9.0
    2011-02-07 00:09:00  8.5  9.5
    """

    def calculate_mean_at_ts(ts):
        """Function (closure) to apply that actually computes the rolling mean"""
        if center_b == False:
            dslice_df_ser = data_df_ser[
                ts-pd.datetools.to_offset(window_i_s).delta+timedelta(0,0,1):
                ts
            ]
            # adding a microsecond because when slicing with labels start and endpoint
            # are inclusive
        else:
            dslice_df_ser = data_df_ser[
                ts-pd.datetools.to_offset(window_i_s).delta/2+timedelta(0,0,1):
                ts+pd.datetools.to_offset(window_i_s).delta/2
            ]
        if  (isinstance(dslice_df_ser, pd.DataFrame) and dslice_df_ser.shape[0] < min_periods_i) or \
            (isinstance(dslice_df_ser, pd.Series) and dslice_df_ser.size < min_periods_i):
            return dslice_df_ser.mean()*np.nan   # keeps number format and whether Series or DataFrame
        else:
            return dslice_df_ser.mean()

    if isinstance(window_i_s, int):
        mean_df_ser = pd.rolling_mean(data_df_ser, window=window_i_s, min_periods=min_periods_i, center=center_b)
    elif isinstance(window_i_s, basestring):
        idx_ser = pd.Series(data_df_ser.index.to_pydatetime(), index=data_df_ser.index)
        mean_df_ser = idx_ser.apply(calculate_mean_at_ts)

    return mean_df_ser

Why is the Java main method static?

Because otherwise, it would need an instance of the object to be executed. But it must be called from scratch, without constructing the object first, since it is usually the task of the main() function (bootstrap), to parse the arguments and construct the object, usually by using these arguments/program parameters.

How to use "Share image using" sharing Intent to share images in android?

The solution proposed from superM worked for me for a long time, but lately I tested it on 4.2 (HTC One) and it stopped working there. I am aware that this is a workaround, but it was the only one which worked for me with all devices and versions.

According to the documentation, developers are asked to "use the system MediaStore" to send binary content. This, however, has the (dis-)advantage, that the media content will be saved permanently on the device.

If this is an option for you, you might want to grant permission WRITE_EXTERNAL_STORAGE and use the system-wide MediaStore.

Bitmap icon = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");

ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, "title");
values.put(Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
        values);


OutputStream outstream;
try {
    outstream = getContentResolver().openOutputStream(uri);
    icon.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
    outstream.close();
} catch (Exception e) {
    System.err.println(e.toString());
}

share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));

How to stop default link click behavior with jQuery

You want e.preventDefault() to prevent the default functionality from occurring.

Or have return false from your method.

preventDefault prevents the default functionality and stopPropagation prevents the event from bubbling up to container elements.

An Iframe I need to refresh every 30 seconds (but not the whole page)

add "id='myiframe'" to the iframe, then use this script :

<script>

function f1()
{
 var x=document.getElementById("myiframe");
   x.src=x.src+Math.floor(random()%100000);
}

setInterval(f1,30*1000);

</script>

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

Example :

String teste = " 'Bauru '";

teste = teste.replaceAll("  '  ","");
JOptionPane.showMessageDialog(null,teste);

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

Select where count of one field is greater than one

It should also be mentioned that the "pk" should be a key field. The self-join

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk 

by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried

SELECT * FROM db.table HAVING COUNT(someField) > 1

above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.

"Invalid form control" only in Google Chrome

If you don't care about HTML5 validation (maybe you are validating in JS or on the server), you could try adding "novalidate" to the form or the input elements.

Clear variable in python

Actually, that does not delete the variable/property. All it will do is set its value to None, therefore the variable will still take up space in memory. If you want to completely wipe all existence of the variable from memory, you can just type:

del self.left

CSS override rules and specificity

To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 trfrom rule one and add it to rule two.

table.rule1 tr td {
    background-color: #ff0000;
}

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.

Creating runnable JAR with Gradle

You can define a jar artifact in the module settings (or project structure).

  • Right click the module > Open module settings > Artifacts > + > JAR > from modules with dependencies.
  • Set the main class.

Making a jar is then as easy as clicking "Build artifact..." from the Build menu. As a bonus, you can package all the dependencies into a single jar.

Tested on IntelliJ IDEA 14 Ultimate.

Detect iPad users using jQuery?

I use this:

function fnIsAppleMobile() 
{
    if (navigator && navigator.userAgent && navigator.userAgent != null) 
    {
        var strUserAgent = navigator.userAgent.toLowerCase();
        var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
        if (arrMatches != null) 
             return true;
    } // End if (navigator && navigator.userAgent) 

    return false;
} // End Function fnIsAppleMobile


var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove

Install Node.js on Ubuntu

My apt-get was old and busted, so I had to install from source. Here is what worked for me:

# Get the latest version from nodejs.org. At the time of this writing, it was 0.10.24
curl -o ~/node.tar.gz http://nodejs.org/dist/v0.10.24/node-v0.10.24.tar.gz
cd
tar -zxvf node.tar.gz
cd node-v0.6.18
./configure && make && sudo make install

These steps were mostly taken from joyent's installation wiki.

Recommendation for compressing JPG files with ImageMagick

@JavisPerez -- Is there any way to compress that image to 150kb at least? Is that possible? What ImageMagick options can I use?

See the following links where there is an option in ImageMagick to specify the desired output file size for writing to JPG files.

http://www.imagemagick.org/Usage/formats/#jpg_write http://www.imagemagick.org/script/command-line-options.php#define

-define jpeg:extent={size} As of IM v6.5.8-2 you can specify a maximum output filesize for the JPEG image. The size is specified with a suffix. For example "400kb".

convert image.jpg -define jpeg:extent=150kb result.jpg

You will lose some quality by decompressing and recompressing in addition to any loss due to lowering -quality value from the input.

Codeigniter unset session

$session_data = array('username' =>"shashikant");
$this->session->set_userdata('logged_in', $session_data);

$this->session->unset_userdata('logged_in');

PHP Multidimensional Array Searching (Find key by specific value)

For the next visitor coming along: use the recursive array walk; it visits every "leaf" in the multidimensional array. Here's for inspiration:

function getMDArrayValueByKey($a, $k) {
    $r = [];
    array_walk_recursive ($a, 
                          function ($item, $key) use ($k, &$r) {if ($key == $k) $r[] = $item;}
                          );
    return $r;
}

How to use wait and notify in Java without IllegalMonitorStateException?

You can only call notify on objects where you own their monitor. So you need something like

synchronized(threadObject)
{
   threadObject.notify();
}

Switch: Multiple values in one case?

There's no way to evaluate multiple values in one 'case'. You could either use an if statement (as others have suggested) or call a method which evaluates the range that the integer belongs to and returns a value which represents that range (such as "minor", "adult", etc.), then evaluate this returned value in the switch statement. Of course, you'd probably still be using an if statement in the custom method.

Upload artifacts to Nexus, without Maven

@Adam Vandenberg For Java code to POST to Nexus. https://github.com/manbalagan/nexusuploader

public class NexusRepository implements RepoTargetFactory {

    String DIRECTORY_KEY= "raw.directory";
    String ASSET_KEY= "raw.asset1";
    String FILENAME_KEY= "raw.asset1.filename";

    String repoUrl;
    String userName;
    String password;

    @Override
    public void setRepoConfigurations(String repoUrl, String userName, String password) {
        this.repoUrl = repoUrl;
        this.userName = userName;
        this.password = password;
    }

    public String pushToRepository() {
        HttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost postRequest = new HttpPost(repoUrl) ;
        String auth = userName + ":" + password;
        byte[] encodedAuth = Base64.encodeBase64(
                auth.getBytes(StandardCharsets.ISO_8859_1));
        String authHeader = "Basic " + new String(encodedAuth);
        postRequest.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        try
        {
            byte[] packageBytes = "Hello. This is my file content".getBytes();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            InputStream packageStream = new ByteArrayInputStream(packageBytes);
            InputStreamBody inputStreamBody = new InputStreamBody(packageStream, ContentType.APPLICATION_OCTET_STREAM);
            multipartEntityBuilder.addPart(DIRECTORY_KEY, new StringBody("DIRECTORY"));
            multipartEntityBuilder.addPart(FILENAME_KEY, new StringBody("MyFile.txt"));
            multipartEntityBuilder.addPart(ASSET_KEY, inputStreamBody);
            HttpEntity entity = multipartEntityBuilder.build();
            postRequest.setEntity(entity); ;

            HttpResponse response = httpclient.execute(postRequest) ;
            if (response != null)
            {
                System.out.println(response.getStatusLine().getStatusCode());
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace() ;
        }
        return null;
    }

}

How do I profile memory usage in Python?

Python 3.4 includes a new module: tracemalloc. It provides detailed statistics about which code is allocating the most memory. Here's an example that displays the top three lines allocating memory.

from collections import Counter
import linecache
import os
import tracemalloc

def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


tracemalloc.start()

counts = Counter()
fname = '/usr/share/dict/american-english'
with open(fname) as words:
    words = list(words)
    for word in words:
        prefix = word[:3]
        counts[prefix] += 1
print('Top prefixes:', counts.most_common(3))

snapshot = tracemalloc.take_snapshot()
display_top(snapshot)

And here are the results:

Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
Top 3 lines
#1: scratches/memory_test.py:37: 6527.1 KiB
    words = list(words)
#2: scratches/memory_test.py:39: 247.7 KiB
    prefix = word[:3]
#3: scratches/memory_test.py:40: 193.0 KiB
    counts[prefix] += 1
4 other: 4.3 KiB
Total allocated size: 6972.1 KiB

When is a memory leak not a leak?

That example is great when the memory is still being held at the end of the calculation, but sometimes you have code that allocates a lot of memory and then releases it all. It's not technically a memory leak, but it's using more memory than you think it should. How can you track memory usage when it all gets released? If it's your code, you can probably add some debugging code to take snapshots while it's running. If not, you can start a background thread to monitor memory usage while the main thread runs.

Here's the previous example where the code has all been moved into the count_prefixes() function. When that function returns, all the memory is released. I also added some sleep() calls to simulate a long-running calculation.

from collections import Counter
import linecache
import os
import tracemalloc
from time import sleep


def count_prefixes():
    sleep(2)  # Start up time.
    counts = Counter()
    fname = '/usr/share/dict/american-english'
    with open(fname) as words:
        words = list(words)
        for word in words:
            prefix = word[:3]
            counts[prefix] += 1
            sleep(0.0001)
    most_common = counts.most_common(3)
    sleep(3)  # Shut down time.
    return most_common


def main():
    tracemalloc.start()

    most_common = count_prefixes()
    print('Top prefixes:', most_common)

    snapshot = tracemalloc.take_snapshot()
    display_top(snapshot)


def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


main()

When I run that version, the memory usage has gone from 6MB down to 4KB, because the function released all its memory when it finished.

Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
Top 3 lines
#1: collections/__init__.py:537: 0.7 KiB
    self.update(*args, **kwds)
#2: collections/__init__.py:555: 0.6 KiB
    return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
#3: python3.6/heapq.py:569: 0.5 KiB
    result = [(key(elem), i, elem) for i, elem in zip(range(0, -n, -1), it)]
10 other: 2.2 KiB
Total allocated size: 4.0 KiB

Now here's a version inspired by another answer that starts a second thread to monitor memory usage.

from collections import Counter
import linecache
import os
import tracemalloc
from datetime import datetime
from queue import Queue, Empty
from resource import getrusage, RUSAGE_SELF
from threading import Thread
from time import sleep

def memory_monitor(command_queue: Queue, poll_interval=1):
    tracemalloc.start()
    old_max = 0
    snapshot = None
    while True:
        try:
            command_queue.get(timeout=poll_interval)
            if snapshot is not None:
                print(datetime.now())
                display_top(snapshot)

            return
        except Empty:
            max_rss = getrusage(RUSAGE_SELF).ru_maxrss
            if max_rss > old_max:
                old_max = max_rss
                snapshot = tracemalloc.take_snapshot()
                print(datetime.now(), 'max RSS', max_rss)


def count_prefixes():
    sleep(2)  # Start up time.
    counts = Counter()
    fname = '/usr/share/dict/american-english'
    with open(fname) as words:
        words = list(words)
        for word in words:
            prefix = word[:3]
            counts[prefix] += 1
            sleep(0.0001)
    most_common = counts.most_common(3)
    sleep(3)  # Shut down time.
    return most_common


def main():
    queue = Queue()
    poll_interval = 0.1
    monitor_thread = Thread(target=memory_monitor, args=(queue, poll_interval))
    monitor_thread.start()
    try:
        most_common = count_prefixes()
        print('Top prefixes:', most_common)
    finally:
        queue.put('stop')
        monitor_thread.join()


def display_top(snapshot, key_type='lineno', limit=3):
    snapshot = snapshot.filter_traces((
        tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
        tracemalloc.Filter(False, "<unknown>"),
    ))
    top_stats = snapshot.statistics(key_type)

    print("Top %s lines" % limit)
    for index, stat in enumerate(top_stats[:limit], 1):
        frame = stat.traceback[0]
        # replace "/path/to/module/file.py" with "module/file.py"
        filename = os.sep.join(frame.filename.split(os.sep)[-2:])
        print("#%s: %s:%s: %.1f KiB"
              % (index, filename, frame.lineno, stat.size / 1024))
        line = linecache.getline(frame.filename, frame.lineno).strip()
        if line:
            print('    %s' % line)

    other = top_stats[limit:]
    if other:
        size = sum(stat.size for stat in other)
        print("%s other: %.1f KiB" % (len(other), size / 1024))
    total = sum(stat.size for stat in top_stats)
    print("Total allocated size: %.1f KiB" % (total / 1024))


main()

The resource module lets you check the current memory usage, and save the snapshot from the peak memory usage. The queue lets the main thread tell the memory monitor thread when to print its report and shut down. When it runs, it shows the memory being used by the list() call:

2018-05-29 10:34:34.441334 max RSS 10188
2018-05-29 10:34:36.475707 max RSS 23588
2018-05-29 10:34:36.616524 max RSS 38104
2018-05-29 10:34:36.772978 max RSS 45924
2018-05-29 10:34:36.929688 max RSS 46824
2018-05-29 10:34:37.087554 max RSS 46852
Top prefixes: [('con', 1220), ('dis', 1002), ('pro', 809)]
2018-05-29 10:34:56.281262
Top 3 lines
#1: scratches/scratch.py:36: 6527.0 KiB
    words = list(words)
#2: scratches/scratch.py:38: 16.4 KiB
    prefix = word[:3]
#3: scratches/scratch.py:39: 10.1 KiB
    counts[prefix] += 1
19 other: 10.8 KiB
Total allocated size: 6564.3 KiB

If you're on Linux, you may find /proc/self/statm more useful than the resource module.

SSIS Text was truncated with status value 4

I suspect the or one or more characters had no match in the target code page part of the error.

If you remove the rows with values in that column, does it load? Can you identify, in other words, the rows which cause the package to fail? It could be the data is too long, or it could be that there's some funky character in there SQL Server doesn't like.

How do I get the unix timestamp in C as an int?

With second precision, you can print tv_sec field of timeval structure that you get from gettimeofday() function. For example:

#include <sys/time.h>
#include <stdio.h>

int main()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec);
    return 0;
}

Example of compiling and running:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834

Note, however, that its been a while since epoch and so long int is used to fit a number of seconds these days.

There are also functions to print human-readable times. See this manual page for details. Here goes an example using ctime():

#include <time.h>
#include <stdio.h>

int main()
{
    time_t clk = time(NULL);
    printf("%s", ctime(&clk));
    return 0;
}

Example run & output:

$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 

Java 8 NullPointerException in Collectors.toMap

Here's somewhat simpler collector than proposed by @EmmanuelTouzery. Use it if you like:

public static <T, K, U> Collector<T, ?, Map<K, U>> toMapNullFriendly(
        Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper) {
    @SuppressWarnings("unchecked")
    U none = (U) new Object();
    return Collectors.collectingAndThen(
            Collectors.<T, K, U> toMap(keyMapper,
                    valueMapper.andThen(v -> v == null ? none : v)), map -> {
                map.replaceAll((k, v) -> v == none ? null : v);
                return map;
            });
}

We just replace null with some custom object none and do the reverse operation in the finisher.

How to resolve "must be an instance of string, string given" prior to PHP 7?

As others have already said, type hinting currently only works for object types. But I think the particular error you've triggered might be in preparation of the upcoming string type SplString.

In theory it behaves like a string, but since it is an object would pass the object type verification. Unfortunately it's not yet in PHP 5.3, might come in 5.4, so haven't tested this.

How to search for an element in a golang slice

You can use sort.Slice() plus sort.Search()

type Person struct {
    Name string
}

func main() {
    crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}

    sort.Slice(crowd, func(i, j int) bool {
        return crowd[i].Name <= crowd[j].Name
    })

    needle := "Benni"
    idx := sort.Search(len(crowd), func(i int) bool {
        return string(crowd[i].Name) >= needle
    })

    if crowd[idx].Name == needle {
        fmt.Println("Found:", idx, crowd[idx])
    } else {
        fmt.Println("Found noting: ", idx)
    }
}

See: https://play.golang.org/p/47OPrjKb0g_c

android.content.res.Resources$NotFoundException: String resource ID #0x0

When you try to set text in Edittext or textview you should pass only String format.

dateTime.setText(app.getTotalDl());

to

dateTime.setText(String.valueOf(app.getTotalDl()));

Centering text in a table in Twitter Bootstrap

<td class="text-center">

and fix .text-center in bootstrap.css:

.text-center {
    text-align: center !important;
}

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

How to retrieve the dimensions of a view?

Simple Response: This worked for me with no Problem. It seems the key is to ensure that the View has focus before you getHeight etc. Do this by using the hasFocus() method, then using getHeight() method in that order. Just 3 lines of code required.

ImageButton myImageButton1 =(ImageButton)findViewById(R.id.imageButton1); myImageButton1.hasFocus();

int myButtonHeight = myImageButton1.getHeight();

Log.d("Button Height: ", ""+myButtonHeight );//Not required

Hope it helps.

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

Form.Close() is use to close an instance of a Form with in .NET application it does not kill the entire application. Application.exit() kills your application.

Why does this CSS margin-top style not work?

Try using display: inline-block; on the inner div.

#outer {
    width:500px; 
    height:200px; 
    background:#FFCCCC;
    margin:50px auto 0 auto;
    display:block;
}
#inner {
    background:#FFCC33;
    margin:50px 50px 50px 50px;
    padding:10px;
    display:inline-block;
}

Converting a PDF to PNG

You can use one commandline with two commands (gs, convert) connected through a pipe, if the first command can write its output to stdout, and if the second one can read its input from stdin.

  1. Luckily, gs can write to stdout (... -o %stdout ...).
  2. Luckily, convert can read from stdin (convert -background transparent - output.png).

Problem solved:

  • GS used for alpha channel handling a special image,
  • convert used for creating transparent background,
  • pipe used to avoid writing out a temp file on disk.

Complete solution:

gs -sDEVICE=pngalpha       \
   -o %stdout              \
   -r144 cover.pdf         \
   |                       \
convert                    \
   -background transparent \
   -                       \
    cover.png

Update

If you want to have a separate PNG per PDF page, you can use the %d syntax:

gs -sDEVICE=pngalpha -o file-%03d.png -r144 cover.pdf

This will create PNG files named page-000.png, page-001.png, ... (Note that the %d-counting is zero-based -- file-000.png corresponds to page 1 of the PDF, 001 to page 2...

Or, if you want to keep your transparent background, for a 100-page PDF, do

for i in {1..100}; do        \
                             \
  gs -sDEVICE=pngalpha       \
     -dFirstPage="${i}"      \
     -dLastPage="${i}"       \
     -o %stdout              \
     -r144 input.pdf         \
     |                       \
  convert                    \
     -background transparent \
     -                       \
      page-${i}.png ;        \
                             \
done

Testing the type of a DOM element in JavaScript

Perhaps you'll have to check the nodetype too:

if(element.nodeType == 1){//element of type html-object/tag
  if(element.tagName=="a"){
    //this is an a-element
  }
  if(element.tagName=="div"){
    //this is a div-element
  }
}

Edit: Corrected the nodeType-value

How to use Morgan logger?

I faced the same problem ago and instead, I used winston. As fellas above said, morgan is for automated logging of request/response. Winston can be configured pretty much same way as log4Net/log4J, has severity levels, different streams to which you can log etc.

For example:

npm install winston

Then, if you call the below code somewhere on you application initialization:

var winston = require('winston');

// setup default logger (no category)
winston.loggers.add('default', {
    console: {
        colorize: 'true',
        handleExceptions: true,
        json: false,
        level: 'silly',
        label: 'default',
    },
    file: {
        filename: 'some/path/where/the/log/file/reside/default.log',
        level: 'silly',
        json: false,
        handleExceptions: true,
    },
});

//
// setup logger for category `usersessions`
// you can define as many looggers as you like
//
winston.loggers.add('usersessions', {
    console: {
        level: 'silly',
        colorize: 'true',
        label: 'usersessions',
        json: false,
        handleExceptions: true,
    },
    file: {
        filename: 'some/path/where/the/log/file/reside/usersessions.log',
        level: 'silly',
        json: false,
        handleExceptions: true,
    },
});

note: before calling above code, winston.loggers is empty, i.e you dont have any loggers configured yet. Pretty much like Log4Net/J XmlConfigure methods - you need to first call them, to init your logging.

Then, later wherever in you application server side code you may do:

var winston = require('winston');
// log instances as defined in first snippet
var defaultLog = winston.loggers.get('default'); 
var userSessionsLog = winston.loggers.get('usersessions');

defaultLog.info('this goes to file default.log');
userSessionsLog.debug('this goes to file usersessions.log')

Hope that helps.

for further documentation reference: https://www.npmjs.com/package/winston

How to run a task when variable is undefined in ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword.

tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined

Ansible Documentation

unsigned APK can not be installed

You could also send your testers the apk that is signed with your debug key. You can find that in the bin folder of your project after building in debug mode.

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

Efficiently sorting a numpy array in descending order?

Unfortunately when you have a complex array, only np.sort(temp)[::-1] works properly. The two other methods mentioned here are not effective.

On npm install: Unhandled rejection Error: EACCES: permission denied

sudo chown -R $(whoami) ~/.npm

sudo chown -R $(whoami) ~/.config

Efficient way to determine number of digits in an integer

// Meta-program to calculate number of digits in (unsigned) 'N'.    
template <unsigned long long N, unsigned base=10>
struct numberlength
{   // http://stackoverflow.com/questions/1489830/
    enum { value = ( 1<=N && N<base ? 1 : 1+numberlength<N/base, base>::value ) };
};

template <unsigned base>
struct numberlength<0, base>
{
    enum { value = 1 };
};

{
    assert( (1 == numberlength<0,10>::value) );
}
assert( (1 == numberlength<1,10>::value) );
assert( (1 == numberlength<5,10>::value) );
assert( (1 == numberlength<9,10>::value) );

assert( (4 == numberlength<1000,10>::value) );
assert( (4 == numberlength<5000,10>::value) );
assert( (4 == numberlength<9999,10>::value) );

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

SQL Error: 0, SQLState: 08S01 Communications link failure

Check your server config file /etc/mysql/my.cnf - verify bind_address is not set to 127.0.0.1. Set it to 0.0.0.0 or comment it out then restart server with:

sudo service mysql restart

How to tell PowerShell to wait for each command to end before starting the next?

Some programs can't process output stream very well, using pipe to Out-Null may not block it.
And Start-Process needs the -ArgumentList switch to pass arguments, not so convenient.
There is also another approach.

$exitCode = [Diagnostics.Process]::Start(<process>,<arguments>).WaitForExit(<timeout>)

How to find and restore a deleted file in a Git repository

In order to restore all deleted file with Git, you can also do:

git checkout $(git ls-files --deleted)

Where git ls-files --deleted lists all deleted files and git checkout $(git command) restores the list of files in a parameter.

How do I rename the android package name?

In addition to @Cristian's answer above, I had to do two more steps to get it working correctly. I will sum all of it here:

  1. Change the package name manually in the manifest file.
  2. Click on your R.java class and the press F6 (Refactor->Move...). It will allow you to move the class to another package, and all references to that class will be updated.
  3. Change manually the application Id in the build.gradle file : android / defaultconfig / application ID [source].
  4. Create a new package with the desired name by right clicking on the java folder -> new -> package and select and drag all your classes to the new package. Android Studio will refactor the package name everywhere [source].

What is the difference between #include <filename> and #include "filename"?

#include "filename" // User defined header
#include <filename> // Standard library header.

Example:

The filename here is Seller.h:

#ifndef SELLER_H     // Header guard
#define SELLER_H     // Header guard

#include <string>
#include <iostream>
#include <iomanip>

class Seller
{
    private:
        char name[31];
        double sales_total;

    public:
        Seller();
        Seller(char[], double);
        char*getName();

#endif

In the class implementation (for example, Seller.cpp, and in other files that will use the file Seller.h), the header defined by the user should now be included, as follows:

#include "Seller.h"

How to store Node.js deployment settings/configuration files?

I am a bit late in the game, but I couldn't find what I needed here- or anywhere else - so I wrote something myself.

My requirements for a configuration mechanism are the following:

  1. Support front-end. What is the point if the front-end cannot use the configuration?
  2. Support settings-overrides.js - which looks the same but allows overrides of configuration at settings.js. The idea here is to modify configuration easily without changing the code. I find it useful for saas.

Even though I care less about supporting environments - the will explain how to add it easily to my solution

var publicConfiguration = {
    "title" : "Hello World"
    "demoAuthToken" : undefined, 
    "demoUserId" : undefined, 
    "errorEmail" : null // if null we will not send emails on errors. 

};

var privateConfiguration = {
    "port":9040,
    "adminAuthToken":undefined,
    "adminUserId":undefined
}

var meConf = null;
try{
    meConf = require("../conf/dev/meConf");
}catch( e ) { console.log("meConf does not exist. ignoring.. ")}




var publicConfigurationInitialized = false;
var privateConfigurationInitialized = false;

function getPublicConfiguration(){
    if (!publicConfigurationInitialized) {
        publicConfigurationInitialized = true;
        if (meConf != null) {
            for (var i in publicConfiguration) {
                if (meConf.hasOwnProperty(i)) {
                    publicConfiguration[i] = meConf[i];
                }
            }
        }
    }
    return publicConfiguration;
}


function getPrivateConfiguration(){
    if ( !privateConfigurationInitialized ) {
        privateConfigurationInitialized = true;

        var pubConf = getPublicConfiguration();

        if ( pubConf != null ){
            for ( var j in pubConf ){
                privateConfiguration[j] = pubConf[j];
            }
        }
        if ( meConf != null ){
              for ( var i in meConf ){
                  privateConfiguration[i] = meConf[i];
              }
        }
    }
    return privateConfiguration;

}


exports.sendPublicConfiguration = function( req, res ){
    var name = req.param("name") || "conf";

    res.send( "window." + name + " = " + JSON.stringify(getPublicConfiguration()) + ";");
};


var prConf = getPrivateConfiguration();
if ( prConf != null ){
    for ( var i in prConf ){
        if ( prConf[i] === undefined ){

            throw new Error("undefined configuration [" + i + "]");
        }
        exports[i] = prConf[i];
    }
}


return exports;

Explanation

  • undefined means this property is required
  • null means it is optional
  • meConf - currently the code is target to a file under app. meConf is the overrides files which is targeted to conf/dev - which is ignored by my vcs.
  • publicConfiguration - will be visible from front-end and back-end.
  • privateConfiguration - will be visible from back-end only.
  • sendPublicConfiguration - a route that will expose the public configuration and assign it to a global variable. For example the code below will expose the public configuration as global variable myConf in the front-end. By default it will use the global variable name conf.

    app.get("/backend/conf", require("conf").sendPublicConfiguration);

Logic of overrides

  • privateConfiguration is merged with publicConfiguration and then meConf.
  • publicConfiguration checks each key if it has an override, and uses that override. This way we are not exposing anything private.

Adding environment support

Even though I don't find an "environment support" useful, maybe someone will.

To add environment support you need to change the meConf require statement to something like this (pseudocode)

if ( environment == "production" ) { meConf = require("../conf/dev/meConf").production; }

if ( environment == "development" ) { meConf = require("../conf/dev/meConf").development; }

Similarly you can have a file per environment

 meConf.development.js
 meConf.production.js

and import the right one. The rest of the logic stays the same.

Is it possible to have a default parameter for a mysql stored procedure?

Unfortunately, MySQL doesn't support DEFAULT parameter values, so:

CREATE PROCEDURE `blah`
(
  myDefaultParam int DEFAULT 0
)
BEGIN
  -- Do something here
END

returns the error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use 
near 'DEFAULT 0) BEGIN END' at line 3

To work around this limitation, simply create additional procedures that assign default values to the original procedure:

DELIMITER //

DROP PROCEDURE IF EXISTS blah//
DROP PROCEDURE IF EXISTS blah2//
DROP PROCEDURE IF EXISTS blah1//
DROP PROCEDURE IF EXISTS blah0//

CREATE PROCEDURE blah(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    SELECT param1, param2;
END;
//

CREATE PROCEDURE blah2(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
    CALL blah(param1, param2);
END;
//

CREATE PROCEDURE blah1(param1 INT UNSIGNED)
BEGIN
    CALL blah2(param1, 3);
END;
//

CREATE PROCEDURE blah0()
BEGIN
    CALL blah1(4);
END;
//

Then, running this:

CALL blah(1, 1);
CALL blah2(2, 2);
CALL blah1(3);
CALL blah0();

will return:

+--------+--------+
| param1 | param2 |
+--------+--------+
|      1 |      1 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      2 |      2 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      3 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

+--------+--------+
| param1 | param2 |
+--------+--------+
|      4 |      3 |
+--------+--------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Then, if you make sure to only use the blah2(), blah1() and blah0() procedures, your code will not need to be immediately updated, when you add a third parameter to the blah() procedure.

angularjs make a simple countdown

function timerCtrl ($scope,$interval) {
    $scope.seconds = 0;
    var timer = $interval(function(){
        $scope.seconds++;
        $scope.$apply();
        console.log($scope.countDown);
    }, 1000);
}

Make a phone call programmatically

Swift

if let url = NSURL(string: "tel://\(number)"), 
    UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

Converting a SimpleXML Object to an Array

Just (array) is missing in your code before the simplexml object:

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

How do you do natural logs (e.g. "ln()") with numpy in Python?

You could simple just do the reverse by making the base of log to e.

import math

e = 2.718281

math.log(e, 10) = 2.302585093
ln(10) = 2.30258093

Creating composite primary key in SQL Server

How about this:

ALTER TABLE dbo.testRequest
ADD CONSTRAINT PK_TestRequest 
PRIMARY KEY (wardNo, BHTNo, TestID) 

How to convert the background to transparent?

Quick solution without downloading anything is to use online editors that has "Magic Wand Tool".

converting list to json format - quick and easy way

I would avoid rolling your own and use either:

System.Web.Script.JavascriptSerializer

or

JSON.net

Both will do an excellent job :)

Node.js Generate html

You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.

Change auto increment starting number?

If you need this procedure for variable fieldnames instead of id this might be helpful:

DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(128), _fieldname VARCHAR(128))
BEGIN
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(',_fieldname,'), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;
    DEALLOCATE PREPARE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END //
DELIMITER ;

CALL update_auto_increment('your_table_name', 'autoincrement_fieldname');

Why rgb and not cmy?

The difference lies in whether mixing colours results in LIGHTER or DARKER colours. When mixing light, the result is a lighter colour, so mixing red light and blue light becomes a lighter pink. When mixing paint (or ink), red and blue become a darker purple. Mixing paint results in DARKER colours, whereas mixing light results in LIGHTER colours. Therefore for paint the primary colours are Red Yellow Blue (or Cyan Magenta Yellow) as you stated. Yet for light the primary colours are Red Green Blue. It is (virtually) impossible to mix Red Green Blue paint into Yellow paint, or mixing Red Yellow Blue light into Green light.

how to call url of any other website in php

If you meant .. to REDIRECT from that page to another, the function is really simple

header("Location:www.google.com");

jQuery append() - return appended elements

There's a simpler way to do this:

$(newHtml).appendTo('#myDiv').effects(...);

This turns things around by first creating newHtml with jQuery(html [, ownerDocument ]), and then using appendTo(target) (note the "To" bit) to add that it to the end of #mydiv.

Because you now start with $(newHtml) the end result of appendTo('#myDiv') is that new bit of html, and the .effects(...) call will be on that new bit of html too.

How to retrieve a user environment variable in CMake (Windows)

Getting variables into your CMake script

You can pass a variable on the line with the cmake invocation:

FOO=1 cmake

or by exporting a variable in BASH:

export FOO=1

Then you can pick it up in a cmake script using:

$ENV{FOO}

Install MySQL on Ubuntu without a password prompt

Use:

sudo DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server

sudo mysql -h127.0.0.1 -P3306 -uroot -e"UPDATE mysql.user SET password = PASSWORD('yourpassword') WHERE user = 'root'"

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

Add text at the end of each line

If you'd like to add text at the end of each line in-place (in the same file), you can use -i parameter, for example:

sed -i'.bak' 's/$/:80/' foo.txt

However -i option is non-standard Unix extension and may not be available on all operating systems.

So you can consider using ex (which is equivalent to vi -e/vim -e):

ex +"%s/$/:80/g" -cwq foo.txt

which will add :80 to each line, but sometimes it can append it to blank lines.

So better method is to check if the line actually contain any number, and then append it, for example:

ex  +"g/[0-9]/s/$/:80/g" -cwq foo.txt

If the file has more complex format, consider using proper regex, instead of [0-9].

Clear screen in shell

using windows 10 and pyhton3.5 i have tested many codes and nothing helped me more than this:

First define a simple function, this funtion will print 50 newlines;(the number 50 will depend on how many lines you can see on your screen, so you can change this number)

def cls(): print ("\n" * 50)

then just call it as many times as you want or need

cls()

Get response from PHP file using AJAX

<?php echo 'apple'; ?> is pretty much literally all you need on the server.

as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have

success: function(data) {
   alert(data); // apple
}

Mean of a column in a data frame, given the column's name

I think you're asking how to compute the mean of a variable in a data frame, given the name of the column. There are two typical approaches to doing this, one indexing with [[ and the other indexing with [:

data(iris)
mean(iris[["Petal.Length"]])
# [1] 3.758
mean(iris[,"Petal.Length"])
# [1] 3.758
mean(iris[["Sepal.Width"]])
# [1] 3.057333
mean(iris[,"Sepal.Width"])
# [1] 3.057333

How to set a default Value of a UIPickerView

I too had this problem. But apparently there is an issue of the order of method calls. You must call:

[self.picker selectRow:2 inComponent:0 animated:YES];

after calling

[self.view addSubview:self.picker];

Required maven dependencies for Apache POI to work

Add this dependency to work with Apache POI

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.16-beta1</version>
 </dependency>

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

How to list all the files in android phone by using adb shell?

Open cmd type adb shell then press enter. Type ls to view files list.

Defining lists as global variables in Python

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

How can I control the width of a label tag?

You can definitely try this way

.col-form-label{
  display: inline-block;
  width:200px;}

Displaying a message in iOS which has the same functionality as Toast in Android

You can make use of MBProgressHUD project.

Use HUD mode MBProgressHUDModeText for toast-like behaviour,

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

// Configure for text only and offset down
hud.mode = MBProgressHUDModeText;
hud.label.text = @"Some message...";
hud.margin = 10.f;
hud.yOffset = 150.f;
hud.removeFromSuperViewOnHide = YES;

[hud hideAnimated:YES afterDelay:3];

enter image description here

how to find seconds since 1970 in java

Another option is to use the TimeUtils utility method:

TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)

Write-back vs Write-Through caching?

The benefit of write-through to main memory is that it simplifies the design of the computer system. With write-through, the main memory always has an up-to-date copy of the line. So when a read is done, main memory can always reply with the requested data.

If write-back is used, sometimes the up-to-date data is in a processor cache, and sometimes it is in main memory. If the data is in a processor cache, then that processor must stop main memory from replying to the read request, because the main memory might have a stale copy of the data. This is more complicated than write-through.

Also, write-through can simplify the cache coherency protocol because it doesn't need the Modify state. The Modify state records that the cache must write back the cache line before it invalidates or evicts the line. In write-through a cache line can always be invalidated without writing back since memory already has an up-to-date copy of the line.

One more thing - on a write-back architecture software that writes to memory-mapped I/O registers must take extra steps to make sure that writes are immediately sent out of the cache. Otherwise writes are not visible outside the core until the line is read by another processor or the line is evicted.

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

Angular 2 'component' is not a known element

I just had the exact same issue. Before trying some of the solutions posted here, you might want to check if the component really doesn't work. For me, the error was shown in my IDE (WebStorm), but it turned out that the code worked perfectly when i ran it in the browser.

After I shut down the terminal (that was running ng serve) and restarted my IDE, the message stopped showing up.

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

I got same issue on Catalina mac. I also installed the R from the source in following diretory. ./Documents/R-4.0.3

Now from the terminal type

 ls -a 

and open

 vim .bash_profile 

type

export LANG="en_US.UTF-8"

save with :wq

then type

source .bash_profile 

and then open

./Documents/R-4.0.3/bin/R 
./Documents/R-4.0.3/bin/Rscript 

I always have to run "source /Users/yourComputerName/.bash_profile" before running R scripts.

FileProvider - IllegalArgumentException: Failed to find configured root

I noticed that the policy or behaviour regarding the path.xml file changed between Support Library 26 and 27. For capturing a picture from the camera, I saw the following changes:

  • With 26, I had to use <external-path> and the full path given in the path argument.

  • With 27, I had to use <external-files-path> and only the subfolder in the path argument.

So what specifically worked for me with Support Library 27 as the path.xml file was

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-files-path name="camera_image" path="Pictures/"/>
</paths>

SQL Add foreign key to existing column

If the table has already been created:

First do:

ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);

Then:

ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);

How to change default format at created_at and updated_at value laravel

{{ $post->created_at }}

will return '2014-06-26 04:07:31'

The solution is

{{ $post->created_at->format('Y-m-d') }}

How to parse a JSON string to an array using Jackson

I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]

Swift convert unix time to date and time

To get the date to show as the current time zone I used the following.

if let timeResult = (jsonResult["dt"] as? Double) {
     let date = NSDate(timeIntervalSince1970: timeResult)
     let dateFormatter = NSDateFormatter()
     dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle //Set time style
     dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle //Set date style
     dateFormatter.timeZone = NSTimeZone()
     let localDate = dateFormatter.stringFromDate(date)
}

Swift 3.0 Version

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = self.timeZone
    let localDate = dateFormatter.string(from: date)                     
}

Swift 5

if let timeResult = (jsonResult["dt"] as? Double) {
    let date = Date(timeIntervalSince1970: timeResult)
    let dateFormatter = DateFormatter()
    dateFormatter.timeStyle = DateFormatter.Style.medium //Set time style
    dateFormatter.dateStyle = DateFormatter.Style.medium //Set date style
    dateFormatter.timeZone = .current
    let localDate = dateFormatter.string(from: date)                                
}

How can I include a YAML file inside another?

I make some examples for your reference.

import yaml

main_yaml = """
Package:
 - !include _shape_yaml    
 - !include _path_yaml
"""

_shape_yaml = """
# Define
Rectangle: &id_Rectangle
    name: Rectangle
    width: &Rectangle_width 20
    height: &Rectangle_height 10
    area: !product [*Rectangle_width, *Rectangle_height]

Circle: &id_Circle
    name: Circle
    radius: &Circle_radius 5
    area: !product [*Circle_radius, *Circle_radius, pi]

# Setting
Shape:
    property: *id_Rectangle
    color: red
"""

_path_yaml = """
# Define
Root: &BASE /path/src/

Paths: 
    a: &id_path_a !join [*BASE, a]
    b: &id_path_b !join [*BASE, b]

# Setting
Path:
    input_file: *id_path_a
"""


# define custom tag handler
def yaml_import(loader, node):
    other_yaml_file = loader.construct_scalar(node)
    return yaml.load(eval(other_yaml_file), Loader=yaml.SafeLoader)


def yaml_product(loader, node):
    import math
    list_data = loader.construct_sequence(node)
    result = 1
    pi = math.pi
    for val in list_data:
        result *= eval(val) if isinstance(val, str) else val
    return result


def yaml_join(loader, node):
    seq = loader.construct_sequence(node)
    return ''.join([str(i) for i in seq])


def yaml_ref(loader, node):
    ref = loader.construct_sequence(node)
    return ref[0]


def yaml_dict_ref(loader: yaml.loader.SafeLoader, node):
    dict_data, key, const_value = loader.construct_sequence(node)
    return dict_data[key] + str(const_value)


def main():
    # register the tag handler
    yaml.SafeLoader.add_constructor(tag='!include', constructor=yaml_import)
    yaml.SafeLoader.add_constructor(tag='!product', constructor=yaml_product)
    yaml.SafeLoader.add_constructor(tag='!join', constructor=yaml_join)
    yaml.SafeLoader.add_constructor(tag='!ref', constructor=yaml_ref)
    yaml.SafeLoader.add_constructor(tag='!dict_ref', constructor=yaml_dict_ref)

    config = yaml.load(main_yaml, Loader=yaml.SafeLoader)

    pk_shape, pk_path = config['Package']
    pk_shape, pk_path = pk_shape['Shape'], pk_path['Path']
    print(f"shape name: {pk_shape['property']['name']}")
    print(f"shape area: {pk_shape['property']['area']}")
    print(f"shape color: {pk_shape['color']}")

    print(f"input file: {pk_path['input_file']}")


if __name__ == '__main__':
    main()

output

shape name: Rectangle
shape area: 200
shape color: red
input file: /path/src/a

Update 2

and you can combine it, like this

# xxx.yaml
CREATE_FONT_PICTURE:
  PROJECTS:
    SUNG: &id_SUNG
      name: SUNG
      work_dir: SUNG
      output_dir: temp
      font_pixel: 24


  DEFINE: &id_define !ref [*id_SUNG]  # you can use config['CREATE_FONT_PICTURE']['DEFINE'][name, work_dir, ... font_pixel]
  AUTO_INIT:
    basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # SUNG30

# ? This is not correct.
# basename_suffix: !dict_ref [*id_define, name, !product [5, 3, 2]]  # It will build by Deep-level. id_define is Deep-level: 2. So you must put it after 2. otherwise, it can't refer to the correct value.

Is there a way to get the source code from an APK file?

apktool is the best thing you can try. I have saved some xml with it, but honestly I don't know how it will work with the .java code.

I would recommend you to have a code repository even if your are the only coder. I've been using Project Locker for my own projects. It gives you free svn and git repos.

Cordova - Error code 1 for command | Command failed for

Delete all the apk files from platfroms >> android >> build >> generated >> outputs >> apk and run command cordova run android

How do you implement a re-try-catch?

Here is my solution similar to some others can wrap a function, but allows you to get the functions return value, if it suceeds.

    /**
     * Wraps a function with retry logic allowing exceptions to be caught and retires made.
     *
     * @param function the function to retry
     * @param maxRetries maximum number of retires before failing
     * @param delay time to wait between each retry
     * @param allowedExceptionTypes exception types where if caught a retry will be performed
     * @param <V> return type of the function
     * @return the value returned by the function if successful
     * @throws Exception Either an unexpected exception from the function or a {@link RuntimeException} if maxRetries is exceeded
     */
    @SafeVarargs
    public static <V> V runWithRetriesAndDelay(Callable<V> function, int maxRetries, Duration delay, Class<? extends Exception>... allowedExceptionTypes) throws Exception {
        final Set<Class<? extends Exception>> exceptions = new HashSet<>(Arrays.asList(allowedExceptionTypes));
        for(int i = 1; i <= maxRetries; i++) {
            try {
                return function.call();
            } catch (Exception e) {
                if(exceptions.contains(e.getClass())){
                    // An exception of an expected type
                    System.out.println("Attempt [" + i + "/" + maxRetries + "] Caught exception [" + e.getClass() + "]");
                    // Pause for the delay time
                    Thread.sleep(delay.toMillis());
                }else {
                    // An unexpected exception type
                    throw e;
                }
            }
        }
        throw new RuntimeException(maxRetries + " retries exceeded");
    }

How can I get a user's media from Instagram without authenticating as a user?

The Instagram API requires user authentication through OAuth to access the recent media endpoint for a user. There doesn't appear to be any other way right now to get all media for a user.

Could not create work tree dir 'example.com'.: Permission denied

I was facing same issue then I read first few lines of this question and I realised that I was trying to run command at the root directory of my bash profile instead of CD/my work project folder. I switched back to my work folder and able to clone the project successfully

How to indent HTML tags in Notepad++

On Notepadd++ v7.5.9 (32-bits), "Indent by fold" plugin is working fine with html content.

  1. Search and install in plugin manager
  2. Use "Plugins" > "Indent by fold" > "Reindent file"

https://www.fesevur.com/indentbyfold/

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

Google Gson - deserialize list<class> object? (generic type)

Refer to example 2 for 'Type' class understanding of Gson.

Example 1: In this deserilizeResturant we used Employee[] array and get the details

public static void deserializeResturant(){

       String empList ="[{\"name\":\"Ram\",\"empId\":1},{\"name\":\"Surya\",\"empId\":2},{\"name\":\"Prasants\",\"empId\":3}]";
       Gson gson = new Gson();
       Employee[] emp = gson.fromJson(empList, Employee[].class);
       int numberOfElementInJson = emp.length();
       System.out.println("Total JSON Elements" + numberOfElementInJson);
       for(Employee e: emp){
           System.out.println(e.getName());
           System.out.println(e.getEmpId());
       }
   }

Example 2:

//Above deserilizeResturant used Employee[] array but what if we need to use List<Employee>
public static void deserializeResturantUsingList(){

    String empList ="[{\"name\":\"Ram\",\"empId\":1},{\"name\":\"Surya\",\"empId\":2},{\"name\":\"Prasants\",\"empId\":3}]";
    Gson gson = new Gson();

    // Additionally we need to se the Type then only it accepts List<Employee> which we sent here empTypeList
    Type empTypeList = new TypeToken<ArrayList<Employee>>(){}.getType();


    List<Employee> emp = gson.fromJson(empList, empTypeList);
    int numberOfElementInJson = emp.size();
    System.out.println("Total JSON Elements" + numberOfElementInJson);
    for(Employee e: emp){
        System.out.println(e.getName());
        System.out.println(e.getEmpId());
    }
}

String.equals() with multiple conditions (and one action on result)

if (Arrays.asList("John", "Mary", "Peter").contains(name)) {
}
  • This is not as fast as using a prepared Set, but it performs no worse than using OR.
  • This doesn't crash when name is NULL (same with Set).
  • I like it because it looks clean

How can I find the number of days between two Date objects in Ruby?

This worked for me:

(endDate - beginDate).to_i

What is the difference between float and double?

There are three floating point types:

  • float
  • double
  • long double

A simple Venn diagram will explain about: The set of values of the types

enter image description here

How to scanf only integer?

Try using the following pattern in scanf. It will read until the end of the line:

scanf("%d\n", &n)

You won't need the getchar() inside the loop since scanf will read the whole line. The floats won't match the scanf pattern and the prompt will ask for an integer again.

How to recognize vehicle license / number plate (ANPR) from an image?

I have done some googling about this a couple of months ago. There are quite a few papers about this topic, but I never found any concrete open-source implementation. There are a lot of commercial implementations though, but none of them with a price quote, so they're probably pretty expensive.

How to call getClass() from a static method in Java?

Try it

Thread.currentThread().getStackTrace()[1].getClassName()

Or

Thread.currentThread().getStackTrace()[2].getClassName()

jQuery ID starts with

Here you go:

$('td[id^="' + value +'"]')

so if the value is for instance 'foo', then the selector will be 'td[id^="foo"]'.

Note that the quotes are mandatory: [id^="...."].

Source: http://api.jquery.com/attribute-starts-with-selector/

Initialise a list to a specific length in Python

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

get original element from ng-click

You need $event.currentTarget instead of $event.target.

How to install Selenium WebDriver on Mac OS

To use the java -jar selenium-server-standalone-2.45.0.jar command-line tool you need to install a JDK. You need to download and install the JDK and the standalone selenium server.

Total width of element (including padding and border) in jQuery

$(document).ready(function(){     
$("div.width").append($("div.width").width()+" px");
$("div.innerWidth").append($("div.innerWidth").innerWidth()+" px");   
$("div.outerWidth").append($("div.outerWidth").outerWidth()+" px");         
});


<div class="width">Width of this div container without including padding is: </div>  
<div class="innerWidth">width of this div container including padding is: </div> 
<div class="outerWidth">width of this div container including padding and margin is:     </div>

HTML5 Canvas vs. SVG vs. div

For your purposes, I recommend using SVG, since you get DOM events, like mouse handling, including drag and drop, included, you don't have to implement your own redraw, and you don't have to keep track of the state of your objects. Use Canvas when you have to do bitmap image manipulation and use a regular div when you want to manipulate stuff created in HTML. As to performance, you'll find that modern browsers are now accelerating all three, but that canvas has received the most attention so far. On the other hand, how well you write your javascript is critical to getting the most performance with canvas, so I'd still recommend using SVG.

Different ways of clearing lists

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []

Python list directory, subdirectory, and files

Since every example here is just using walk (with join), i'd like to show a nice example and comparison with listdir:

import os, time

def listFiles1(root): # listdir
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0)+"/"; items = os.listdir(folder) # items = folders + files
        for i in items: i=folder+i; (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles2(root): # listdir/join (takes ~1.4x as long) (and uses '\\' instead)
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0); items = os.listdir(folder) # items = folders + files
        for i in items: i=os.path.join(folder,i); (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles3(root): # walk (takes ~1.5x as long)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[folder.replace("\\","/")+"/"+file] # folder+"\\"+file still ~1.5x
    return allFiles

def listFiles4(root): # walk/join (takes ~1.6x as long) (and uses '\\' instead)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[os.path.join(folder,file)]
    return allFiles


for i in range(100): files = listFiles1("src") # warm up

start = time.time()
for i in range(100): files = listFiles1("src") # listdir
print("Time taken: %.2fs"%(time.time()-start)) # 0.28s

start = time.time()
for i in range(100): files = listFiles2("src") # listdir and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.38s

start = time.time()
for i in range(100): files = listFiles3("src") # walk
print("Time taken: %.2fs"%(time.time()-start)) # 0.42s

start = time.time()
for i in range(100): files = listFiles4("src") # walk and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.47s

So as you can see for yourself, the listdir version is much more efficient. (and that join is slow)

TypeError: 'float' object is not subscriptable

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
for i,price in enumerate(PriceList):
  PriceList[i] = PizzaChange + 3*int(i>=7)

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

How to match letters only using java regex, matches method?

[A-Za-z ]* to match letters and spaces.

Sql query to insert datetime in SQL Server

You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.

insert into table1(approvaldate)values('20120618 10:34:09 AM');

If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.

insert into table1 (approvaldate)
       values (convert(datetime,'18-06-12 10:34:09 PM',5));

5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.

Count how many files in directory PHP

<?php echo(count(array_slice(scandir($directory),2))); ?>

array_slice works similary like substr function, only it works with arrays.

For example, this would chop out first two array keys from array:

$key_zero_one = array_slice($someArray, 0, 2);

And if You ommit the first parameter, like in first example, array will not contain first two key/value pairs *('.' and '..').

Set up adb on Mac OS X

After trying all the solutions, none of them where working for me.

In my case I had the Android Studio and the adb was correctly working but the Android Studio was not capable to detect the adb. These was because I installed it with homebrew in another directory, not the /Users/$USER/Library/Android/sdk but Usr/Library blabla

Apparently AS needed to have it in his route /Users/$USER/Library/Android/sdk (same place as in preferences SDK installation route)

So I deleted all the adb from my computer (I installed several) and executed these terminal commands:

echo 'export ANDROID_HOME=/Users/$USER/Library/Android/sdk' >> ~/.bash_profile
echo 'export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools' >> ~/.bash_profile
source ~/.bash_profile
adb devices

Well, after that, still wasn't working, because for some reason the route for the adb was /Users/$USER/Library/Android/sdk/platform-tools/platform-tools (yes, repeated) so I just copied the last platform-tools into the first directory with all the license files and started working.

Weird but true

Creating a UICollectionView programmatically

You can handle custom cell in uicollection view see below code.enter image description here

- (void)viewDidLoad
{
  UINib *nib2 = [UINib nibWithNibName:@"YourCustomCell" bundle:nil];
    [CollectionVW registerNib:nib2 forCellWithReuseIdentifier:@"YourCustomCell"];


    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setItemSize:CGSizeMake(200, 230)];
    flowLayout.minimumInteritemSpacing = 0;
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    [CollectionVW setCollectionViewLayout:flowLayout];

    [CollectionVW reloadData];
}

#pragma mark - COLLECTIONVIEW
#pragma mark Collection View CODE

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return Array.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"YourCustomCell";
    YourCustomCell *cell = (YourCustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    cell.MainIMG.image=[UIImage imageNamed:[Array objectAtIndex:indexPath.row]];


    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}

#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize mElementSize;
    mElementSize=CGSizeMake(kScreenWidth/3.4, 150);
    return mElementSize;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 5.0;
}

// Layout: Set Edges
- (UIEdgeInsets)collectionView: (UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (isIphone5 || isiPhone4)
    {
        return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
    }
    else if (isIphone6)
    {
        return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
    }
    else if (isIphone6P)
    {
        return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
    }

    return UIEdgeInsetsMake(15,15,5,15);  // top, left, bottom, right
}

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

$lookup on ObjectId's in an array

Aggregating with $lookup and subsequent $group is pretty cumbersome, so if (and that's a medium if) you're using node & Mongoose or a supporting library with some hints in the schema, you could use a .populate() to fetch those documents:

var mongoose = require("mongoose"),
    Schema = mongoose.Schema;

var productSchema = Schema({ ... });

var orderSchema = Schema({
  _id     : Number,
  products: [ { type: Schema.Types.ObjectId, ref: "Product" } ]
});

var Product = mongoose.model("Product", productSchema);
var Order   = mongoose.model("Order", orderSchema);

...

Order
    .find(...)
    .populate("products")
    ...

Passing Objects By Reference or Value in C#

When you pass the the System.Drawing.Image type object to a method you are actually passing a copy of reference to that object.

So if inside that method you are loading a new image you are loading using new/copied reference. You are not making change in original.

YourMethod(System.Drawing.Image image)
{
    //now this image is a new reference
    //if you load a new image 
    image = new Image()..
    //you are not changing the original reference you are just changing the copy of original reference
}

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Detect whether current Windows version is 32 bit or 64 bit

Answer for Newer Versions of Windows

Today, I posted some code on another question and an explanation of how to do this with IsWow64Process2 for Windows 10 version 1511 or later and Windows Server 2016. Additionally, the code determines if the process is 32 or 64 bit and whether the process is running under the WOW64 emulator.

One of the main reasons I have posted the answer is because while there were several suggestions to use IsWow64Process2, no code that I saw showed how.

Please see the answer here: https://stackoverflow.com/a/59377888/1691559

How can I pass arguments to anonymous functions in JavaScript?

The delegates:

function displayMessage(message, f)
{
    f(message); // execute function "f" with variable "message"
}

function alerter(message)
{
    alert(message);
}

function writer(message)
{
    document.write(message);
}

Running the displayMessage function:

function runDelegate()
{
    displayMessage("Hello World!", alerter); // alert message

    displayMessage("Hello World!", writer); // write message to DOM
}

Swipe ListView item From right to left show delete button

see there link was very nice and simple. its working fine... u don't want any library its working fine. click here

OnTouchListener gestureListener = new View.OnTouchListener() {
    private int padding = 0;
    private int initialx = 0;
    private int currentx = 0;
    private  ViewHolder viewHolder;

    public boolean onTouch(View v, MotionEvent event) {
        if ( event.getAction() == MotionEvent.ACTION_DOWN) {
            padding = 0;
            initialx = (int) event.getX();
            currentx = (int) event.getX();
            viewHolder = ((ViewHolder) v.getTag());
        }
        if ( event.getAction() == MotionEvent.ACTION_MOVE) {
            currentx = (int) event.getX();
            padding = currentx - initialx;
        }       
        if ( event.getAction() == MotionEvent.ACTION_UP || 
                     event.getAction() == MotionEvent.ACTION_CANCEL) {
            padding = 0;
            initialx = 0;
            currentx = 0;
        }
        if(viewHolder != null) {
            if(padding == 0) {
                v.setBackgroundColor(0xFF000000 );  
                if(viewHolder.running)
                    v.setBackgroundColor(0xFF058805);
            }
            if(padding > 75) {
                viewHolder.running = true;
                v.setBackgroundColor(0xFF00FF00 );  
                viewHolder.icon.setImageResource(R.drawable.clock_running);
            }
            if(padding < -75) {
                viewHolder.running = false;
                v.setBackgroundColor(0xFFFF0000 );  
            }

            v.setPadding(padding, 0,0, 0);
        }

        return true;
    }
};

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

How to use PHP OPCache?

Installation

OpCache is compiled by default on PHP5.5+. However it is disabled by default. In order to start using OpCache in PHP5.5+ you will first have to enable it. To do this you would have to do the following.

Add the following line to your php.ini:

zend_extension=/full/path/to/opcache.so (nix)
zend_extension=C:\path\to\php_opcache.dll (win)

Note that when the path contains spaces you should wrap it in quotes:

zend_extension="C:\Program Files\PHP5.5\ext\php_opcache.dll"

Also note that you will have to use the zend_extension directive instead of the "normal" extension directive because it affects the actual Zend engine (i.e. the thing that runs PHP).

Usage

Currently there are four functions which you can use:

opcache_get_configuration():

Returns an array containing the currently used configuration OpCache uses. This includes all ini settings as well as version information and blacklisted files.

var_dump(opcache_get_configuration());

opcache_get_status():

This will return an array with information about the current status of the cache. This information will include things like: the state the cache is in (enabled, restarting, full etc), the memory usage, hits, misses and some more useful information. It will also contain the cached scripts.

var_dump(opcache_get_status());

opcache_reset():

Resets the entire cache. Meaning all possible cached scripts will be parsed again on the next visit.

opcache_reset();

opcache_invalidate():

Invalidates a specific cached script. Meaning the script will be parsed again on the next visit.

opcache_invalidate('/path/to/script/to/invalidate.php', true);

Maintenance and reports

There are some GUI's created to help maintain OpCache and generate useful reports. These tools leverage the above functions.

OpCacheGUI

Disclaimer I am the author of this project

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Multilingual
  • Mobile device support
  • Shiny graphs

Screenshots:

status

cached-scripts

graphs

mobilr

URL: https://github.com/PeeHaa/OpCacheGUI

opcache-status

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • Cached scripts overview
  • Single file

Screenshot:

status

URL: https://github.com/rlerdorf/opcache-status

opcache-gui

Features:

  • OpCache status
  • OpCache configuration
  • OpCache statistics
  • OpCache reset
  • Cached scripts overview
  • Cached scripts invalidation
  • Automatic refresh

Screenshot:

opcache-gui-overview

URL: https://github.com/amnuts/opcache-gui