Programs & Examples On #Core video

Core Video is a pipeline model for digital video in MacOS X 10.4, iOS 4.0 and above.

How to add image to canvas

here is the sample code to draw image on canvas-

$("#selectedImage").change(function(e) {

var URL = window.URL;
var url = URL.createObjectURL(e.target.files[0]);
img.src = url;

img.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");        

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(img, 0, 0, 500, 500);
}});

In the above code selectedImage is an input control which can be used to browse image on system. For more details of sample code to draw image on canvas while maintaining the aspect ratio:

http://newapputil.blogspot.in/2016/09/show-image-on-canvas-html5.html

How to get char from string by index?

In [1]: x = "anmxcjkwnekmjkldm!^%@(*)#_+@78935014712jksdfs"
In [2]: len(x)
Out[2]: 45

Now, For positive index ranges for x is from 0 to 44 (i.e. length - 1)

In [3]: x[0]
Out[3]: 'a'
In [4]: x[45]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)

/home/<ipython console> in <module>()

IndexError: string index out of range

In [5]: x[44]
Out[5]: 's'

For Negative index, index ranges from -1 to -45

In [6]: x[-1]
Out[6]: 's'
In [7]: x[-45]
Out[7]: 'a

For negative index, negative [length -1] i.e. the last valid value of positive index will give second list element as the list is read in reverse order,

In [8]: x[-44]
Out[8]: 'n'

Other, index's examples,

In [9]: x[1]
Out[9]: 'n'
In [10]: x[-9]
Out[10]: '7'

How do I determine if my python shell is executing in 32bit or 64bit?

Do a python -VV in the command line. It should return the version.

How to delete zero components in a vector in Matlab?

Why not just, a=a(~~a) or a(~a)=[]. It's equivalent to the other approaches but certainly less key strokes.

Make the console wait for a user input to close

In Java this would be System.in.read()

Why is using a wild card with a Java import statement bad?

  1. It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
  2. It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
  3. It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
  4. The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.

Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.

Google Maps JS API v3 - Simple Multiple Marker Example

Add a marker in your program is very easy. You just may add this code:

var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  title: 'Hello World!'
});

The following fields are particularly important and commonly set when you construct a marker:

  • position (required) specifies a LatLng identifying the initial location of the marker. One way of retrieving a LatLng is by using the Geocoding service.
  • map (optional) specifies the Map on which to place the marker. If you do not specify a map on construction of the marker, the marker is created but is not attached to (or displayed on) the map. You may add the marker later by calling the marker's setMap() method.

Note, in the example, the title field set the marker's title who will appear as a tooltip.

You may consult the Google api documenation here.


This is a complete example to set one marker in a map. Be care full, you have to replace YOUR_API_KEY by your google API key:

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
   <meta charset="utf-8">
   <title>Simple markers</title>
<style>
  /* Always set the map height explicitly to define the size of the div
   * element that contains the map. */
  #map {
    height: 100%;
  }
  /* Optional: Makes the sample page fill the window. */
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
</style>
</head>
<body>
 <div id="map"></div>
<script>

  function initMap() {
    var myLatLng = {lat: -25.363, lng: 131.044};

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'Hello World!'
    });
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>


Now, if you want to plot markers of an array in a map, you should do like this:

var locations = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function initMap() {
  var myLatLng = {lat: -33.90, lng: 151.16};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: myLatLng
    });

  var count;

  for (count = 0; count < locations.length; count++) {  
    new google.maps.Marker({
      position: new google.maps.LatLng(locations[count][1], locations[count][2]),
      map: map,
      title: locations[count][0]
      });
   }
}

This example give me the following result:

enter image description here


You can, also, add an infoWindow in your pin. You just need this code:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[count][1], locations[count][2]),
    map: map
    });

marker.info = new google.maps.InfoWindow({
    content: 'Hello World!'
    });

You can have the Google's documentation about infoWindows here.


Now, we can open the infoWindow when the marker is "clik" like this:

var marker = new google.maps.Marker({
     position: new google.maps.LatLng(locations[count][1], locations[count][2]),
     map: map
     });

marker.info = new google.maps.InfoWindow({
     content: locations [count][0]
     });


google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();
    this.info.open(marker_map, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
            });

Note, you can have some documentation about Listener here in google developer.


And, finally, we can plot an infoWindow in a marker if the user click on it. This is my complete code:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Info windows</title>
    <style>
    /* Always set the map height explicitly to define the size of the div
    * element that contains the map. */
    #map {
        height: 100%;
    }
    /* Optional: Makes the sample page fill the window. */
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>

    var locations = [
        ['Bondi Beach', -33.890542, 151.274856, 4],
        ['Coogee Beach', -33.923036, 151.259052, 5],
        ['Cronulla Beach', -34.028249, 151.157507, 3],
        ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
        ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];


    // When the user clicks the marker, an info window opens.

    function initMap() {
        var myLatLng = {lat: -33.90, lng: 151.16};

        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 10,
            center: myLatLng
            });

        var count=0;


        for (count = 0; count < locations.length; count++) {  

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[count][1], locations[count][2]),
                map: map
                });

            marker.info = new google.maps.InfoWindow({
                content: locations [count][0]
                });


            google.maps.event.addListener(marker, 'click', function() {  
                // this = marker
                var marker_map = this.getMap();
                this.info.open(marker_map, this);
                // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
                });
        }
    }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</body>
</html>

Normally, you should have this result:

Your result

Error: Cannot find module 'gulp-sass'

I ran : npm i gulp-sass@latest --save-dev

That did the magic for me

XML Serialize generic list of serializable objects

You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer (the extraTypes parameter) :

List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());

XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
    xs.Serialize(streamWriter, list);
}

If all the objects of your list inherit from the same class, you can also use the XmlInclude attribute to specify the expected types :

[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}

Xcode 8 shows error that provisioning profile doesn't include signing certificate

Here are the steps solved for me (For those who face the same problem in XCode 9.2):

  1. Just manually deleted local profiles in ~/Library/MobileDevice/Provisioning Profiles.

  2. Deleted and created all the certificates and provisioning profile from developers account.

  3. Removed developers account from Xcode and re-added it.

Solved my problem! :-)

python: Change the scripts working directory to the script's own directory

Change your crontab command to

* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)

The (...) starts a sub-shell that your crond executes as a single command. The || exit 1 causes your cronjob to fail in case that the directory is unavailable.

Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.

Clear the value of bootstrap-datepicker

I was having similar trouble and the following worked for me:

$('#datepicker').val('').datepicker('update');

Both method calls were needed, otherwise it didn't clear.

Update my gradle dependencies in eclipse

You have to make sure that "Dependency Management" is enabled. To do so, right click on the project name, go to the "Gradle" sub-menu and click on "Enable Dependency Management". Once you do that, Gradle should load all the dependencies for you.

Git push rejected after feature branch rebase

As the OP does understand the problem, just looks for a nicer solution...

How about this as a practice ?

  • Have on actual feature-develop branch (where you never rebase and force-push, so your fellow feature developers don't hate you). Here, regularly grab those changes from main with a merge. Messier history, yes, but life is easy and no one get's interupted in his work.

  • Have a second feature-develop branch, where one feature team member regulary pushes all feature commits to, indeed rebased, indeed forced. So almost cleanly based on a fairly recent master commit. Upon feature complete, push that branch on top of master.

There might be a pattern name for this method already.

How to keep :active css style after click a button

In the Divi Theme Documentation, it says that the theme comes with access to 'ePanel' which also has an 'Integration' section.

You should be able to add this code:

<script>
 $( ".et-pb-icon" ).click(function() {
 $( this ).toggleClass( "active" );
 });
</script>

into the the box that says 'Add code to the head of your blog' under the 'Integration' tab, which should get the jQuery working.

Then, you should be able to style your class to what ever you need.

Change the image source on rollover using jQuery

I've made something like the following code :)

It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png

$('#social').find('a').hover(function() {
    var target = $(this).find('img').attr('src');
    //console.log(target);
    var newTarg = target.replace('.png', '_hover.png');
    $(this).find('img').attr("src", newTarg);
}, function() {
    var target = $(this).find('img').attr('src');
    var newTarg = target.replace('_hover.png', '.png');
    $(this).find('img').attr("src", newTarg);
});

Override element.style using CSS

you can override the style on your css by referencing the offending property of the element style. On my case these two codes are set as 15px and is causing my background image to go black. So, i override them with 0px and placed the !important so it will be priority

.content {
    border-bottom-left-radius: 0px !important;
     border-bottom-right-radius: 0px !important;
}

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I had set everything correctly (cardinalities and dependent properties) but could not figure out why I keep receiving error. Finally figured out that, EF generated a column in dependent table on its own (table_tablecolumn) and it does not have any relation to the table, so no mapping was specified. I had to delete the column in EDMX file and rebuild the solution which fixed the issue. I am using DB approach.

Change the background color in a twitter bootstrap modal?

To change the color via:

CSS

Put these styles in your stylesheet after the bootstrap styles:

.modal-backdrop {
   background-color: red;
}

Less

Changes the bootstrap-variables to:

@modal-backdrop-bg:           red;

Source

Sass

Changes the bootstrap-variables to:

$modal-backdrop-bg:           red;

Source

Bootstrap-Customizer

Change @modal-backdrop-bg to your desired color:

getbootstrap.com/customize/


You can also remove the backdrop via Javascript or by setting the color to transparent.

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Android Studio : How to uninstall APK (or execute adb command) automatically before Run or Debug?

adb uninstall <package_name>

can be used to uninstall an app via your PC. If you want this to happen automatically every time you launch your app via Android Studio, you can do this:

  1. In Android Studio, click the drop down list to the left of Run button, and select Edit configurations...
  2. Click on app under Android Application, and in General Tab, find the heading 'Before Launch'
  3. Click the + button, select Run external tool, click the + button in the popup window.
  4. Give some name (Eg adb uninstall) and description, and type adb in Program: and uninstall <your-package-name> in Parameters:. Make sure that the new item is selected when you click Ok in the popup window.

Note: If you do not have adb in your PATH environment variable, give the full path to adb in Program: field (eg /home/user/android/sdk/platform-tools/adb).

Remove Project from Android Studio

Found this elsewhere on the web, it deletes basically everything (except the workspace.xml file, which you can delete manually from the project folder).

  1. Right Click on the project name under the save icon.
  2. Click delete
  3. Go to your project folder and check all the files were deleted.

enter image description here

How to redirect docker container logs to a single file?

docker logs -f docker_container_name >> YOUR_LOG_PATH 2>&1 &

How to make an "alias" for a long path?

Maybe it's better to use links

Soft Link

Symbolic or soft link (files or directories, more flexible and self documenting)

#      Source                            Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard Link

Hard link (files only, less flexible and not self documenting)

#    Source                            Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

How to create a link to a directory

Hint: If you need not to see the link in your home you can start it with a dot . ; then it will be hidden by default then you can access it like

cd ~/.myHiddelLongDirLink

Test class with a new() call in it with Mockito

I happened to be in a particular situation where my usecase resembled the one of Mureinik but I ended-up using the solution of Tomasz Nurkiewicz.

Here is how:

class TestedClass extends AARRGGHH {
    public LoginContext login(String user, String password) {
        LoginContext lc = new LoginContext("login", callbackHandler);
        lc.doThis();
        lc.doThat();
        return lc;
    }
}

Now, PowerMockRunner failed to initialize TestedClass because it extends AARRGGHH, which in turn does more contextual initialization... You see where this path was leading me: I would have needed to mock on several layers. Clearly a HUGE smell.

I found a nice hack with minimal refactoring of TestedClass: I created a small method

LoginContext initLoginContext(String login, CallbackHandler callbackHandler) {
    new lc = new LoginContext(login, callbackHandler);
}

The scope of this method is necessarily package.

Then your test stub will look like:

LoginContext lcMock = mock(LoginContext.class)
TestedClass testClass = spy(new TestedClass(withAllNeededArgs))
doReturn(lcMock)
    .when(testClass)
    .initLoginContext("login", callbackHandler)

and the trick is done...

SQL Query - Change date format in query to DD/MM/YYYY

If I understood your question, try something like this

declare @dd varchar(50)='Jan 30 2013 12:00:00:000AM'

Select convert(varchar,(CONVERT(date,@dd,103)),103)

Update

SELECT
PREFIX_TableName.ColumnName1 AS Name,
PREFIX_TableName.ColumnName2 AS E-Mail,
convert(varchar,(CONVERT(date,PREFIX_TableName.ColumnName3,103)),103) AS TransactionDate,
PREFIX_TableName.ColumnName4 AS OrderNumber

React.js: onChange event for contentEditable

This is the is simplest solution that worked for me.

<div
  contentEditable='true'
  onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>

How do I create a MessageBox in C#?

I got the same error 'System.Windows.Forms.MessageBox' is a 'type' but is used like a 'variable', even if using:

MessageBox.Show("Hello, World!");

I guess my initial attempts with invalid syntax caused some kind of bug and I ended up fixing it by adding a space between "MessageBox.Show" and the brackets ():

MessageBox.Show ("Hello, World!");

Now using the original syntax without the extra space works again:

MessageBox.Show("Hello, World!");

Rotate axis text in python matplotlib

import pylab as pl
pl.xticks(rotation = 90)

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

Test if executable exists in Python?

You can try the external lib called "sh" (http://amoffat.github.io/sh/).

import sh
print sh.which('ls')  # prints '/bin/ls' depending on your setup
print sh.which('xxx') # prints None

Drawing Isometric game worlds

Coobird's answer is the correct, complete one. However, I combined his hints with those from another site to create code that works in my app (iOS/Objective-C), which I wanted to share with anyone who comes here looking for such a thing. Please, if you like/up-vote this answer, do the same for the originals; all I did was "stand on the shoulders of giants."

As for sort-order, my technique is a modified painter's algorithm: each object has (a) an altitude of the base (I call "level") and (b) an X/Y for the "base" or "foot" of the image (examples: avatar's base is at his feet; tree's base is at it's roots; airplane's base is center-image, etc.) Then I just sort lowest to highest level, then lowest (highest on-screen) to highest base-Y, then lowest (left-most) to highest base-X. This renders the tiles the way one would expect.

Code to convert screen (point) to tile (cell) and back:

typedef struct ASIntCell {  // like CGPoint, but with int-s vice float-s
    int x;
    int y;
} ASIntCell;

// Cell-math helper here:
//      http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511
// Although we had to rotate the coordinates because...
// X increases NE (not SE)
// Y increases SE (not SW)
+ (ASIntCell) cellForPoint: (CGPoint) point
{
    const float halfHeight = rfcRowHeight / 2.;

    ASIntCell cell;
    cell.x = ((point.x / rfcColWidth) - ((point.y - halfHeight) / rfcRowHeight));
    cell.y = ((point.x / rfcColWidth) + ((point.y + halfHeight) / rfcRowHeight));

    return cell;
}


// Cell-math helper here:
//      http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds/893063
// X increases NE,
// Y increases SE
+ (CGPoint) centerForCell: (ASIntCell) cell
{
    CGPoint result;

    result.x = (cell.x * rfcColWidth  / 2) + (cell.y * rfcColWidth  / 2);
    result.y = (cell.y * rfcRowHeight / 2) - (cell.x * rfcRowHeight / 2);

    return result;
}

How to calculate difference in hours (decimal) between two dates in SQL Server?

Using Postgres I had issues with DATEDIFF, but had success with this:

  DATE_PART('day',(delivery_time)::timestamp - (placed_time)::timestamp) * 24 + 
  DATE_PART('hour',(delivery_time)::timestamp - (placed_time)::timestamp) +
  DATE_PART('minute',(delivery_time)::timestamp - (placed_time)::timestamp) / 60

which gave me an output like "14.3"

What is the difference between Cygwin and MinGW?

Cygwin is an attempt to create a complete UNIX/POSIX environment on Windows. To do this it uses various DLLs. While these DLLs are covered by GPLv3+, their license contains an exception that does not force a derived work to be covered by the GPLv3+. MinGW is a C/C++ compiler suite which allows you to create Windows executables without dependency on such DLLs - you only need the normal MSVC runtimes, which are part of any normal Microsoft Windows installation.

You can also get a small UNIX/POSIX like environment, compiled with MinGW called MSYS. It doesn't have anywhere near all the features of Cygwin, but is ideal for programmers wanting to use MinGW.

How to call a method in MainActivity from another class?

But an error occurred which says java.lang.NullPointerException.

Thats because, you never initialized your MainActivity. you should initialize your object before you call its methods.

MainActivity mActivity = new MainActivity();//make sure that you pass the appropriate arguments if you have an args constructor
mActivity.startChronometer();

Passing arrays as url parameter

I do this with serialized data base64 encoded. Best and smallest way, i guess. urlencode is to much wasting space and you have only 4k.

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

How do I manually configure a DataSource in Java?

The javadoc for DataSource you refer to is of the wrong package. You should look at javax.sql.DataSource. As you can see this is an interface. The host and port name configuration depends on the implementation, i.e. the JDBC driver you are using.

I have not checked the Derby javadocs but I suppose the code should compile like this:

ClientDataSource ds = org.apache.derby.jdbc.ClientDataSource()
ds.setHost etc....

Laravel 5 - redirect to HTTPS

For Laravel 5.6, I had to change condition a little to make it work.

from:

if (!$request->secure() && env('APP_ENV') === 'prod') {
return redirect()->secure($request->getRequestUri());
}

To:

if (empty($_SERVER['HTTPS']) && env('APP_ENV') === 'prod') {
return redirect()->secure($request->getRequestUri());
}

Codeigniter - multiple database connections

If you need to connect to more than one database simultaneously you can do so as follows:

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to (or you can pass the connection values as indicated above).

By setting the second parameter to TRUE (boolean) the function will return the database object.

Visit https://www.codeigniter.com/userguide3/database/connecting.html for further information.

Can an XSLT insert the current date?

XSLT 2

Date functions are available natively, such as:

<xsl:value-of  select="current-dateTime()"/>

There is also current-date() and current-time().

XSLT 1

Use the EXSLT date and times extension package.

  1. Download the date and times package from GitHub.
  2. Extract date.xsl to the location of your XSL files.
  3. Set the stylesheet header.
  4. Import date.xsl.

For example:

<xsl:stylesheet version="1.0" 
    xmlns:date="http://exslt.org/dates-and-times" 
    extension-element-prefixes="date"
    ...>

    <xsl:import href="date.xsl" />

    <xsl:template match="//root">
       <xsl:value-of select="date:date-time()"/>
    </xsl:template>
</xsl:stylesheet>

Adding click event handler to iframe

You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);

How do I update Node.js?

As some of you already said, the easiest way is to update Node.js through the Node.js package manager, npm. If you are a Linux (Debian-based in my case) user I would suggest to add these lines to your .bashrc file (in home directory):

function nodejsupdate() {
    ARGC=$#
    version=latest
    if [ $ARGC != 0 ]; then
        version=$1
    fi
    sudo npm cache clean -f
    sudo npm install -g n
    sudo n $version
}

Restart your terminal after saving and write nodejsupdate to update to the latest version of Node.js or nodejsupdate v6.0.0 (for example) to update to a specific version of Node.js.

BONUS: Update npm (add these lines to .bashrc)

function npmupdate() {
    sudo npm i npm -g
}

After restarting the terminal write npmupdate to update your node package manager to the latest version.

Now you can update Node.js and npm through your terminal (easier).

How to append output to the end of a text file

For example your file contains :

 1.  mangesh@001:~$ cat output.txt
    1
    2
    EOF

if u want to append at end of file then ---->remember spaces between 'text' >> 'filename'

  2. mangesh@001:~$ echo somthing to append >> output.txt|cat output.txt 
    1
    2
    EOF
    somthing to append

And to overwrite contents of file :

  3.  mangesh@001:~$ echo 'somthing new to write' > output.tx|cat output.tx
    somthing new to write

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

How to "set a breakpoint in malloc_error_break to debug"

I had the same problem with Xcode. I followed steps you gave and it didn't work. I became crazy because in every forum I saw, all clues for this problem are the one you gave. I finally saw I put a space after the malloc_error_break, I suppressed it and now it works. A dumb problem but if the solution doesn't work, be sure you haven't put any space before and after the malloc_error_break.

Hope this message will help..

Convert NaN to 0 in javascript

How about a regex?

function getNum(str) {
  return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}

The code below will ignore NaN to allow a calculation of properly entered numbers

_x000D_
_x000D_
function getNum(str) {_x000D_
  return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;_x000D_
}_x000D_
var inputsArray = document.getElementsByTagName('input');_x000D_
_x000D_
function computeTotal() {_x000D_
  var tot = 0;_x000D_
  tot += getNum(inputsArray[0].value);_x000D_
  tot += getNum(inputsArray[1].value);_x000D_
  tot += getNum(inputsArray[2].value);_x000D_
  inputsArray[3].value = tot;_x000D_
}
_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text" disabled></input>_x000D_
<button type="button" onclick="computeTotal()">Calculate</button>
_x000D_
_x000D_
_x000D_

Comparing object properties in c#

sometimes you don't want to compare all public properties and want to compare only the subset of them, so in this case you can just move logic to compare the desired list of properties to abstract class

public abstract class ValueObject<T> where T : ValueObject<T>
{
    protected abstract IEnumerable<object> GetAttributesToIncludeInEqualityCheck();

    public override bool Equals(object other)
    {
        return Equals(other as T);
    }

    public bool Equals(T other)
    {
        if (other == null)
        {
            return false;
        }

        return GetAttributesToIncludeInEqualityCheck()
            .SequenceEqual(other.GetAttributesToIncludeInEqualityCheck());
    }

    public static bool operator ==(ValueObject<T> left, ValueObject<T> right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(ValueObject<T> left, ValueObject<T> right)
    {
        return !(left == right);
    }

    public override int GetHashCode()
    {
        int hash = 17;
        foreach (var obj in this.GetAttributesToIncludeInEqualityCheck())
            hash = hash * 31 + (obj == null ? 0 : obj.GetHashCode());

        return hash;
    }
}

and use this abstract class later to compare the objects

public class Meters : ValueObject<Meters>
{
    ...

    protected decimal DistanceInMeters { get; private set; }

    ...

    protected override IEnumerable<object> GetAttributesToIncludeInEqualityCheck()
    {
        return new List<Object> { DistanceInMeters };
    }
}

Extract elements of list at odd positions

For the odd positions, you probably want:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

Bash or KornShell (ksh)?

Available in most UNIX system, ksh is standard-comliant, clearly designed, well-rounded. I think books,helps in ksh is enough and clear, especially the O'Reilly book. Bash is a mass. I keep it as root login shell for Linux at home only.

For interactive use, I prefer zsh on Linux/UNIX. I run scripts in zsh, but I'll test most of my scripts, functions in AIX ksh though.

Jquery: how to trigger click event on pressing enter key

try out this....

$('#txtSearchProdAssign').keypress(function (e) {
 var key = e.which;
 if(key == 13)  // the enter key code
  {
    $('input[name = butAssignProd]').click();
    return false;  
  }
});   

_x000D_
_x000D_
$(function() {

  $('input[name="butAssignProd"]').click(function() {
    alert('Hello...!');
  });

  //press enter on text area..

  $('#txtSearchProdAssign').keypress(function(e) {
    var key = e.which;
    if (key == 13) // the enter key code
    {
      $('input[name = butAssignProd]').click();
      return false;
    }
  });

});
_x000D_
<!DOCTYPE html>
<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
  <meta charset=utf-8 />
  <title>JS Bin</title>
</head>

<body>
  <textarea id="txtSearchProdAssign"></textarea>
  <input type="text" name="butAssignProd" placeholder="click here">
</body>

</html>
_x000D_
_x000D_
_x000D_


Find Demo in jsbin.com

How to edit Docker container files from the host?

The way I am doing is using Emacs with docker package installed. I would recommend Spacemacs version of Emacs. I would follow the following steps:

1) Install Emacs (Instruction) and install Spacemacs (Instruction)

2) Add docker in your .spacemacs file

3) Start Emacs

4) Find file (SPC+f+f) and type /docker:<container-id>:/<path of dir/file in the container>

5) Now your emacs will use the container environment to edit the files

How can I get a list of Git branches, ordered by most recent commit?

I use the following alias:

recent = "!r(){git for-each-ref --sort=-committerdate refs/heads --format='%(HEAD)%(color:yellow)%(refname:short)|%(color:bold green)%(committerdate:relative)|%(color:blue)%(subject)|%(color:magenta)%(authorname)%(color:reset)' --color=always | column -ts'|'}; r"

which produces:

Result

Use '|' to separate.

Python - 'ascii' codec can't decode byte

If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u:

Python 2.7.2 (default, Jan 14 2012, 23:14:09) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'

Further reading: Unicode HOWTO.

Using SQL LOADER in Oracle to import CSV file

LOAD DATA INFILE 'D:\CertificationInputFile.csv' INTO TABLE CERT_EXCLUSION_LIST FIELDS TERMINATED BY "|" OPTIONALLY ENCLOSED BY '"' ( CERTIFICATIONNAME, CERTIFICATIONVERSION )

File Upload to HTTP server in iphone programming

I have made a lightweight backup method for the Mobile-AppSales app available at github

I wrote about it here http://memention.com/blog/2009/11/22/Lightweight-backup.html

Look for the - (void)startUpload method in ReportManager.m

is of a type that is invalid for use as a key column in an index

A solution would be to declare your key as nvarchar(20).

A SQL Query to select a string between two known strings

I had a similar need to parse out a set of parameters stored within an IIS logs' csUriQuery field, which looked like this: id=3598308&user=AD\user&parameter=1&listing=No needed in this format.

I ended up creating a User-defined function to accomplish a string between, with the following assumptions:

  1. If the starting occurrence is not found, a NULL is returned, and
  2. If the ending occurrence is not found, the rest of the string is returned

Here's the code:

CREATE FUNCTION dbo.str_between(@col varchar(max), @start varchar(50), @end varchar(50))  
  RETURNS varchar(max)  
  WITH EXECUTE AS CALLER  
AS  
BEGIN  
  RETURN substring(@col, charindex(@start, @col) + len(@start), 
         isnull(nullif(charindex(@end, stuff(@col, 1, charindex(@start, @col)-1, '')),0),
         len(stuff(@col, 1, charindex(@start, @col)-1, ''))+1) - len(@start)-1);
END;  
GO

For the above question, the usage is as follows:

DECLARE @a VARCHAR(MAX) = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'
SELECT dbo.str_between(@a, 'the dog', 'immediately')
-- Yields' had been very bad and required harsh punishment '

How to check a string for a special character?

You will need to define "special characters", but it's likely that for some string s you mean:

import re
if re.match(r'^\w+$', s):
    # s is good-to-go

How do you get the current text contents of a QComboBox?

If you want the text value of a QString object you can use the __str__ property, like this:

>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'

Hope that helps.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Put in head link to google styles

<link href="https://fonts.googleapis.com/icon?family=Material+Icons+Outlined" rel="stylesheet">

and in body something like this

<i class="material-icons-outlined">bookmarks</i>

How to submit a form when the return key is pressed?

I believe this is what you want.

//<![CDATA[

//Send form if they hit enter.
document.onkeypress = enter;
function enter(e) {
  if (e.which == 13) { sendform(); }
}

//Form to send
function sendform() {
  document.forms[0].submit();
}
//]]>

Every time a key is pressed, function enter() will be called. If the key pressed matches the enter key (13), then sendform() will be called and the first encountered form will be sent. This is only for Firefox and other standards compliant browsers.

If you find this code useful, please be sure to vote me up!

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

Best way to do multiple constructors in PHP

Hmm, surprised I don't see this answer yet, suppose I'll throw my hat in the ring.

class Action {
    const cancelable    =   0;
    const target        =   1
    const type          =   2;

    public $cancelable;
    public $target;
    public $type;


    __construct( $opt = [] ){

        $this->cancelable   = isset($opt[cancelable]) ? $opt[cancelable] : true;
        $this->target       = isset($opt[target]) ?     $opt[target] : NULL;
        $this->type         = isset($opt[type]) ?       $opt[type] : 'action';

    }
}


$myAction = new Action( [
    Action::cancelable => false,
    Action::type => 'spin',
    .
    .
    .
]);

You can optionally separate the options into their own class, such as extending SplEnum.

abstract class ActionOpt extends SplEnum{
    const cancelable    =   0;
    const target        =   1
    const type          =   2;
}

Add new column with foreign key constraint in one command

As so often with SQL-related question, it depends on the DBMS. Some DBMS allow you to combine ALTER table operations separated by commas. For example...

Informix syntax:

ALTER TABLE one
    ADD two_id INTEGER,
    ADD CONSTRAINT FOREIGN KEY(two_id) REFERENCES two(id);

The syntax for IBM DB2 LUW is similar, repeating the keyword ADD but (if I read the diagram correctly) not requiring a comma to separate the added items.

Microsoft SQL Server syntax:

ALTER TABLE one
    ADD two_id INTEGER,
    FOREIGN KEY(two_id) REFERENCES two(id);

Some others do not allow you to combine ALTER TABLE operations like that. Standard SQL only allows a single operation in the ALTER TABLE statement, so in Standard SQL, it has to be done in two steps.

How to overwrite the output directory in spark

  val jobName = "WordCount";
  //overwrite the output directory in spark  set("spark.hadoop.validateOutputSpecs", "false")
  val conf = new 
  SparkConf().setAppName(jobName).set("spark.hadoop.validateOutputSpecs", "false");
  val sc = new SparkContext(conf)

How to center align the ActionBar title in Android?

Just a quick addition to Ahmad's answer. You can't use getSupportActionBar().setTitle anymore when using a custom view with a TextView. So to set the title when you have multiple Activities with this custom ActionBar (using this one xml), in your onCreate() method after you assign a custom view:

TextView textViewTitle = (TextView) findViewById(R.id.mytext);
textViewTitle.setText(R.string.title_for_this_activity);

Printing Mongo query output to a file while in the mongo shell

There are ways to do this without having to quit the CLI and pipe mongo output to a non-tty.

To save the output from a query with result x we can do the following to directly store the json output to /tmp/x.json:

> EDITOR="cat > /tmp/x.json"
> x = db.MyCollection.find(...).toArray()
> edit x
>

Note that the output isn't strictly Json but rather the dialect that Mongo uses.

Python for and if on one line

In python3 the variable i will be out of scope when you try to print it.

To get the value you want you should store the result of your operation inside a new variable:

my_list = ["one","two","three"]
result=[(i) for i in my_list if i=="two"]
print(result)

you will then the following output

['two']

Node.js: how to consume SOAP XML web service

Adding to Kim .J's solution: you can add preserveWhitespace=true in order to avoid a Whitespace error. Like this:

soap.CreateClient(url,preserveWhitespace=true,function(...){

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

How can I escape latex code received through user input?

I spent a lot of time trying different answers all around the internet, and I suspect the reasons why one thing works for some people and not for others is due to very small weird differences in application. For context, I needed to read in file names from a csv file that had strange and/or unmappable unicode characters and write them to a new csv file. For what it's worth, here's what worked for me:

s = '\u00e7\u00a3\u0085\u00e5\u008d\u0095' # csv freaks if you try to write this
s = repr(s.encode('utf-8', 'ignore'))[2:-1]

GIT commit as different user without email / or only email

Just supplement:

git commit --author="[email protected] " -m "Impersonation is evil."

In some cases the commit still fails and shows you the following message:

*** Please tell me who you are.

Run

git config --global user.email "[email protected]" git config --global user.name "Your Name"

to set your account's default identity. Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got xxxx)

So just run "git config", then "git commit"

How to resolve /var/www copy/write permission denied?

are you in a develpment enviroment? why just not do

chown -R user.group /var/www

so you will be able to write with your user.

How can I set the 'backend' in matplotlib in Python?

This can also be set in the configuration file matplotlibrc (as explained in the error message), for instance:

# The default backend; one of GTK GTKAgg GTKCairo GTK3Agg GTK3Cairo
# CocoaAgg MacOSX Qt4Agg Qt5Agg TkAgg WX WXAgg Agg Cairo GDK PS PDF SVG
backend : Agg

That way, the backend does not need to be hardcoded if the code is shared with other people. For more information, check the documentation.

How to obtain the chat_id of a private Telegram channel?

NEEDED ANSWER:

You should add & make your BOT as administrator of the PRIVATE channel, otherwise chat not found error happens.

Return HTML content as a string, given URL. Javascript Function

you need to return when the readystate==4 e.g.

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

Checking for empty queryset in Django

if not orgs:
    # Do this...
else:
    # Do that...

How to get input text value from inside td

I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.

I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:

    $('.start').keyup(function() {
        var otherInputs = $(this).parents('td').siblings().find('input');

        for(var i = 0; i < otherInputs.length; i++) {
            alert($(otherInputs[i]).val());
        }
        return false;
    });

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

require 'date'
DateTime.strptime("1318996912",'%s')

Python function as a function argument?

Can a Python function be an argument of another function?

Yes.

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)

To be more specific ... with various arguments ...

>>> def x(a,b):
...     print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
...     z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I had the same problem and I fixed it just by setting this: <item name="android:windowIsFloating">false</item> in styles.xml

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

None of the solutions above worked for me. What did was removing the main.iml file manually and it suddenly worked.

How do I Merge two Arrays in VBA?

I tried the code provided above, but it gave an error 9 for me. I made this code, and it worked fine for my purposes. I hope others find it useful as well.

Function mergeArrays(ByRef arr1() As Variant, arr2() As Variant) As Variant

    Dim returnThis() As Variant
    Dim len1 As Integer, len2 As Integer, lenRe As Integer, counter As Integer
    len1 = UBound(arr1)
    len2 = UBound(arr2)
    lenRe = len1 + len2
    ReDim returnThis(1 To lenRe)
    counter = 1

    Do While counter <= len1 'get first array in returnThis
        returnThis(counter) = arr1(counter)
        counter = counter + 1
    Loop
    Do While counter <= lenRe 'get the second array in returnThis
        returnThis(counter) = arr2(counter - len1)
        counter = counter + 1
    Loop

mergeArrays = returnThis
End Function

Break statement in javascript array map method

That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});

docker error: /var/run/docker.sock: no such file or directory

If you're using CentOS 7, and you've installed Docker via yum, don't forget to run:

$ sudo systemctl start docker
$ sudo systemctl enable docker

This will start the server, as well as re-start it automatically on boot.

Specifying an Index (Non-Unique Key) Using JPA

OpenJPA allows you to specify non-standard annotation to define index on property.

Details are here.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

include popper.js before bootstrap.min.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.0.4/popper.js"></script>

use this link to get popper

what do <form action="#"> and <form method="post" action="#"> do?

action="" will resolve to the page's address. action="#" will resolve to the page's address + #, which will mean an empty fragment identifier.

Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.

Usually, authors just put # in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action="" (or omit it if validation allows).

WPF Binding StringFormat Short Date String

Be aware of the single quotes for the string format. This doesn't work:

    Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"

while this does:

    Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"

JavaScript associative array to JSON

You might want to push the object into the array

enter code here

var AssocArray = new Array();

AssocArray.push( "The letter A");

console.log("a = " + AssocArray[0]);

// result: "a = The letter A"

console.log( AssocArray[0]);

JSON.stringify(AssocArray);

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.

with SomeContextManager() as foo:
    #works because a new object is referenced...

not

with SomeContextManager as foo:
    #AttributeError because the class is referenced

Catches me out from time to time and I end up here -__-

Where can I get a list of Ansible pre-defined variables?

https://github.com/f500/ansible-dumpall
FYI: this github project shows you how to list 90% of variables across all hosts. I find it more globally useful than single host commands. The README includes instructions for building a simple inventory report. It's even more valuable to run this at the end of a playbook to see all the Facts. To also debug Task behaviour use register:

The result is missing a few items: - included YAML file variables - extra-vars - a number of the Ansible internal vars described here: Ansible Behavioural Params

How can I update a single row in a ListView?

My solution: If it is correct*, update the data and viewable items without re-drawing the whole list. Else notifyDataSetChanged.

Correct - oldData size == new data size, and old data IDs and their order == new data IDs and order

How:

/**
 * A View can only be used (visible) once. This class creates a map from int (position) to view, where the mapping
 * is one-to-one and on.
 * 
 */
    private static class UniqueValueSparseArray extends SparseArray<View> {
    private final HashMap<View,Integer> m_valueToKey = new HashMap<View,Integer>();

    @Override
    public void put(int key, View value) {
        final Integer previousKey = m_valueToKey.put(value,key);
        if(null != previousKey) {
            remove(previousKey);//re-mapping
        }
        super.put(key, value);
    }
}

@Override
public void setData(final List<? extends DBObject> data) {
    // TODO Implement 'smarter' logic, for replacing just part of the data?
    if (data == m_data) return;
    List<? extends DBObject> oldData = m_data;
    m_data = null == data ? Collections.EMPTY_LIST : data;
    if (!updateExistingViews(oldData, data)) notifyDataSetChanged();
    else if (DEBUG) Log.d(TAG, "Updated without notifyDataSetChanged");
}


/**
 * See if we can update the data within existing layout, without re-drawing the list.
 * @param oldData
 * @param newData
 * @return
 */
private boolean updateExistingViews(List<? extends DBObject> oldData, List<? extends DBObject> newData) {
    /**
     * Iterate over new data, compare to old. If IDs out of sync, stop and return false. Else - update visible
     * items.
     */
    final int oldDataSize = oldData.size();
    if (oldDataSize != newData.size()) return false;
    DBObject newObj;

    int nVisibleViews = m_visibleViews.size();
    if(nVisibleViews == 0) return false;

    for (int position = 0; nVisibleViews > 0 && position < oldDataSize; position++) {
        newObj = newData.get(position);
        if (oldData.get(position).getId() != newObj.getId()) return false;
        // iterate over visible objects and see if this ID is there.
        final View view = m_visibleViews.get(position);
        if (null != view) {
            // this position has a visible view, let's update it!
            bindView(position, view, false);
            nVisibleViews--;
        }
    }

    return true;
}

and of course:

@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
    final View result = createViewFromResource(position, convertView, parent);
    m_visibleViews.put(position, result);

    return result;
}

Ignore the last param to bindView (I use it to determine whether or not I need to recycle bitmaps for ImageDrawable).

As mentioned above, the total number of 'visible' views is roughly the amount that fits on the screen (ignoring orientation changes etc), so no biggie memory-wise.

Performing Inserts and Updates with Dapper

you can do it in such way:

sqlConnection.Open();

string sqlQuery = "INSERT INTO [dbo].[Customer]([FirstName],[LastName],[Address],[City]) VALUES (@FirstName,@LastName,@Address,@City)";
sqlConnection.Execute(sqlQuery,
    new
    {
        customerEntity.FirstName,
        customerEntity.LastName,
        customerEntity.Address,
        customerEntity.City
    });

sqlConnection.Close();

Calling a function when ng-repeat has finished

If you’re not averse to using double-dollar scope props and you’re writing a directive whose only content is a repeat, there is a pretty simple solution (assuming you only care about the initial render). In the link function:

const dereg = scope.$watch('$$childTail.$last', last => {
    if (last) {
        dereg();
        // do yr stuff -- you may still need a $timeout here
    }
});

This is useful for cases where you have a directive that needs to do DOM manip based on the widths or heights of the members of a rendered list (which I think is the most likely reason one would ask this question), but it’s not as generic as the other solutions that have been proposed.

How to ignore user's time zone and force Date() use specific time zone

Use this and always use UTC functions afterwards e.g. mydate.getUTCHours();

_x000D_
_x000D_
   function getDateUTC(str) {
        function getUTCDate(myDateStr){
            if(myDateStr.length <= 10){
                //const date = new Date(myDateStr); //is already assuming UTC, smart - but for browser compatibility we will add time string none the less
                const date = new Date(myDateStr.trim() + 'T00:00:00Z');
                return date;
            }else{
                throw "only date strings, not date time";
            }
        }

        function getUTCDatetime(myDateStr){
            if(myDateStr.length <= 10){
                throw "only date TIME strings, not date only";
            }else{
                return new Date(myDateStr.trim() +'Z'); //this assumes no time zone is part of the date string. Z indicates UTC time zone
            }
        }  
        
        let rv = '';
        
        if(str && str.length){
            if(str.length <= 10){
                rv = getUTCDate(str);
            }else if(str.length > 10){
                rv = getUTCDatetime(str);
            } 
        }else{
            rv = '';
        }
        return rv;
    }

console.info(getDateUTC('2020-02-02').toUTCString());

var mydateee2 = getDateUTC('2020-02-02 02:02:02');
console.info(mydateee2.toUTCString());

// you are free to use all UTC functions on date e.g.
console.info(mydateee2.getUTCHours())
console.info('all is good now if you use UTC functions')
_x000D_
_x000D_
_x000D_

JPA CascadeType.ALL does not delete orphans

you can use @PrivateOwned to delete orphans e.g

@OneToMany(mappedBy = "masterData", cascade = {
        CascadeType.ALL })
@PrivateOwned
private List<Data> dataList;

Is it better practice to use String.format over string Concatenation in Java?

You cannot compare String Concatenation and String.Format by the program above.

You may try this also be interchanging the position of using your String.Format and Concatenation in your code block like the below

public static void main(String[] args) throws Exception {      
  long start = System.currentTimeMillis();

  for( int i=0;i<1000000; i++){
    String s = String.format( "Hi %s; Hi to you %s",i, + i*2);
  }

  long end = System.currentTimeMillis();
  System.out.println("Format = " + ((end - start)) + " millisecond");
  start = System.currentTimeMillis();

  for( int i=0;i<1000000; i++){
    String s = "Hi " + i + "; Hi to you " + i*2;
  }

  end = System.currentTimeMillis();
  System.out.println("Concatenation = " + ((end - start)) + " millisecond") ;
}

You will be surprised to see that Format works faster here. This is since the intial objects created might not be released and there can be an issue with memory allocation and thereby the performance.

SHA-1 fingerprint of keystore certificate

For local you get easily sha1 from android studio but for live please check below url :

Facebook Android Generate Key Hash

We mostly not done below steps so please check the link which is 100% correct.

8) If you see in openssl Bin folder, you will get a file with the name of debug.txt

9) Now either you can restart command prompt or work with existing command prompt

10) get back to C drive and give the path of openssl Bin folder

11) copy the following code and paste

openssl sha1 -binary debug.txt > debug_sha.txt

12) you will get debug_sha.txt in openssl bin folder

13) Again copy following code and paste

openssl base64 -in debug_sha.txt > debug_base64.txt

14) you will get debug_base64.txt in openssl bin folder

15) open debug_base64.txt file Here is your Key hash.

Link to a section of a webpage

Simple:

Use <section>.

and use <a href="page.html#tips">Visit the Useful Tips Section</a>

w3school.com/html_links

What is the difference between static_cast<> and C style casting?

C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime.

Also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts.

Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly.

When writing C++ I'd pretty much always use the C++ ones over the the C style.

How to sum up elements of a C++ vector?

I'm a Perl user, an a game we have is to find every different ways to increment a variable... that's not really different here. The answer to how many ways to find the sum of the elements of a vector in C++ is probably an infinity...

My 2 cents:

Using BOOST_FOREACH, to get free of the ugly iterator syntax:

sum = 0;
BOOST_FOREACH(int & x, myvector){
  sum += x;
}

iterating on indices (really easy to read).

int i, sum = 0;
for (i=0; i<myvector.size(); i++){
  sum += myvector[i];
}

This other one is destructive, accessing vector like a stack:

while (!myvector.empty()){
   sum+=myvector.back();
   myvector.pop_back();
}

Can I hide/show asp:Menu items based on role?

SIMPLE method may not be the best for all cases

        <%                
            if (Session["Utype"].ToString() == "1")
            {
        %>
        <li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>   
        <li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
        <%
              }
            else
             {
        %>                      
        <li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
        <%
             }                
        %>

Converting string to double in C#

There are 3 problems.

1) Incorrect decimal separator

Different cultures use different decimal separators (namely , and .).

If you replace . with , it should work as expected:

Console.WriteLine(Convert.ToDouble("52,8725945"));

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:

double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);

You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.

2) You have an incorrect double

One of your values is incorrect, because it contains two dots:

15.5859949000000662452.23862099999999

3) Your array has an empty value at the end, which is an incorrect double

You can use overloaded Split which removes empty values:

string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

Difference between 2 dates in SQLite

Both answers provide solutions a bit more complex, as they need to be. Say the payment was created on January 6, 2013. And we want to know the difference between this date and today.

sqlite> SELECT julianday() - julianday('2013-01-06');
34.7978485878557 

The difference is 34 days. We can use julianday('now') for better clarity. In other words, we do not need to put date() or datetime() functions as parameters to julianday() function.

How to run C program on Mac OS X using Terminal?

First save your program as program.c.

Now you need the compiler, so you need to go to App Store and install Xcode which is Apple's compiler and development tools. How to find App Store? Do a "Spotlight Search" by typing Space and start typing App Store and hit Enter when it guesses correctly.

App Store looks like this:

enter image description here

Xcode looks like this on App Store:

enter image description here

Then you need to install the command-line tools in Terminal. How to start Terminal? You need to do another "Spotlight Search", which means you type Space and start typing Terminal and hit Enter when it guesses Terminal.

Now install the command-line tools like this:

xcode-select --install

Then you can compile your code with by simply running gcc as in the next line without having to fire up the big, ugly software development GUI called Xcode:

gcc -Wall -o program program.c

Note: On newer versions of OS X, you would use clang instead of gcc, like this:

clang program.c -o program

Then you can run it with:

./program
Hello, world!

If your program is C++, you'll probably want to use one of these commands:

clang++ -o program program.cpp
g++ -std=c++11 -o program program.cpp
g++-7 -std=c++11 -o program program.cpp

numbers not allowed (0-9) - Regex Expression in javascript

Like this: ^[^0-9]+$

Explanation:

  • ^ matches the beginning of the string
  • [^...] matches anything that isn't inside
  • 0-9 means any character between 0 and 9
  • + matches one or more of the previous thing
  • $ matches the end of the string

How to show hidden divs on mouseover?

If the divs are hidden, they will never trigger the mouseover event.

You will have to listen to the event of some other unhidden element.

You can consider wrapping your hidden divs into container divs that remain visible, and then act on the mouseover event of these containers.

_x000D_
_x000D_
<div style="width: 80px; height: 20px; background-color: red;" _x000D_
        onmouseover="document.getElementById('div1').style.display = 'block';">_x000D_
   <div id="div1" style="display: none;">Text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You could also listen for the mouseout event if you want the div to disappear when the mouse leaves the container div:

onmouseout="document.getElementById('div1').style.display = 'none';"

Why use HttpClient for Synchronous Connection

In my case the accepted answer did not work. I was calling the API from an MVC application which had no async actions.

This is how I managed to make it work:

private static readonly TaskFactory _myTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
public static T RunSync<T>(Func<Task<T>> func)
    {           
        CultureInfo cultureUi = CultureInfo.CurrentUICulture;
        CultureInfo culture = CultureInfo.CurrentCulture;
        return _myTaskFactory.StartNew<Task<T>>(delegate
        {
            Thread.CurrentThread.CurrentCulture = culture;
            Thread.CurrentThread.CurrentUICulture = cultureUi;
            return func();
        }).Unwrap<T>().GetAwaiter().GetResult();
    }

Then I called it like this:

Helper.RunSync(new Func<Task<ReturnTypeGoesHere>>(async () => await AsyncCallGoesHere(myparameter)));

How to select only 1 row from oracle sql?

select a.user from (select user from users order by user) a where rownum = 1

will perform the best, another option is:

select a.user 
from ( 
select user, 
row_number() over (order by user) user_rank, 
row_number() over (partition by dept order by user) user_dept_rank 
from users 
) a 
where a.user_rank = 1 or user_dept_rank = 2

in scenarios where you want different subsets, but I guess you could also use RANK() But, I also like row_number() over(...) since no grouping is required.

How to draw checkbox or tick mark in GitHub Markdown table?

There are very nice Emoji icons instructions available at

You can check them out. I hope you would find suitable icons for your writing.

Nice Emojis

Best,

failed to open stream: HTTP wrapper does not support writeable connections

May this code help you. It works in my case.

$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
    $fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
    if(!file_exists($filename)):
        $handle = fopen( $filename, 'a' ) or die( 'Cannot open file:  ' . $fileUrl ); //implicitly creates file
        fwrite( $handle, json_encode(array()));
        fclose( $handle );
    endif;
    $response = file_get_contents($filename);
    $tempArray = json_decode($response);
    if(!empty($tempArray)):
        $count = count($tempArray) + 1;
    else:
        $count = 1;
    endif;
    $tempArray[] = array_merge(array("sn." => $count), $data);
    $jsonData = json_encode($tempArray);
    file_put_contents($filename, $jsonData);

how to deal with google map inside of a hidden div (Updated picture)

I didn't like that the map would load only after the hidden div had become visible. In a carousel, for example, that doesn't really work.

This my solution is to add class to the hidden element to unhide it and hide it with position absolute instead, then render the map, and remove the class after map load.

Tested in Bootstrap Carousel.

HTML

<div class="item loading"><div id="map-canvas"></div></div>

CSS

.loading { display: block; position: absolute; }

JS

$(document).ready(function(){
    // render map //
    google.maps.event.addListenerOnce(map, 'idle', function(){
        $('.loading').removeClass('loading');
    });
}

How can I style an Android Switch?

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

Virtual Memory Usage from Java under Linux, too much memory used

Just a thought, but you may check the influence of a ulimit -v option.

That is not an actual solution since it would limit address space available for all process, but that would allow you to check the behavior of your application with a limited virtual memory.

See :hover state in Chrome Developer Tools

In my case, I want to dubug bootstrap tooltip. But the methods above not work for me. I guess bootstrap implemented this by something like mouse in/out event.

Anyway, when I hover on a button, it will generate a brother html element below the button, so I select the button's parent element in "Elements" tab of "Developer tools" window, hover the button, and "Ctrl + C", then I can paste the source code which contains the generated code. Last find the generated code, and add it to the source code by "Edit as HTML" in "Elements" tab.

Hope it can help somebody.

How to check if a float value is a whole number

You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:

r = int(12000**(1/3.0))
print r*r*r # 10648

Where are environment variables stored in the Windows Registry?

I always had problems with that, and I made a getx.bat script:

:: getx %envvar% [\m]
:: Reads envvar from user environment variable and stores it in the getxvalue variable
:: with \m read system environment

@SETLOCAL EnableDelayedExpansion
@echo OFF

@set l_regpath="HKEY_CURRENT_USER\Environment"
@if "\m"=="%2" set l_regpath="HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

::REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH /t REG_SZ /f /d "%PATH%"
::@REG QUERY %l_regpath% /v %1 /S

@FOR /F "tokens=*" %%A IN ('REG QUERY %l_regpath% /v %1 /S') DO (
@  set l_a=%%A
@    if NOT "!l_a!"=="!l_a:    =!" set l_line=!l_a!
)

:: Delimiter is four spaces. Change it to tab \t
@set l_line=!l_line!
@set l_line=%l_line:    =    %

@set getxvalue=

@FOR /F "tokens=3* delims=  " %%A IN ("%l_line%") DO (
@    set getxvalue=%%A
)
@set getxvalue=!getxvalue!
@echo %getxvalue% > getxfile.tmp.txt
@ENDLOCAL

:: We already used tab as a delimiter
@FOR /F "delims=    " %%A IN (getxfile.tmp.txt) DO (
    @set getxvalue=%%A
)
@del getxfile.tmp.txt

@echo ON

Save results to csv file with Python

An easy example would be something like:

writer = csv.writer(open("filename.csv", "wb"))
String[] entries = "first#second#third".split("#");
writer.writerows(entries)
writer.close()

Nginx serves .php files as downloads, instead of executing them

Update nginx config /etc/nginx/sites-available/default or your config file

if you are using php7 use this

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php7.0-fpm.sock;      
    }

if you are using php5 use this

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php5-fpm.sock;
            fastcgi_index index.php;
            include fastcgi_params;
    }

Visit here for complete detail Detail here

MySQL direct INSERT INTO with WHERE clause

Example of how to perform a INSERT INTO SELECT with a WHERE clause.

INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2

What is the difference between onBlur and onChange attribute in HTML?

In Firefox the onchange fires only when you tab or else click outside the input field. The same is true of Onblur. The difference is that onblur will fire whether you changed anything in the field or not. It is possible that ENTER will fire one or both of these, but you wouldn't know that if you disable the ENTER in your forms to prevent unexpected submits.

Twitter bootstrap scrollable modal

/* Important part */
.modal-dialog{
    overflow-y: initial !important
}
.modal-body{
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

This works for Bootstrap 3 without JS code and is responsive.

Source

Reportviewer tool missing in visual studio 2017 RC

** Update**: 11/19/2019

Microsoft has released a new version of the control 150.1400.0 in their Nuget library. My short testing shows that it works again in the forms designer where 150.1357.0 and 150.1358.0 did not. This includes being able to resize and modify the ReportViewer Tasks on the control itself.

** Update**: 8/18/2019

Removing the latest version and rolling back to 150.900.148.0 seems to work on multiple computers I'm using with VS2017 and VS2019.

You can roll back to 150.900.148 in the Nuget solution package manager. It works similarly to the previous versions. Use the drop down box to select the older version.

enter image description here

It may be easier to manually delete references to post 150.900 versions of ReportViewer and readd them than it is to fix them.

Remember to restart Visual Studio after changing the toolbox entry.

Update: 8/7/2019

A newer version of the ReportViewer control has been released, probably coinciding with Visual Studio 2019. I was working with V150.1358.0.

Following the directions in this answer gets the control in the designer's toolbox. But once dropped on the form it doesn't display. The control shows up below the form as a non-visual component.

This is working as designed according to Microsoft SQL BI support. This is the group responsible for the control.

While you still cannot interact with the control directly, these additional steps give a workaround so the control can be sized on the form. While now visible, the designer treats the control as if it didn't exist.

I've created a feedback request at the suggestion of Microsoft SQL BI support. Please consider voting on it to get Microsoft's attention.

Microsoft Azure Feedback page - Restore Designtime features of the WinForms ReportViewer Control

Additional steps:

  • After adding the reportviewer to the WinForm
  • Add a Panel Control to the WinForm.
  • In the form's form.designer.cs file, add the Reportviewer control to the panel.

      // 
      // panel1
      // 
      this.panel1.Controls.Add(this.reportViewer1);
    
  • Return to the form's designer, you should see the reportViewer on the panel

  • In the Properties panel select the ReportViewer in the controls list dropdown
  • Set the reportViewer's Dock property to Fill

Now you can position the reportViewer by actually interacting with the panel.

Update: Microsoft released a document on April 18, 2017 describing how to configure and use the reporting tool in Visual Studio 2017.

Visual Studio 2017 does not have the ReportViewer tool installed by default in the ToolBox. Installing the extension Microsoft Rdlc Report Designer for Visual Studio and then adding that to the ToolBox results in a non-visual component that appears below the form.

Microsoft Support had told me this is a bug, but as of April 21, 2017 it is "working as designed".

The following steps need to be followed for each project that requires ReportViewer.

  • If you have ReportViewer in the Toolbox, remove it. Highlight, right-click and delete.
    • You will have to have a project with a form open to do this.

Edited 8/7/2019 - It looks like the current version of the RDLC Report Designer extension no longer interferes. You need this to actually edit the reports.

  • If you have the Microsoft Rdlc Report Designer for Visual Studio extension installed, uninstall it.

  • Close your solution and restart Visual Studio. This is a crucial step, errors will occur if VS is not restarted when switching between solutions.

  • Open your solution.
  • Open the NuGet Package Manager Console (Tools/NuGet Package Manager/Package Manager Console)
  • At the PM> prompt enter this command, case matters.

    Install-Package Microsoft.ReportingServices.ReportViewerControl.WinForms

    You should see text describing the installation of the package.

Now we can temporarily add the ReportViewer tool to the tool box.

  • Right-click in the toolbox and use Choose Items...

  • We need to browse to the proper DLL that is located in the solutions Packages folder, so hit the browse button.

  • In our example we can paste in the packages folder as shown in the text of Package Manager Console.

    C:\Users\jdoe\Documents\Projects\_Test\ReportViewerTest\WindowsFormsApp1\packages

  • Then double click on the folder named Microsoft.ReportingServices.ReportViewerControl.Winforms.140.340.80

    The version number will probably change in the future.

  • Then double-click on lib and again on net40.

  • Finally, double click on the file Microsoft.ReportViewer.WinForms.dll

    You should see ReportViewer checked in the dialog. Scroll to the right and you will see the version 14.0.0.0 associated to it.

  • Click OK.

ReportViewer is now located in the ToolBox.

  • Drag the tool to the desired form(s).

  • Once completed, delete the ReportViewer tool from the tool box. You can't use it with another project.

  • You may save the project and are good to go.

Remember to restart Visual Studio any time you need to open a project with ReportViewer so that the DLL is loaded from the correct location. If you try and open a solution with a form with ReportViewer without restarting you will see errors indicating that the “The variable 'reportViewer1' is either undeclared or was never assigned.“.

If you add a new project to the same solution you need to create the project, save the solution, restart Visual Studio and then you should be able to add the ReportViewer to the form. I have seen it not work the first time and show up as a non-visual component.

When that happens, removing the component from the form, deleting the Microsoft.ReportViewer.* references from the project, saving and restarting usually works.

Traverse a list in reverse order in Python

If you need the index and your list is small, the most readable way is to do reversed(list(enumerate(your_list))) like the accepted answer says. But this creates a copy of your list, so if your list is taking up a large portion of your memory you'll have to subtract the index returned by enumerate(reversed()) from len()-1.

If you just need to do it once:

a = ['b', 'd', 'c', 'a']

for index, value in enumerate(reversed(a)):
    index = len(a)-1 - index

    do_something(index, value)

or if you need to do this multiple times you should use a generator:

def enumerate_reversed(lyst):
    for index, value in enumerate(reversed(lyst)):
        index = len(lyst)-1 - index
        yield index, value

for index, value in enumerate_reversed(a):
    do_something(index, value)

jQuery changing css class to div

An HTML element like div can have more than one classes. Let say div is assigned two styles using addClass method. If style1 has 3 properties like font-size, weight and color, and style2 has 4 properties like font-size, weight, color and background-color, the resultant effective properties set (style), i think, will have 4 properties i.e. union of all style sets. Common properties, in our case, color,font-size, weight, will have one occuerance with latest values. If div is assigned style1 first and style2 second, the common prpoerties will be overwritten by style2 values.

Further, I have written a post at Using JQuery to Apply,Remove and Manage Styles, I hope it will help you

Regards Awais

How to style child components from parent component's CSS file?

Sadly it appears that the /deep/ selector is deprecated (at least in Chrome) https://www.chromestatus.com/features/6750456638341120

In short it appears there is (currently) no long term solution other than to somehow get your child component to style things dynamically.

You could pass a style object to your child and have it applied via:
<div [attr.style]="styleobject">

Or if you have a specific style you can use something like:
<div [style.background-color]="colorvar">

More discussion related to this: https://github.com/angular/angular/issues/6511

How to handle a single quote in Oracle SQL

I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;

SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;


Result: Paddy O'Reilly

jQuery and AJAX response header

The underlying XMLHttpRequest object used by jQuery will always silently follow redirects rather than return a 302 status code. Therefore, you can't use jQuery's AJAX request functionality to get the returned URL. Instead, you need to put all the data into a form and submit the form with the target attribute set to the value of the name attribute of the iframe:

$('#myIframe').attr('name', 'myIframe');

var form = $('<form method="POST" action="url.do"></form>').attr('target', 'myIframe');
$('<input type="hidden" />').attr({name: 'search', value: 'test'}).appendTo(form);

form.appendTo(document.body);
form.submit();

The server's url.do page will be loaded in the iframe, but when its 302 status arrives, the iframe will be redirected to the final destination.

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

Try to delete the .IntelliJIdea15(depends on version) from C:\Users\Username

When you start IntelliJ it will create the folder again.

Disabling the button after once click

jQuery .one() should not be used with the click event but with the submit event as described below.

 $('input[type=submit]').one('submit', function() {
     $(this).attr('disabled','disabled');
 });

How to handle ETIMEDOUT error?

In case if you are using node js, then this could be the possible solution

const express = require("express");
const app = express();
const server = app.listen(8080);
server.keepAliveTimeout = 61 * 1000;

https://medium.com/hk01-tech/running-eks-in-production-for-2-years-the-kubernetes-journey-at-hk01-68130e603d76

Send request to curl with post data sourced from a file

If you are using form data to upload file,in which a parameter name must be specified , you can use:

curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx

Using JAXB to unmarshal/marshal a List<String>

User1's example worked well for me. But, as a warning, it won't work with anything other than simple String/Integer types, unless you add an @XmlSeeAlso annotation:

@XmlRootElement(name = "List")
@XmlSeeAlso(MovieTicket.class)
public class MovieTicketList {
    protected List<MovieTicket> list;

This works OK, although it prevents me from using a single generic list class across my entire application. It might also explain why this seemingly obvious class doesn't exist in the JAXB package.

CSV in Python adding an extra carriage return, on Windows

Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.

How to debug ORA-01775: looping chain of synonyms?

http://ora-01775.ora-code.com/ suggests:

ORA-01775: looping chain of synonyms
Cause: Through a series of CREATE synonym statements, a synonym was defined that referred to itself. For example, the following definitions are circular:
CREATE SYNONYM s1 for s2 CREATE SYNONYM s2 for s3 CREATE SYNONYM s3 for s1
Action: Change one synonym definition so that it applies to a base table or view and retry the operation.

Matplotlib - Move X-Axis label downwards, but not X-Axis Ticks

If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):

    bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
    bbox = mtransforms.Bbox.union(bboxes)
    bottom = bbox.y0
    x, y = self.label.get_position()
    self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))

You can set the label position independently of the ticks by using:

    ax.xaxis.set_label_coords(x0, y0)

that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.

Writing your own square root function

The inverse, as the name says, but sometimes "close enough" is "close enough"; an interesting read anyway.

Origin of Quake3's Fast InvSqrt()

How to get main div container to align to centre?

You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Just add the column names, yes you can use Null instead but is is a very bad idea to not use column names in any insert, ever.

Parse String date in (yyyy-MM-dd) format

I convert String to Date in format ("yyyy-MM-dd") to save into Mysql data base .

 String date ="2016-05-01";
 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 Date parsed = format.parse(date);
 java.sql.Date sql = new java.sql.Date(parsed.getTime());

sql it's my output in date format

typescript - cloning object

Since TypeScript 3.7 is released, recursive type aliases are now supported and it allows us to define a type safe deepCopy() function:

// DeepCopy type can be easily extended by other types,
// like Set & Map if the implementation supports them.
type DeepCopy<T> =
    T extends undefined | null | boolean | string | number ? T :
    T extends Function | Set<any> | Map<any, any> ? unknown :
    T extends ReadonlyArray<infer U> ? Array<DeepCopy<U>> :
    { [K in keyof T]: DeepCopy<T[K]> };

function deepCopy<T>(obj: T): DeepCopy<T> {
    // implementation doesn't matter, just use the simplest
    return JSON.parse(JSON.stringify(obj));
}

interface User {
    name: string,
    achievements: readonly string[],
    extras?: {
        city: string;
    }
}

type UncopiableUser = User & {
    delete: () => void
};

declare const user: User;
const userCopy: User = deepCopy(user); // no errors

declare const uncopiableUser: UncopiableUser;
const uncopiableUserCopy: UncopiableUser = deepCopy(uncopiableUser); // compile time error

Playground

react-router scroll to top on every transition

For smaller apps, with 1-4 routes, you could try to hack it with redirect to the top DOM element with #id instead just a route. Then there is no need to wrap Routes in ScrollToTop or using lifecycle methods.

Reading PDF content with itextsharp dll in VB.NET or C#

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;

public string ReadPdfFile(string fileName)
{
    StringBuilder text = new StringBuilder();

    if (File.Exists(fileName))
    {
        PdfReader pdfReader = new PdfReader(fileName);

        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
        {
            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.Append(currentText);
        }
        pdfReader.Close();
    }
    return text.ToString();
}

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

try using a different valid login using RUNAS command

runas /user:domain\user “C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\ssmsee.exe” 

runas /user:domain\user “C:\WINDOWS\system32\mmc.exe /s \”C:\Program Files\Microsoft SQL Server\80\Tools\BINN\SQL Server Enterprise Manager.MSC\”" 

runas /user:domain\user isqlw 

How to make Google Fonts work in IE?

For what its worth, I couldn't get it working on IE7/8/9 and the multiple declaration option didn't make any difference.

The fix for me was as a result of the instructions on the Technical Considerations Page where it highlights...

For best display in IE, make the stylesheet 'link' tag the first element in the HTML 'head' section.

Works across IE7/8/9 for me now.

How do I find out which keystore was used to sign an app?

You can use Java 7's Key and Certificate Management Tool keytool to check the signature of a keystore or an APK without extracting any files.

Signature of an APK or AAB

# APK file
keytool -printcert -jarfile app.apk

# AAB file
keytool -printcert -jarfile app.aab

The output will reveal the signature owner/issuer and MD5, SHA1 and SHA256 fingerprints of the APK file app.apk or AAB file app.aab.

(Note that the -jarfile argument was introduced in Java 7; see the documentation for more details.)

Signature of a keystore

keytool -list -v -keystore release.jks

The output will reveal the aliases (entries) in the keystore file release.jks, with the certificate fingerprints (MD5, SHA1 and SHA256).

If the SHA1 fingerprints between the APK and the keystore match, then you can rest assured that that app is signed with the key.

Why does flexbox stretch my image rather than retaining aspect ratio?

I faced the same issue with a Foundation menu. align-self: center; didn't work for me.

My solution was to wrap the image with a <div style="display: inline-table;">...</div>

pandas how to check dtype for all columns in a dataframe?

Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:

df.info()

OraOLEDB.Oracle provider is not registered on the local machine

My team would stumble upon this issue every now and then in random machines that we would try to install our platform in (we use oracle drivers 12c ver 12.2.0.4 but we came across this bug with other versions as well)

After quite a bit of experimentation we realized what was wrong:

Said machines would have apps that were using the machine-wide oracle drivers silently locking them and preventing the oracle driver-installer from working its magic when would attempt to upgrade/reinstall said oracle-drivers. The sneakiest "app" would be websites running in IIS and the like because these apps essentially auto-start on reboot. To counter this we do the following:

  1. Disable IIS from starting automagically on restart. Do the same for any other apps/services that auto-start themselves on reboot.
  2. Uninstall any previous Oracle driver and double-check that there are no traces left behind in registry or folders.
  3. Reboot the machine
  4. (Re)Install the Oracle drivers and re-enable IIS and other auto-start apps.
  5. Reboot the machine <- This is vital. Oracle's OLE DB drivers won't work unless you reboot the machine.

If this doesn't work then rinse repeat until the OLE DB drivers work. Hope this helps someone out there struggling to figure out what's going on.

How do I test if a recordSet is empty? isNull?

If temp_rst1.BOF and temp_rst1.EOF then the recordset is empty. This will always be true for an empty recordset, linked or local.

Getting the class of the element that fired an event using JQuery

Try:

$(document).ready(function() {
    $("a").click(function(event) {
       alert(event.target.id+" and "+$(event.target).attr('class'));
    });
});

JavaScript hide/show element

You can also use this code to show/hide elements:

document.getElementById(id).style.visibility = "hidden";
document.getElementById(id).style.visibility = "visible";

Note The difference between style.visibility and style.display is when using visibility:hidden unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.

See this link to see the differences.

ImportError: No module named requests

In my case requests was already installed, but needed an upgrade. The following command did the trick

$ sudo pip install requests --upgrade

How to use View.OnTouchListener instead of onClick

Presumably, if one wants to use an OnTouchListener rather than an OnClickListener, then the extra functionality of the OnTouchListener is needed. This is a supplemental answer to show more detail of how an OnTouchListener can be used.

Define the listener

Put this somewhere in your activity or fragment.

private View.OnTouchListener handleTouch = new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i("TAG", "touched down");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i("TAG", "moving: (" + x + ", " + y + ")");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("TAG", "touched up");
                break;
        }

        return true;
    }
};

Set the listener

Set the listener in onCreate (for an Activity) or onCreateView (for a Fragment).

myView.setOnTouchListener(handleTouch);

Notes

  • getX and getY give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX and getRawY if you want the absolute screen coordinates.
  • You can use the x and y values to determine things like swipe direction.

setup.py examples?

READ THIS FIRST https://packaging.python.org/en/latest/current.html

Installation Tool Recommendations

  1. Use pip to install Python packages from PyPI.
  2. Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.
  3. Use pip wheel to create a cache of wheel distributions, for the purpose of > speeding up subsequent installations.
  4. If you’re looking for management of fully integrated cross-platform software stacks, consider buildout (primarily focused on the web development community) or Hashdist, or conda (both primarily focused on the scientific community).

Packaging Tool Recommendations

  1. Use setuptools to define projects and create Source Distributions.
  2. Use the bdist_wheel setuptools extension available from the wheel project to create wheels. This is especially beneficial, if your project contains binary extensions.
  3. Use twine for uploading distributions to PyPI.

This anwser has aged, and indeed there is a rescue plan for python packaging world called

wheels way

I qoute pythonwheels.com here:

What are wheels?

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

Advantages of wheels

  1. Faster installation for pure python and native C extension packages.
  2. Avoids arbitrary code execution for installation. (Avoids setup.py)
  3. Installation of a C extension does not require a compiler on Windows or OS X.
  4. Allows better caching for testing and continuous integration.
  5. Creates .pyc files as part of installation to ensure they match the python interpreter used.
  6. More consistent installs across platforms and machines.

The full story of correct python packaging (and about wheels) is covered at packaging.python.org


conda way

For scientific computing (this is also recommended on packaging.python.org, see above) I would consider using CONDA packaging which can be seen as a 3rd party service build on top of PyPI and pip tools. It also works great on setting up your own version of binstar so I would imagine it can do the trick for sophisticated custom enterprise package management.

Conda can be installed into a user folder (no super user permisssions) and works like magic with

conda install

and powerful virtual env expansion.


eggs way

This option was related to python-distribute.org and is largerly outdated (as well as the site) so let me point you to one of the ready to use yet compact setup.py examples I like:

  • A very practical example/implementation of mixing scripts and single python files into setup.py is giving here
  • Even better one from hyperopt

This quote was taken from the guide on the state of setup.py and still applies:

  • setup.py gone!
  • distutils gone!
  • distribute gone!
  • pip and virtualenv here to stay!
  • eggs ... gone!

I add one more point (from me)

  • wheels!

I would recommend to get some understanding of packaging-ecosystem (from the guide pointed by gotgenes) before attempting mindless copy-pasting.

Most of examples out there in the Internet start with

from distutils.core import setup

but this for example does not support building an egg python setup.py bdist_egg (as well as some other old features), which were available in

from setuptools import setup

And the reason is that they are deprecated.

Now according to the guide

Warning

Please use the Distribute package rather than the Setuptools package because there are problems in this package that can and will not be fixed.

deprecated setuptools are to be replaced by distutils2, which "will be part of the standard library in Python 3.3". I must say I liked setuptools and eggs and have not yet been completely convinced by convenience of distutils2. It requires

pip install Distutils2

and to install

python -m distutils2.run install

PS

Packaging never was trivial (one learns this by trying to develop a new one), so I assume a lot of things have gone for reason. I just hope this time it will be is done correctly.

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

How can I send an xml body using requests library?

Pass in the straight XML instead of a dictionary.

Sending HTTP POST with System.Net.WebClient

As far as the http verb is concerned the WebRequest might be easier. You could go for something like:

    WebRequest r = WebRequest.Create("http://some.url");
    r.Method = "POST";
    using (var s = r.GetResponse().GetResponseStream())
    {
        using (var reader = new StreamReader(r, FileMode.Open))
        {
            var content = reader.ReadToEnd();
        }
    }

Obviously this lacks exception handling and writing the request body (for which you can use r.GetRequestStream() and write it like a regular stream, but I hope it may be of some help.

Python to print out status bar and percentage

For Python 3.6 the following works for me to update the output inline:

for current_epoch in range(10):
    for current_step) in range(100):
        print("Train epoch %s: Step %s" % (current_epoch, current_step), end="\r")
print()

UILabel text margin

You can also solve this by initializing your UILabel with a custom frame.

    CGRect initialFrame = CGRectMake(0, 0, 100, 100);
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    CGRect paddedFrame = UIEdgeInsetsInsetRect(initialFrame, contentInsets);

    self.label = [[UILabel alloc] initWithFrame:paddedFrame];

Nod to CGRect Tricks.

Splitting strings in PHP and get last part

To satisfy the requirement that "it needs to be as fast as possible" I ran a benchmark against some possible solutions. Each solution had to satisfy this set of test cases.

$cases = [
    'aaa-zzz'                     => 'zzz',
    'zzz'                         => 'zzz',
    '-zzz'                        => 'zzz',
    'aaa-'                        => '',
    ''                            => '',
    'aaa-bbb-ccc-ddd-eee-fff-zzz' => 'zzz',
];

Here are the solutions:

function test_substr($str, $delimiter = '-') {
    $idx = strrpos($str, $delimiter);
    return $idx === false ? $str : substr($str, $idx + 1);
}

function test_end_index($str, $delimiter = '-') {
    $arr = explode($delimiter, $str);
    return $arr[count($arr) - 1];
}

function test_end_explode($str, $delimiter = '-') {
    $arr = explode($delimiter, $str);
    return end($arr);
}

function test_end_preg_split($str, $pattern = '/-/') {
    $arr = preg_split($pattern, $str);
    return end($arr);
}

Here are the results after each solution was run against the test cases 1,000,000 times:

test_substr               : 1.706 sec
test_end_index            : 2.131 sec  +0.425 sec  +25%
test_end_explode          : 2.199 sec  +0.493 sec  +29%
test_end_preg_split       : 2.775 sec  +1.069 sec  +63%

So turns out the fastest of these was using substr with strpos. Note that in this solution we must check strpos for false so we can return the full string (catering for the zzz case).

Adding a new entry to the PATH variable in ZSH

Here, add this line to .zshrc:

export PATH=/home/david/pear/bin:$PATH

EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH. This approach is standard for bash, but as far as I know, there is no reason to use it when ZSH provides better alternatives.

How to access session variables from any class in ASP.NET?

Access the Session via the thread's HttpContext:-

HttpContext.Current.Session["loginId"]

Splitting dataframe into multiple dataframes

In [28]: df = DataFrame(np.random.randn(1000000,10))

In [29]: df
Out[29]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000000 entries, 0 to 999999
Data columns (total 10 columns):
0    1000000  non-null values
1    1000000  non-null values
2    1000000  non-null values
3    1000000  non-null values
4    1000000  non-null values
5    1000000  non-null values
6    1000000  non-null values
7    1000000  non-null values
8    1000000  non-null values
9    1000000  non-null values
dtypes: float64(10)

In [30]: frames = [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]

In [31]: %timeit [ df.iloc[i*60:min((i+1)*60,len(df))] for i in xrange(int(len(df)/60.) + 1) ]
1 loops, best of 3: 849 ms per loop

In [32]: len(frames)
Out[32]: 16667

Here's a groupby way (and you could do an arbitrary apply rather than sum)

In [9]: g = df.groupby(lambda x: x/60)

In [8]: g.sum()    

Out[8]: 
<class 'pandas.core.frame.DataFrame'>
Int64Index: 16667 entries, 0 to 16666
Data columns (total 10 columns):
0    16667  non-null values
1    16667  non-null values
2    16667  non-null values
3    16667  non-null values
4    16667  non-null values
5    16667  non-null values
6    16667  non-null values
7    16667  non-null values
8    16667  non-null values
9    16667  non-null values
dtypes: float64(10)

Sum is cythonized that's why this is so fast

In [10]: %timeit g.sum()
10 loops, best of 3: 27.5 ms per loop

In [11]: %timeit df.groupby(lambda x: x/60)
1 loops, best of 3: 231 ms per loop

Mongoose's find method with $or condition does not work properly

async() => {
let body = await model.find().or([
  { name: 'something'},
  { nickname: 'somethang'}
]).exec();
console.log(body);
}
/* Gives an array of the searched query!
returns [] if not found */

Simple way to convert datarow array to datatable

Incase anyone needs it in VB.NET:

Dim dataRow as DataRow
Dim yourNewDataTable as new datatable
For Each dataRow In yourArray
     yourNewDataTable.ImportRow(dataRow)
Next

Javascript: Fetch DELETE and PUT requests

Here is a fetch POST example. You can do the same for DELETE.

function createNewProfile(profile) {
    const formData = new FormData();
    formData.append('first_name', profile.firstName);
    formData.append('last_name', profile.lastName);
    formData.append('email', profile.email);

    return fetch('http://example.com/api/v1/registration', {
        method: 'POST',
        body: formData
    }).then(response => response.json())
}

createNewProfile(profile)
   .then((json) => {
       // handle success
    })
   .catch(error => error);

Tensorflow import error: No module named 'tensorflow'

for python 3.8 version go for anaconda navigator then go for environments --> then go for base(root)----> not installed from drop box--->then search for tensorflow then install it then run the program.......hope it may helpful

How to read a file into vector in C++?

Just to expand on juanchopanza's answer a bit...

for (int i=0; i=((Main.size())-1); i++) {
    cout << Main[i] << '\n';
}

does this:

  1. Create i and set it to 0.
  2. Set i to Main.size() - 1. Since Main is empty, Main.size() is 0, and i gets set to -1.
  3. Main[-1] is an out-of-bounds access. Kaboom.

Javascript - validation, numbers only

// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:

$(document).ready(function () {
       $(".nosonly").keydown(function (event) {
           // Allow only backspace and delete
           if (event.keyCode == 46 || event.keyCode == 8) {
               // let it happen, don't do anything
           }
           else {
               // Ensure that it is a number and stop the keypress
               if (event.keyCode < 48 || event.keyCode > 57) {
              alert("Only Numbers Allowed"),event.preventDefault();
               }
           }
       });
   });

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry

public static String getRealPathFromUri(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

This will end up giving you an absolute file path that you can construct a file uri from

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

How to format a java.sql Timestamp for displaying?

String timeFrSSHStr = timeFrSSH.toString();

What is the equivalent of Java static methods in Kotlin?

A lot of people mention companion objects, which is correct. But, just so you know, you can also use any sort of object (using the object keyword, not class) i.e.,

object StringUtils {
    fun toUpper(s: String) : String { ... }
}

Use it just like any static method in java:

StringUtils.toUpper("foobar")

That sort of pattern is kind of useless in Kotlin though, one of its strengths is that it gets rid of the need for classes filled with static methods. It is more appropriate to utilize global, extension and/or local functions instead, depending on your use case. Where I work we often define global extension functions in a separate, flat file with the naming convention: [className]Extensions.kt i.e., FooExtensions.kt. But more typically we write functions where they are needed inside their operating class or object.

How to stick text to the bottom of the page?

From my research and starting on this post, i think this is the best option:

_x000D_
_x000D_
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">This will stick at the botton no matter what :).</p> 
_x000D_
_x000D_
_x000D_

This option allow resizes of the page and even if the page is blank it will stick at the bottom.

Parsing command-line arguments in C

Qt 5.2 comes with a command line parser API.

Small example:

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QDebug>

int main(int argc, char **argv)
{
  QCoreApplication app(argc, argv);
  app.setApplicationName("ToolX");
  app.setApplicationVersion("1.2");

  QCommandLineParser parser;
  parser.setApplicationDescription("Tool for doing X.");
  parser.addHelpOption();
  parser.addVersionOption();
  parser.addPositionalArgument("infile",
      QCoreApplication::translate("main", "Input file."));

  QCommandLineOption verbose_opt("+",
      QCoreApplication::translate("main", "be verbose"));
  parser.addOption(verbose_opt);

  QCommandLineOption out_opt(QStringList() << "o" << "output",
      QCoreApplication::translate("main", "Output file."),
      QCoreApplication::translate("main", "filename"), // value name
      QCoreApplication::translate("main", "out")   // default value
      );
  parser.addOption(out_opt);

  // exits on error
  parser.process(app);

  const QStringList args = parser.positionalArguments();

  qDebug() << "Input files: " << args
    << ", verbose: " << parser.isSet(verbose_opt)
    << ", output: " << parser.value(out_opt)
    << '\n';
  return 0;
}

Example output

The automatically generated help screen:

$ ./qtopt -h
Usage: ./qtopt [options] infile
Tool for doing X.

Options:
  -h, --help               Displays this help.
  -v, --version            Displays version information.
  -+                       be verbose
  -o, --output   Output file.

Arguments:
  infile                   Input file.

Automatically generated version output:

$ ./qtopt -v
ToolX 1.2

Some real calls:

$ ./qtopt b1 -+ -o tmp blah.foo
Input files:  ("b1", "blah.foo") , verbose:  true , output:  "tmp"
$ ./qtopt          
Input files:  () , verbose:  false , output:  "out"

A parse error:

$ ./qtopt --hlp
Unknown option 'hlp'.
$ echo $?
1

Conclusion

If your program already use the Qt (>= 5.2) libraries, its command line parsing API is convenient enough to get the job done.

Be aware that builtin Qt options are consumed by QApplication before the option parser runs.

mkdir's "-p" option

Note that -p is an argument to the mkdir command specifically, not the whole of Unix. Every command can have whatever arguments it needs.

In this case it means "parents", meaning mkdir will create a directory and any parents that don't already exist.

Default passwords of Oracle 11g?

Once installed in windows Followed the instructions starting from Run SQL Command Line (command prompt)

then... v. SQL> connect /as sysdba

Connected. [SQL prompt response]

vi. SQL> alter user SYS identified by "newpassword";

User altered. [SQL prompt response]

Thank you. This minimized a headache

How can I write these variables into one line of code in C#?

Simple as:

DateTime.Now.ToString("MM.dd.yyyy");

link to MSDN on ALL formatting options for DateTime.ToString() method

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

Twitter bootstrap float div right

You can assign the class name like text-center, left or right. The text will align accordingly to these class name. You don't need to make extra class name separately. These classes are built in BootStrap 3 and bootstrap 4.

Bootstrap 3

v3 Text Alignment Docs

<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>

Bootstrap 4

v4 Text Alignment Docs

<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

What are the First and Second Level caches in (N)Hibernate?

1.1) First-level cache

First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.

1.2) Second-level cache

Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.

Quoted from: http://javabeat.net/introduction-to-hibernate-caching/

ios simulator: how to close an app

You can also kill the app by process id

ps -cx -o pid,command | awk '$2 == "YourAppNameCaseSensitive" { print $1 }' | xargs kill -9

Convert JSONObject to Map

You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.

HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);

How to check if all elements of a list matches a condition?

Another way to use itertools.ifilter. This checks truthiness and process (using lambda)

Sample-

for x in itertools.ifilter(lambda x: x[2] == 0, my_list):
    print x

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

How to get HttpClient to pass credentials along with the request?

In .NET Core, I managed to get a System.Net.Http.HttpClient with UseDefaultCredentials = true to pass through the authenticated user's Windows credentials to a back end service by using WindowsIdentity.RunImpersonated.

HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true } );
HttpResponseMessage response = null;

if (identity is WindowsIdentity windowsIdentity)
{
    await WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, async () =>
    {
        var request = new HttpRequestMessage(HttpMethod.Get, url)
        response = await client.SendAsync(request);
    });
}