Programs & Examples On #Enyim

How to change Hash values?

I do something like this:

new_hash = Hash[*original_hash.collect{|key,value| [key,value + 1]}.flatten]

This provides you with the facilities to transform the key or value via any expression also (and it's non-destructive, of course).

error LNK2005, already defined?

In the Project’s Settings, add /FORCE:MULTIPLE to the Linker’s Command Line options.

From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."

Better way to find control in ASP.NET

I decided to just build controls dictionaries. Harder to maintain, might run faster than the recursive FindControl().

protected void Page_Load(object sender, EventArgs e)
{
  this.BuildControlDics();
}

private void BuildControlDics()
{
  _Divs = new Dictionary<MyEnum, HtmlContainerControl>();
  _Divs.Add(MyEnum.One, this.divOne);
  _Divs.Add(MyEnum.Two, this.divTwo);
  _Divs.Add(MyEnum.Three, this.divThree);

}

And before I get down-thumbs for not answering the OP's question...

Q: Now, my question is that is there any other way/solution to find the nested control in ASP.NET? A: Yes, avoid the need to search for them in the first place. Why search for things you already know are there? Better to build a system allowing reference of known objects.

How to download and save an image in Android

I have a simple solution which is working perfectly. The code is not mine, I found it on this link. Here are the steps to follow:

1. Before downloading the image, let’s write a method for saving bitmap into an image file in the internal storage in android. It needs a context, better to use the pass in the application context by getApplicationContext(). This method can be dumped into your Activity class or other util classes.

public void saveImage(Context context, Bitmap b, String imageName) 
{
    FileOutputStream foStream;
    try 
    {
        foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
        b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
        foStream.close();
    } 
    catch (Exception e) 
    {
        Log.d("saveImage", "Exception 2, Something went wrong!");
        e.printStackTrace();
    }
}

2. Now we have a method to save bitmap into an image file in andorid, let’s write the AsyncTask for downloading images by url. This private class need to be placed in your Activity class as a subclass. After the image is downloaded, in the onPostExecute method, it calls the saveImage method defined above to save the image. Note, the image name is hardcoded as “my_image.png”.

private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    private String TAG = "DownloadImage";
    private Bitmap downloadImageBitmap(String sUrl) {
        Bitmap bitmap = null;
        try {
            InputStream inputStream = new URL(sUrl).openStream();   // Download Image from URL
            bitmap = BitmapFactory.decodeStream(inputStream);       // Decode Bitmap
            inputStream.close();
        } catch (Exception e) {
            Log.d(TAG, "Exception 1, Something went wrong!");
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        return downloadImageBitmap(params[0]);
    }

    protected void onPostExecute(Bitmap result) {
        saveImage(getApplicationContext(), result, "my_image.png");
    }
}

3. The AsyncTask for downloading the image is defined, but we need to execute it in order to run that AsyncTask. To do so, write this line in your onCreate method in your Activity class, or in an onClick method of a button or other places you see fit.

new DownloadImage().execute("http://developer.android.com/images/activity_lifecycle.png");

The image should be saved in /data/data/your.app.packagename/files/my_image.jpeg, check this post for accessing this directory from your device.

IMO this solves the issue! If you want further steps such as load the image you can follow these extra steps:

4. After the image is downloaded, we need a way to load the image bitmap from the internal storage, so we can use it. Let’s write the method for loading the image bitmap. This method takes two paramethers, a context and an image file name, without the full path, the context.openFileInput(imageName) will look up the file at the save directory when this file name was saved in the above saveImage method.

public Bitmap loadImageBitmap(Context context, String imageName) {
    Bitmap bitmap = null;
    FileInputStream fiStream;
    try {
        fiStream    = context.openFileInput(imageName);
        bitmap      = BitmapFactory.decodeStream(fiStream);
        fiStream.close();
    } catch (Exception e) {
        Log.d("saveImage", "Exception 3, Something went wrong!");
        e.printStackTrace();
    }
    return bitmap;
}

5. Now we have everything we needed for setting the image of an ImageView or any other Views that you like to use the image on. When we save the image, we hardcoded the image name as “my_image.jpeg”, now we can pass this image name to the above loadImageBitmap method to get the bitmap and set it to an ImageView.

someImageView.setImageBitmap(loadImageBitmap(getApplicationContext(), "my_image.jpeg"));

6. To get the image full path by image name.

File file            = getApplicationContext().getFileStreamPath("my_image.jpeg");
String imageFullPath = file.getAbsolutePath();

7. Check if the image file exists.

File file =

getApplicationContext().getFileStreamPath("my_image.jpeg");
if (file.exists()) Log.d("file", "my_image.jpeg exists!");
  1. To delete the image file.

    File file = getApplicationContext().getFileStreamPath("my_image.jpeg"); if (file.delete()) Log.d("file", "my_image.jpeg deleted!");

static function in C

Looking at the posts above I would like to give a more clarified answer:

Suppose our main.c file looks like this:

#include "header.h"

int main(void) {
    FunctionInHeader();
}

Now consider three cases:

  • Case 1: Our header.h file looks like this:

     #include <stdio.h>
    
     static void FunctionInHeader();
    
     void FunctionInHeader() {
         printf("Calling function inside header\n");
     }
    

    Then the following command on linux:

     gcc main.c -o main
    

    will succeed! That's because after the main.c file includes the header.h, the static function definition will be in the same main.c file (more precisely, in the same translation unit) to where it's called.

    If one runs ./main, the output will be Calling function inside header, which is what that static function should print.

  • Case 2: Our header header.h looks like this:

      static void FunctionInHeader();     
    

    and we also have one more file header.c, which looks like this:

      #include <stdio.h>
      #include "header.h"
    
      void FunctionInHeader() {
          printf("Calling function inside header\n");
      }
    

    Then the following command

      gcc main.c header.c -o main
    

    will give an error. In this case main.c includes only the declaration of the static function, but the definition is left in another translation unit and the static keyword prevents the code defining a function to be linked

  • Case 3:

    Similar to case 2, except that now our header header.h file is:

      void FunctionInHeader(); // keyword static removed
    

    Then the same command as in case 2 will succeed, and further executing ./main will give the expected result. Here the FunctionInHeader definition is in another translation unit, but the code defining it can be linked.

Thus, to conclude:

static keyword prevents the code defining a function to be linked,
when that function is defined in another translation unit than where it is called.

What does \u003C mean?

It is a unicode char \u003C = <

How can I add new dimensions to a Numpy array?

You can use np.concatenate() specifying which axis to append, using np.newaxis:

import numpy as np
movie = np.concatenate((img1[:,np.newaxis], img2[:,np.newaxis]), axis=3)

If you are reading from many files:

import glob
movie = np.concatenate([cv2.imread(p)[:,np.newaxis] for p in glob.glob('*.jpg')], axis=3)

Combining multiple condition in single case statement in Sql Server

You can put the condition after the WHEN clause, like so:

SELECT
  CASE
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.ELIGIBILITY is null THEN 'Favor'
    WHEN PAT_ENT.SCR_DT is not null and PAT_ENTRY.EL = 'No' THEN 'Error'
    WHEN PAT_ENTRY.EL = 'Yes' and ISNULL(DS.DES, 'OFF') = 'OFF' THEN 'Active'
    WHEN DS.DES = 'N' THEN 'Early Term'
    WHEN DS.DES = 'Y' THEN 'Complete'
  END
FROM
  ....

Of course, the argument could be made that complex rules like this belong in your business logic layer, not in a stored procedure in the database...

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

Reading file using fscanf() in C

In your code:

while(fscanf(fp,"%s %c",item,&status) == 1)  

why 1 and not 2? The scanf functions return the number of objects read.

PHP - regex to allow letters and numbers only

1. Use PHP's inbuilt ctype_alnum

You dont need to use a regex for this, PHP has an inbuilt function ctype_alnum which will do this for you, and execute faster:

<?php
$strings = array('AbCd1zyZ9', 'foo!#$bar');
foreach ($strings as $testcase) {
    if (ctype_alnum($testcase)) {
        echo "The string $testcase consists of all letters or digits.\n";
    } else {
        echo "The string $testcase does not consist of all letters or digits.\n";
    }
}
?>

2. Alternatively, use a regex

If you desperately want to use a regex, you have a few options.

Firstly:

preg_match('/^[\w]+$/', $string);

\w includes more than alphanumeric (it includes underscore), but includes all of \d.

Alternatively:

/^[a-zA-Z\d]+$/

Or even just:

/^[^\W_]+$/

How can I get date and time formats based on Culture Info?

Culture can be changed for a specific cell in grid view.

<%# DateTime.ParseExact(Eval("contractdate", "{0}"), "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture) %>

For more detail check the link.

Date Format Issue in Gridview binding with #eval()

How to auto adjust table td width from the content

you could also use display: table insted of tables. Divs are way more flexible than tables.

Example:

_x000D_
_x000D_
.table {_x000D_
   display: table;_x000D_
   border-collapse: collapse;_x000D_
}_x000D_
 _x000D_
.table .table-row {_x000D_
   display: table-row;_x000D_
}_x000D_
 _x000D_
.table .table-cell {_x000D_
   display: table-cell;_x000D_
   text-align: left;_x000D_
   vertical-align: top;_x000D_
   border: 1px solid black;_x000D_
}
_x000D_
<div class="table">_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test1123</div>_x000D_
 </div>_x000D_
 <div class="table-row">_x000D_
  <div class="table-cell">test</div>_x000D_
  <div class="table-cell">test123</div>_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is android:ems attribute in Edit Text?

Taken from: http://www.w3.org/Style/Examples/007/units:

The em is simply the font size. In an element with a 2in font, 1em thus means 2in. Expressing sizes, such as margins and paddings, in em means they are related to the font size, and if the user has a big font (e.g., on a big screen) or a small font (e.g., on a handheld device), the sizes will be in proportion. Declarations such as 'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.

em is basically CSS property for font sizes.

How to get JQuery.trigger('click'); to initiate a mouse click

This is JQuery behavior. I'm not sure why it works this way, it only triggers the onClick function on the link.

Try:

jQuery(document).ready(function() {
    jQuery('#foo').on('click', function() {
        jQuery('#bar')[0].click();
    });
});

Where does Vagrant download its .box files to?

To change the Path, you can set a new Path to an Enviroment-Variable named: VAGRANT_HOME

export VAGRANT_HOME=my/new/path/goes/here/

Thats maybe nice if you want to have those vagrant-Images on another HDD.

More Information here in the Documentations: http://docs.vagrantup.com/v2/other/environmental-variables.html

Create an array with random values

Refer below :-

let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */

Looping through the content of a file in Bash

One way to do it is:

while read p; do
  echo "$p"
done <peptides.txt

As pointed out in the comments, this has the side effects of trimming leading whitespace, interpreting backslash sequences, and skipping the last line if it's missing a terminating linefeed. If these are concerns, you can do:

while IFS="" read -r p || [ -n "$p" ]
do
  printf '%s\n' "$p"
done < peptides.txt

Exceptionally, if the loop body may read from standard input, you can open the file using a different file descriptor:

while read -u 10 p; do
  ...
done 10<peptides.txt

Here, 10 is just an arbitrary number (different from 0, 1, 2).

Preventing HTML and Script injections in Javascript

From here

var string="<script>...</script>";
string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3

Is there a way to use use text as the background with CSS?

It may be possible (but very hackish) with only CSS using the :before or :after pseudo elements:

_x000D_
_x000D_
.bgtext {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.bgtext:after {_x000D_
  content: "Background text";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: -1;_x000D_
}
_x000D_
<div class="bgtext">_x000D_
  Foreground text_x000D_
</div>
_x000D_
_x000D_
_x000D_

This seems to work, but you'll probably need to tweak it a little. Also note it won't work in IE6 because it doesn't support :after.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Check your code for errors in my case i had an error in Kernel.php. First solve errors if any Than run composer require ....(package you wish)

What is the difference between __str__ and __repr__?

One important thing to keep in mind is that container's __str__ uses contained objects' __repr__.

>>> from datetime import datetime
>>> from decimal import Decimal
>>> print (Decimal('52'), datetime.now())
(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 51, 26, 185000))
>>> str((Decimal('52'), datetime.now()))
"(Decimal('52'), datetime.datetime(2015, 11, 16, 10, 52, 22, 176000))"

Python favors unambiguity over readability, the __str__ call of a tuple calls the contained objects' __repr__, the "formal" representation of an object. Although the formal representation is harder to read than an informal one, it is unambiguous and more robust against bugs.

How do I check how many options there are in a dropdown menu?

$('#idofdropdown option').length;

That should do it.

versionCode vs versionName in Android Manifest

Given a version number MAJOR.MINOR.PATCH, increment the:


  • MAJOR version when you make incompatible API changes,
  • MINOR version when you add functionality in a backwards-compatible manner, and
  • PATCH version when you make backwards-compatible bug fixes.

Version Code & Version Name

As you may know, on android you have to define two version fields for an app: the version code (android:versionCode) and the version name (android:versionName). The version code is an incremental integer value that represents the version of the application code. The version name is a string value that represents the “friendly” version name displayed to the users.

Hide text within HTML?

Here are two ways you can achieve this

You can display none or have a opacity none...But if you want the opacity to be cross browser compatible you would have to add this to your css

/* IE 8 */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

/* IE 5-7 */
filter: alpha(opacity=50);

/* Netscape */
-moz-opacity: 0.5;

/* Safari 1.x */
-khtml-opacity: 0.5;

/* Good browsers */
opacity: 0.5;

http://codepen.io/anon/pen/Krkfj

How to format font style and color in echo

echo '< span style = "font-color: #ff0000"> Movie List for {$key} 2013 </span>';

How do I set hostname in docker-compose?

I needed to spin freeipa container to have a working kdc and had to give it a hostname otherwise it wouldn't run. What eventually did work for me is setting the HOSTNAME env variable in compose:

version: 2
services:
  freeipa:
    environment:
      - HOSTNAME=ipa.example.test

Now its working:

docker exec -it freeipa_freeipa_1 hostname
ipa.example.test

Android LinearLayout Gradient Background

It is also possible to have the third color (center). And different kinds of shapes.

For example in drawable/gradient.xml:

<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#000000"
        android:centerColor="#5b5b5b"
        android:endColor="#000000"
        android:angle="0" />
</shape>

This gives you black - gray - black (left to right) which is my favorite dark background atm.

Remember to add gradient.xml as background in your layout xml:

android:background="@drawable/gradient"

It is also possible to rotate, with:

angle="0"

gives you a vertical line

and with

angle="90"

gives you a horizontal line

Possible angles are:

0, 90, 180, 270.

Also there are few different kind of shapes:

android:shape="rectangle"

Rounded shape:

android:shape="oval"

and problably a few more.

Hope it helps, cheers!

How can I escape a double quote inside double quotes?

Use a backslash:

echo "\""     # Prints one " character.

PHP find difference between two datetimes

John Conde does all the right procedures in his method but doesn't satisfy the final step in your question which is to format the result to your specifications.

This code (Demo) will display the raw difference, expose the trouble with trying to immediately format the raw difference, display my preparation steps, and finally present the correctly formatted result:

$datetime1 = new DateTime('2017-04-26 18:13:06');
$datetime2 = new DateTime('2011-01-17 17:13:00');  // change the millenium to see output difference
$diff = $datetime1->diff($datetime2);

// this will get you very close, but it will not pad the digits to conform with your expected format
echo "Raw Difference: ",$diff->format('%y years %m months %d days %h hours %i minutes %s seconds'),"\n";

// Notice the impact when you change $datetime2's millenium from '1' to '2'
echo "Invalid format: ",$diff->format('%Y-%m-%d %H:%i:%s'),"\n";  // only H does it right

$details=array_intersect_key((array)$diff,array_flip(['y','m','d','h','i','s']));

echo '$detail array: ';
var_export($details);
echo "\n";

array_map(function($v,$k)
    use(&$r)
    {
        $r.=($k=='y'?str_pad($v,4,"0",STR_PAD_LEFT):str_pad($v,2,"0",STR_PAD_LEFT));
        if($k=='y' || $k=='m'){$r.="-";}
        elseif($k=='d'){$r.=" ";}
        elseif($k=='h' || $k=='i'){$r.=":";}
    },$details,array_keys($details)
);
echo "Valid format: ",$r; // now all components of datetime are properly padded

Output:

Raw Difference: 6 years 3 months 9 days 1 hours 0 minutes 6 seconds
Invalid format: 06-3-9 01:0:6
$detail array: array (
  'y' => 6,
  'm' => 3,
  'd' => 9,
  'h' => 1,
  'i' => 0,
  's' => 6,
)
Valid format: 0006-03-09 01:00:06

Now to explain my datetime value preparation:

$details takes the diff object and casts it as an array. array_flip(['y','m','d','h','i','s']) creates an array of keys which will be used to remove all irrelevant keys from (array)$diff using array_intersect_key().

Then using array_map() my method iterates each value and key in $details, pads its left side to the appropriate length with 0's, and concatenates the $r (result) string with the necessary separators to conform with requested datetime format.

Base64 PNG data to HTML5 canvas

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
    ctx.drawImage(image, 0, 0);
};
image.src = "data:image/  png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

Embed HTML5 YouTube video without iframe?

Yes, but it depends on what you mean by 'embed'; as far as I can tell after reading through the docs, it seems like you have a couple of options if you want to get around using the iframe API. You can use the javascript and flash API's (https://developers.google.com/youtube/player_parameters) to embed a player, but that involves creating Flash objects in your code (something I personally avoid, but not necessarily something that you have to). Below are some helpful sections from the dev docs for the Youtube API.

If you really want to get around all these methods and include video without any sort of iframe, then your best bet might be creating an HTML5 video player/app that can connect to the Youtube Data API (https://developers.google.com/youtube/v3/). I'm not sure what the extent of your needs are, but this would be the way to go if you really want to get around using any iframes or flash objects.

Hope this helps!


Useful:

(https://developers.google.com/youtube/player_parameters)

IFrame embeds using the IFrame Player API

Follow the IFrame Player API instructions to insert a video player in your web page or application after the Player API's JavaScript code has loaded. The second parameter in the constructor for the video player is an object that specifies player options. Within that object, the playerVars property identifies player parameters.

The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.

...

IFrame embeds using tags

Define an tag in your application in which the src URL specifies the content that the player will load as well as any other player parameters you want to set. The tag's height and width parameters specify the dimensions of the player.

If you are creating the element yourself (rather than using the IFrame Player API to create it), you can append player parameters directly to the end of the URL. The URL has the following format:

...

AS3 object embeds

Object embeds use an tag to specify the player's dimensions and parameters. The sample code below demonstrates how to use an object embed to load an AS3 player that automatically plays the same video as the previous two examples.

Error: class X is public should be declared in a file named X.java

Name of public class must match the name of .java file in which it is placed (like public class Foo{} must be placed in Foo.java file). So either:

  • rename your file from Main.java to WeatherArray.java
  • rename the class from public class WeatherArray { to public class Main {

Difference between a class and a module

I'm surprised anyone hasn't said this yet.

Since the asker came from a Java background (and so did I), here's an analogy that helps.

Classes are simply like Java classes.

Modules are like Java static classes. Think about Math class in Java. You don't instantiate it, and you reuse the methods in the static class (eg. Math.random()).

Close virtual keyboard on button press

For Activity,

InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

For Fragments, use getActivity()

getActivity().getSystemService();

getActivity().getCurrentFocus();

InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);

How can I escape a single quote?

Represent it as a text entity (ASCII 39):

<input type='text' id='abc' value='hel&#39;lo'>

PHP: Return all dates between two dates in an array

I think it's the shortest answer

Edit the code as you like

for ($x=strtotime('2015-12-01');$x<=strtotime('2015-12-30');$x+=86400)
echo date('Y-m-d',$x);

How to remove multiple indexes from a list at the same time?

Old question, but I have an answer.

First, peruse the elements of the list like so:

for x in range(len(yourlist)):
    print '%s: %s' % (x, yourlist[x])

Then, call this function with a list of the indexes of elements you want to pop. It's robust enough that the order of the list doesn't matter.

def multipop(yourlist, itemstopop):
    result = []
    itemstopop.sort()
    itemstopop = itemstopop[::-1]
    for x in itemstopop:
        result.append(yourlist.pop(x))
    return result

As a bonus, result should only contain elements you wanted to remove.

In [73]: mylist = ['a','b','c','d','charles']

In [76]: for x in range(len(mylist)):

      mylist[x])

....:

0: a

1: b

2: c

3: d

4: charles

...

In [77]: multipop(mylist, [0, 2, 4])

Out[77]: ['charles', 'c', 'a']

...

In [78]: mylist

Out[78]: ['b', 'd']

Difference between innerText, innerHTML and value?

to add to the list, innerText will keep your text-transform, innerHTML wont

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

just write "java -d64 -version" or d32 and if you have It installed it will give a response with current version installed

How to properly and completely close/reset a TcpClient connection?

The correct way to close the socket so you can re-open is:

tcpClient.Client.Disconnect(true);

The Boolean parameter indicates if you want to reuse the socket:

Disconnect method usage

How to show first commit by 'git log'?

I found that:

git log --reverse

shows commits from start.

jQuery Toggle Text?

jQuery.fn.extend({
        toggleText: function (a, b){
            var isClicked = false;
            var that = this;
            this.click(function (){
                if (isClicked) { that.text(a); isClicked = false; }
                else { that.text(b); isClicked = true; }
            });
            return this;
        }
    });

$('#someElement').toggleText("hello", "goodbye");

Extension for JQuery that only does toggling of text.

JSFiddle: http://jsfiddle.net/NKuhV/

target="_blank" vs. target="_new"

The target attribute of a link forces the browser to open the destination page in a new browser window. Using _blank as a target value will spawn a new window every time while using _new will only spawn one new window and every link clicked with a target value of _new will replace the page loaded in the previously spawned window

How do I clone a specific Git branch?

Here is a really simple way to do it :)

Clone the repository

git clone <repository_url>

List all branches

git branch -a 

Checkout the branch that you want

git checkout <name_of_branch>

Angularjs prevent form submission when input validation fails

So the suggested answer from TheHippo did not work for me, instead I ended up sending the form as a parameter to the function like so:

<form name="loginform" novalidate ng-submit="login.submit(loginForm)" class="css-form">

This makes the form available in the controller method:

$scope.login = {
    submit : function(form) {
        if(form.$valid)....
    }

Android: how to get the current day of the week (Monday, etc...) in the user's language?

If you are using ThreetenABP date library bt Jake Warthon you can do:

dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()

on your dayOfWeek instance. More at: https://github.com/JakeWharton/ThreeTenABP https://www.threeten.org/threetenbp/apidocs/org/threeten/bp/format/TextStyle.html

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

How does setTimeout work in Node.JS?

setTimeout is a kind of Thread, it holds a operation for a given time and execute.

setTimeout(function,time_in_mills);

in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.

setTimeout(function(){console.log('your name')},3000);

Key point to remember is, what ever you want to do by using the setTimeout method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:

setTimeout(function(){yourOtherMethod(parameter);},3000);

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

ES6 export default with multiple functions referring to each other

The export default {...} construction is just a shortcut for something like this:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { foo(); bar() }
}

export default funcs

It must become obvious now that there are no foo, bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export.

So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { funcs.foo(); funcs.bar() } // here is the fix
}

export default funcs

Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out.

Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:

function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }

export default {foo, bar, baz}

And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:

// util.js

export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }

export default {foo, bar, baz}

// a.js, using default export

import util from './util'
util.foo()

// b.js, using named exports

import {bar} from './util'
bar()

Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.

How to remove all the occurrences of a char in c++ string

string RemoveChar(string str, char c) 
{
   string result;
   for (size_t i = 0; i < str.size(); i++) 
   {
          char currentChar = str[i];
          if (currentChar != c)
              result += currentChar;
   }
       return result;
}

This is how I did it.

Or you could do as Antoine mentioned:

See this question which answers the same problem. In your case:

#include <algorithm>
str.erase(std::remove(str.begin(), str.end(), 'a'), str.end());

Does 'position: absolute' conflict with Flexbox?

No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.

That means that

  • If you add absolute positioning to an element with display: inline-flex, it will become block-level (like display: flex), but will still generate a flex formatting context.

  • If you add absolute positioning to an element with display: flex, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.

That said, absolutely positioning conflicts with flex children.

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

CSS way to horizontally align table

This should work:

<div style="text-align:center;">
  <table style="margin: 0 auto;">
    <!-- table markup here. -->
  </table>
</div>

JavaScript regex for alphanumeric string with length of 3-5 chars

First this script test the strings N having chars from 3 to 5.

For multi language (arabic, Ukrainian) you Must use this

var regex = /^([a-zA-Z0-9_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]+){3,5}$/;  regex.test('?????');

Other wise the below is for English Alphannumeric only

/^([a-zA-Z0-9_-]){3,5}$/

P.S the above dose not accept special characters

one final thing the above dose not take space as test it will fail if there is space if you want space then add after the 0-9\s

\s

And if you want to check lenght of all string add dot .

var regex = /^([a-zA-Z0-9\s@,!=%$#&_-\u0600-\u065f\u066a-\u06EF\u06fa-\u06ff\ufb8a\u067e\u0686\u06af\u0750-\u077f\ufb50-\ufbc1\ufbd3-\ufd3f\ufd50-\ufd8f\ufd92-\ufdc7\ufe70-\ufefc\uFDF0-\uFDFD]).{1,30}$/;

Where does application data file actually stored on android device?

Application Private Data files are stored within <internal_storage>/data/data/<package>

Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()

When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

In python, the str() method is similar to the toString() method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the __str__() method of the parameter object to get its string representation.

In this case, however, you are comparing a UserProperty author from the database, which is of type users.User with the nickname string. You will want to compare the nickname property of the author instead with todo.author.nickname in your template.

How can I get the actual video URL of a YouTube live stream?

This URL return to player actual video_id

https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA

Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.

How can I remove a character from a string using JavaScript?

A simple functional javascript way would be

mystring = mystring.split('/r').join('/')

simple, fast, it replace globally and no need for functions or prototypes

How do you add a Dictionary of items into another Dictionary

The same as @farhadf's answer but adopted for Swift 3:

let sourceDict1 = [1: "one", 2: "two"]
let sourceDict2 = [3: "three", 4: "four"]

let result = sourceDict1.reduce(sourceDict2) { (partialResult , pair) in
    var partialResult = partialResult //without this line we could not modify the dictionary
    partialResult[pair.0] = pair.1
    return partialResult
}

Return positions of a regex match() in Javascript?

In modern browsers, you can accomplish this with string.matchAll().

The benefit to this approach vs RegExp.exec() is that it does not rely on the regex being stateful, as in @Gumbo's answer.

_x000D_
_x000D_
let regexp = /bar/g;
let str = 'foobarfoobar';

let matches = [...str.matchAll(regexp)];
matches.forEach((match) => {
    console.log("match found at " + match.index);
});
_x000D_
_x000D_
_x000D_

How can I know which radio button is selected via jQuery?

How about this?

Using change and get the value of radio type is checked...

_x000D_
_x000D_
$('#my-radio-form').on('change', function() {_x000D_
  console.log($('[type="radio"]:checked').val());_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<form id="my-radio-form">_x000D_
  <input type="radio" name="input-radio" value="a" />a_x000D_
  <input type="radio" name="input-radio" value="b" />b_x000D_
  <input type="radio" name="input-radio" value="c" />c_x000D_
  <input type="radio" name="input-radio" value="d" />d_x000D_
</form>
_x000D_
_x000D_
_x000D_

CSS: 100% width or height while keeping aspect ratio?

Use JQuery or so, as CSS is a general misconception (the countless questions and discussions here about simple design goals show that).

It is not possible with CSS to do what you seem to wish: image shall have width of 100%, but if this width results in a height that is too large, a max-height shall apply - and of course the correct proportions shall be preserved.

datetime.parse and making it work with a specific format

Thanks for the tip, i used this to get my date "20071122" parsed, I needed to add datetimestyles, I used none and it worked:

DateTime dt = DateTime.MinValue;

DateTime.TryParseExact("20071122", "yyyyMMdd", null,System.Globalization.DateTimeStyles.None, out dt);

How can I remove punctuation from input text in Java?

If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:

public String modified(final String input){
    final StringBuilder builder = new StringBuilder();
    for(final char c : input.toCharArray())
        if(Character.isLetterOrDigit(c))
            builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
    return builder.toString();
}

It loops through the underlying char[] in the String and only appends the char if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char.

Cannot open include file 'afxres.h' in VC2010 Express

a similar issue is for Visual studio 2015 RC. Sometimes it loses the ability to open RC: you double click but editor do not one menus and dialogs.

Right click on the file *.rc, it will open:

enter image description here

And change as following:

enter image description here

Check if a number is a perfect square

Use Newton's method to quickly zero in on the nearest integer square root, then square it and see if it's your number. See isqrt.

Python = 3.8 has math.isqrt. If using an older version of Python, look for the "def isqrt(n)" implementation here.

import math

def is_square(i: int) -> bool:
    return i == math.isqrt(i) ** 2

Make cross-domain ajax JSONP request with jQuery

you need to parse your xml with jquery json parse...i.e

  var parsed_json = $.parseJSON(xml);

Get exception description and stack trace which caused an exception, all as a string

See the traceback module, specifically the format_exc() function. Here.

import traceback

try:
    raise ValueError
except ValueError:
    tb = traceback.format_exc()
else:
    tb = "No error"
finally:
    print tb

psycopg2: insert multiple rows with one query

If you're using SQLAlchemy, you don't need to mess with hand-crafting the string because SQLAlchemy supports generating a multi-row VALUES clause for a single INSERT statement:

rows = []
for i, name in enumerate(rawdata):
    row = {
        'id': i,
        'name': name,
        'valid': True,
    }
    rows.append(row)
if len(rows) > 0:  # INSERT fails if no rows
    insert_query = SQLAlchemyModelName.__table__.insert().values(rows)
    session.execute(insert_query)

Print range of numbers on same line

Another single-line Python 3 option but with explicit separator:

print(*range(1,11), sep=' ')

Printing pointers in C

You can't change the value (i.e., address of) a static array. In technical terms, the lvalue of an array is the address of its first element. Hence s == &s. It's just a quirk of the language.

How can I iterate through a string and also know the index (current position)?

You can use standard STL function distance as mentioned before

index = std::distance(s.begin(), it);

Also, you can access string and some other containers with the c-like interface:

for (i=0;i<string1.length();i++) string1[i];

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

while installing vc_redist.x64.exe, getting error "Failed to configure per-machine MSU package."

The OS failed to install the required update Windows8.1-KB2999226-x64.msu. However I tried to find the particular update from -

C:\ProgramData\Package Cache\469A82B09E217DDCF849181A586DF1C97C0C5C85\packages\Patch\amd64\Windows8.1-KB2999226-x64.msu.

I couldn't find it there so I installed the kb2999226 update from here (Windows 10 Universal C runtime)

Then I installed the update according to my OS and after that It was working fine.

Heap space out of memory

No. The heap is cleared by the garbage collector whenever it feels like it. You can ask it to run (with System.gc()) but it is not guaranteed to run.

First try increasing the memory by setting -Xmx256m

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

This seems to work for me when I encounter this:

  • Turn off all entitlements under Capabilities
  • Install app with a basic provisioning profile (no app groups, without push, no keychain sharing, etc)
  • Change the entitlements back and switch back to your proper provisioning profile. I undo the above changes using source control.

Flipping entitlements off/on alone didn't work for me—including uninstalling and reinstalling the app in between, deleting DerivedData, and restarting Xcode. It seemed I actually had to deploy the app in this configuration for it to go back to working properly.

I've had this issue several times when my provisioning profile gets updated and I reload it into Xcode. Nothing had changed with the entitlements allowed by the provisioning profile so everything should have matched as before. It may have worked to delete my entitlements file and recreate it as other uprooted answers suggest, from the Capabilities tab, too; but I use the above method to avoid random/no-op changes to my entitlements file that's checked into source control.

Using the slash character in Git branch name

I could be wrong, but I thought that slashes only appeared in branch names when they related to a remote repo, for example origin/master.

Build Error - missing required architecture i386 in file

This happens when you add a framework to your project and unintentionally copy the framework into your project directory.

The fix is to check your project directory (where you store your project on disk) for any iphone SDK *.Framework files and delete them.

Project will build fine afterwards.

Add a properties file to IntelliJ's classpath

If you ever end up with the same problem with Scala and SBT:

  • Go to Project Structure. The shortcut is (CTRL + ALT + SHIFT + S)

  • On the far left list, choose Project Settings > Modules

  • On the module list right of that, select the module of your project name (without the build) and choose the sources tab

  • In middle, expand the folder that the root of your project for me that's /home/<username>/IdeaProjects/<projectName>

  • Look at the Content Root section on the right side, the red paths are directories that you haven't made. You'll want to put the properties file in a Resources directory. So I created src/main/resources and put log4j.properties in it. I believe you can also modify the Content Root to put it wherever you want (I didn't do this).

  • I ran my code with a SBT configuration and it found my log4j.properties file.

enter image description here

How to show hidden divs on mouseover?

There is a really simple way to do this in a CSS only way.

Apply an opacity to 0, therefore making it invisible, but it will still react to JavaScript events and CSS selectors. In the hover selector, make it visible by changing the opacity value.

_x000D_
_x000D_
#mouse_over {_x000D_
  opacity: 0;_x000D_
}_x000D_
_x000D_
#mouse_over:hover {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div style='border: 5px solid black; width: 120px; font-family: sans-serif'>_x000D_
<div style='height: 20px; width: 120px; background-color: cyan;' id='mouse_over'>Now you see me</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

python error: no module named pylab

With the addition of Python 3, here is an updated code that works:

import numpy as n
import scipy as s
import matplotlib.pylab as p #pylab is part of matplotlib

xa=0.252
xb=1.99

C=n.linspace(xa,xb,100)
print(C)
iter=1000
Y = n.ones(len(C))

for x in range(iter):
    Y = Y**2 - C   #get rid of early transients

for x in range(iter): 
    Y = Y**2 - C
    p.plot(C,Y, '.', color = 'k', markersize = 2)

p.show()

List file names based on a filename pattern and file content?

grep LMN20113456 LMN2011*

or if you want to search recursively through subdirectories:

find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;

convert double to int

label8.Text = "" + years.ToString("00") + " years";

when you want to send it to a label, or something, and you don't want any fractional component, this is the best way

label8.Text = "" + years.ToString("00.00") + " years";

if you want with only 2, and it's always like that

How do you remove a Cookie in a Java Servlet

The MaxAge of -1 signals that you want the cookie to persist for the duration of the session. You want to set MaxAge to 0 instead.

From the API documentation:

A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

Output (echo/print) everything from a PHP Array

For nice & readable results, use this:

function printVar($var) {
    echo '<pre>';
    var_dump($var); 
    echo '</pre>';
}

The above function will preserve the original formatting, making it (more)readable in a web browser.

Case objects vs Enumerations in Scala

If you are serious about maintaining interoperability with other JVM languages (e.g. Java) then the best option is to write Java enums. Those work transparently from both Scala and Java code, which is more than can be said for scala.Enumeration or case objects. Let's not have a new enumerations library for every new hobby project on GitHub, if it can be avoided!

Where does flask look for image files?

From the documentation:

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

To generate URLs for static files, use the special 'static' endpoint name:

url_for('static', filename='style.css')

The file has to be stored on the filesystem as static/style.css.

What does it mean to inflate a view from an xml file?

When you write an XML layout, it will be inflated by the Android OS which basically means that it will be rendered by creating view object in memory. Let's call that implicit inflation (the OS will inflate the view for you). For instance:

class Name extends Activity{
    public void onCreate(){
         // the OS will inflate the your_layout.xml
         // file and use it for this activity
         setContentView(R.layout.your_layout);
    }
}

You can also inflate views explicitly by using the LayoutInflater. In that case you have to:

  1. Get an instance of the LayoutInflater
  2. Specify the XML to inflate
  3. Use the returned View
  4. Set the content view with returned view (above)

For instance:

LayoutInflater inflater = LayoutInflater.from(YourActivity.this); // 1
View theInflatedView = inflater.inflate(R.layout.your_layout, null); // 2 and 3
setContentView(theInflatedView) // 4

Catching exceptions from Guzzle

To catch Guzzle errors you can do something like this:

try {
    $response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
    echo 'Uh oh! ' . $e->getMessage();
}

... but, to be able to "log" or "resend" your request try something like this:

// Add custom error handling to any request created by this client
$client->getEventDispatcher()->addListener(
    'request.error', 
    function(Event $event) {

        //write log here ...

        if ($event['response']->getStatusCode() == 401) {

            // create new token and resend your request...
            $newRequest = $event['request']->clone();
            $newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
            $newResponse = $newRequest->send();

            // Set the response object of the request without firing more events
            $event['response'] = $newResponse;

            // You can also change the response and fire the normal chain of
            // events by calling $event['request']->setResponse($newResponse);

            // Stop other events from firing when you override 401 responses
            $event->stopPropagation();
        }

});

... or if you want to "stop event propagation" you can overridde event listener (with a higher priority than -255) and simply stop event propagation.

$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() != 200) {
        // Stop other events from firing when you get stytus-code != 200
        $event->stopPropagation();
    }
});

thats a good idea to prevent guzzle errors like:

request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response

in your application.

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, but you'll need to run it at the database level.

Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.

Screen shot of Advanced Scripting Options

Adding new files to a subversion repository

Before you can add files in an unversioned directory, you have to add the directory itself to the versioning:

svn add directory_name

will add the directory directory_name and all sub-directories: http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.add.html

Netbeans how to set command line arguments in Java

For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel

Getting assembly name

System.Reflection.Assembly.GetExecutingAssembly().GetName().Name

or

typeof(Program).Assembly.GetName().Name;

Sqlite primary key on multiple columns

According to the documentation, it's

CREATE TABLE something (
  column1, 
  column2, 
  column3, 
  PRIMARY KEY (column1, column2)
);

How to change Android version and code version number?

The easiest way to set the version in Android Studio:

1. Press SHIFT+CTRL+ALT+S (or File -> Project Structure -> app)

Android Studio < 3.4:

  1. Choose tab 'Flavors'
  2. The last two fields are 'Version Code' and 'Version Name'

Android Studio >= 3.4:

  1. Choose 'Modules' in the left panel.
  2. Choose 'app' in middle panel.
  3. Choose 'Default Config' tab in the right panel.
  4. Scroll down to see and edit 'Version Code' and 'Version Name' fields.

Trigger 404 in Spring-MVC controller?

Also if you want to return 404 status from your controller all you need is to do this

@RequestMapping(value = "/somthing", method = RequestMethod.POST)
@ResponseBody
public HttpStatus doSomthing(@RequestBody String employeeId) {
    try{
  return HttpStatus.OK;
    } 
    catch(Exception ex){ 
  return HttpStatus.NOT_FOUND;
    }
}

By doing this you will receive a 404 error in case when you want to return a 404 from your controller.

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

I set the token delimiter to be a newline pattern, read the next token, and then put the delimiter back to whatever it was.

public static String readLine(Scanner scanner) {
        Pattern oldDelimiter = scanner.delimiter();
        scanner.useDelimiter("\\r\\n|[\\n\\x0B\\x0C\\r\\u0085\\u2028\\u2029]");
        String r = scanner.next();
        scanner.useDelimiter(oldDelimiter);
        return r;
}

How to check the function's return value if true or false

false != 'false'

For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:

var result = ValidateForm();
if(result == false) {
...
}

Function stoi not declared

Are you running C++ 11? stoi was added in C++ 11, if you're running on an older version use atoi()

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

  • first you cannot extend AsyncTask without override doInBackground
  • second try to create AlterDailog from the builder then call show().

    private boolean visible = false;
    class chkSubscription extends AsyncTask<String, Void, String>
    {
    
        protected void onPostExecute(String result)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setCancelable(true);
            builder.setMessage(sucObject);
            builder.setInverseBackgroundForced(true);
            builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton)
                {
                    dialog.dismiss();
                }
            });
    
            AlertDialog myAlertDialog = builder.create();
            if(visible) myAlertDialog.show();
        }
    
        @Override
        protected String doInBackground(String... arg0)
        {
            // TODO Auto-generated method stub
            return null;
        }
    }
    
    
    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
        visible = true;
    }
    
    @Override
    protected void onStop()
    {
        visible = false; 
        super.onStop();
    }
    

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

Apache won't run in xampp

In my case I simply had to run the control panel as administrator

Check if a file is executable

Take a look at the various test operators (this is for the test command itself, but the built-in BASH and TCSH tests are more or less the same).

You'll notice that -x FILE says FILE exists and execute (or search) permission is granted.

BASH, Bourne, Ksh, Zsh Script

if [[ -x "$file" ]]
then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
fi

TCSH or CSH Script:

if ( -x "$file" ) then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
endif

To determine the type of file it is, try the file command. You can parse the output to see exactly what type of file it is. Word 'o Warning: Sometimes file will return more than one line. Here's what happens on my Mac:

$ file /bin/ls    
/bin/ls: Mach-O universal binary with 2 architectures
/bin/ls (for architecture x86_64):  Mach-O 64-bit executable x86_64
/bin/ls (for architecture i386):    Mach-O executable i386

The file command returns different output depending upon the OS. However, the word executable will be in executable programs, and usually the architecture will appear too.

Compare the above to what I get on my Linux box:

$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), stripped

And a Solaris box:

$ file /bin/ls
/bin/ls:        ELF 32-bit MSB executable SPARC Version 1, dynamically linked, stripped

In all three, you'll see the word executable and the architecture (x86-64, i386, or SPARC with 32-bit).


Addendum

Thank you very much, that seems the way to go. Before I mark this as my answer, can you please guide me as to what kind of script shell check I would have to perform (ie, what kind of parsing) on 'file' in order to check whether I can execute a program ? If such a test is too difficult to make on a general basis, I would at least like to check whether it's a linux executable or osX (Mach-O)

Off the top of my head, you could do something like this in BASH:

if [ -x "$file" ] && file "$file" | grep -q "Mach-O"
then
    echo "This is an executable Mac file"
elif [ -x "$file" ] && file "$file" | grep -q "GNU/Linux"
then
    echo "This is an executable Linux File"
elif [ -x "$file" ] && file "$file" | grep q "shell script"
then
    echo "This is an executable Shell Script"
elif [ -x "$file" ]
then
    echo "This file is merely marked executable, but what type is a mystery"
else
    echo "This file isn't even marked as being executable"
fi

Basically, I'm running the test, then if that is successful, I do a grep on the output of the file command. The grep -q means don't print any output, but use the exit code of grep to see if I found the string. If your system doesn't take grep -q, you can try grep "regex" > /dev/null 2>&1.

Again, the output of the file command may vary from system to system, so you'll have to verify that these will work on your system. Also, I'm checking the executable bit. If a file is a binary executable, but the executable bit isn't on, I'll say it's not executable. This may not be what you want.

Java, How to add library files in netbeans?

How to import a commons-library into netbeans.

  1. Evaluate the error message in NetBeans:

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    
  2. NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass() and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.

  3. To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.

  4. You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.

  5. You're going to want to download the commons-logging-1.1.3-bin.zip or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.

  6. Download that zip. Unzip it. Search around for things that end in .jar. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.

The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.

Losing Session State

Dont know is it related to your problem or not BUT Windows 2008 Server R2 or SP2 has changed its IIS settings, which leads to issue in session persistence. By default, it manages separate session variable for HTTP and HTTPS. When variables are set in HTTPS, these will be available only on HTTPS pages whenever switched.

To solve the issue, there is IIS setting. In IIS Manager, open up the ASP properties, expand Session Properties, and change New ID On Secure Connection to False.

SQL Server Operating system error 5: "5(Access is denied.)"

This is Windows related issue where SQL Server does not have the appropriate permission to the folder that contains .bak file and hence this error.

The easiest work around is to copy your .bak file to default SQL backup location which has all the necessary permissions. You do not need to fiddle with anything else. In SQL SERVER 2012, this location is

D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup (SQL 2012)
C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup (SQL 2014)
C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Backup (SQL 2016)

Document directory path of Xcode Device Simulator

If you like to go into the app folders to see what's going on and don't want to have to go through labyrinthine UUDID's, I made this: https://github.com/kallewoof/plget

and using it, I made this: https://gist.github.com/kallewoof/de4899aabde564f62687

Basically, when I want to go to some app's folder, I do:

$ cd ~/iosapps
$ ./app.sh
$ ls -l
total 152
lrwxr-xr-x  1 me  staff    72 Nov 14 17:15 My App Beta-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/BD660795-9131-4A5A-9A5D-074459F6A4BF
lrwxr-xr-x  1 me  staff    72 Nov 14 17:15 Other App Beta-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/A74C9F8B-37E0-4D89-80F9-48A15599D404
lrwxr-xr-x  1 me  staff    72 Nov 14 17:15 My App-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/07BA5718-CF3B-42C7-B501-762E02F9756E
lrwxr-xr-x  1 me  staff    72 Nov 14 17:15 Other App-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/5A4642A4-B598-429F-ADC9-BB15D5CEE9B0
-rwxr-xr-x  1 me  staff  3282 Nov 14 17:04 app.sh
lrwxr-xr-x  1 me  staff   158 Nov 14 17:15 com.mycompany.app1-iOS-8-0_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data/Containers/Data/Application/69F7E3EF-B450-4840-826D-3830E79C247A
lrwxr-xr-x  1 me  staff   158 Nov 14 17:15 com.mycompany.app1-iOS-8-1_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/414E8875-8875-4088-B17A-200202219A34/data/Containers/Data/Application/976D1E91-DA9E-4DA0-800D-52D1AE527AC6
lrwxr-xr-x  1 me  staff   158 Nov 14 17:15 com.mycompany.app1beta-iOS-8-0_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data/Containers/Data/Application/473F8259-EE11-4417-B04E-6FBA7BF2ED05
lrwxr-xr-x  1 me  staff   158 Nov 14 17:15 com.mycompany.app1beta-iOS-8-1_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/414E8875-8875-4088-B17A-200202219A34/data/Containers/Data/Application/CB21C38E-B978-4B8F-99D1-EAC7F10BD894
lrwxr-xr-x  1 me  staff   158 Nov 14 17:15 com.mycompany.otherapp-iOS-8-1_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/414E8875-8875-4088-B17A-200202219A34/data/Containers/Data/Application/DE3FF8F1-303D-41FA-AD8D-43B22DDADCDE
lrwxr-xr-x  1 me  staff    51 Nov 14 17:15 iOS-7-1_iPad-Retina.dr -> simulator/4DC11775-F2B5-4447-98EB-FC5C1DB562AD/data
lrwxr-xr-x  1 me  staff    51 Nov 14 17:15 iOS-8-0_iPad-2.dr -> simulator/6FC02AE7-27B4-4DBF-92F1-CCFEBDCAC5EE/data
lrwxr-xr-x  1 me  staff    51 Nov 14 17:15 iOS-8-0_iPad-Retina.dr -> simulator/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data
lrwxr-xr-x  1 me  staff    51 Nov 14 17:15 iOS-8-1_iPad-Retina.dr -> simulator/414E8875-8875-4088-B17A-200202219A34/data
lrwxr-xr-x  1 me  staff   158 Nov 14 17:15 org.cocoapods.demo.pajdeg-iOS-8-0_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data/Containers/Data/Application/C3069623-D55D-462C-82E0-E896C942F7DE
lrwxr-xr-x  1 me  staff    51 Nov 14 17:15 simulator -> /Users/me/Library/Developer/CoreSimulator/Devices

The ./app.sh part syncs the links. It is necessary basically always nowadays as apps change UUID for every run in Xcode as of 6.0. Also, unfortunately, apps are by bundle id for 8.x and by app name for < 8.

How do you uninstall a python package that was installed using distutils?

On Mac OSX, manually delete these 2 directories under your pathToPython/site-packages/ will work:

  • {packageName}
  • {packageName}-{version}-info

for example, to remove pyasn1, which is a distutils installed project:

  • rm -rf lib/python2.7/site-packages/pyasn1
  • rm -rf lib/python2.7/site-packages/pyasn1-0.1.9-py2.7.egg-info

To find out where is your site-packages:

python -m site

input[type='text'] CSS selector does not apply to default-type text inputs?

The CSS uses only the data in the DOM tree, which has little to do with how the renderer decides what to do with elements with missing attributes.

So either let the CSS reflect the HTML

input:not([type]), input[type="text"]
{
background:red;
}

or make the HTML explicit.

<input name='t1' type='text'/> /* Is Not Red */

If it didn't do that, you'd never be able to distinguish between

element { ...properties... }

and

element[attr] { ...properties... }

because all attributes would always be defined on all elements. (For example, table always has a border attribute, with 0 for a default.)

What are the correct version numbers for C#?

C# Version History:

C# is a simple and powerful object-oriented programming language developed by Microsoft.

C# has evolved much since its first release in 2002. C# was introduced with .NET Framework 1.0.

The following table lists important features introduced in each version of C#.

And the latest version of C# is available in C# Versions.

1: enter image description here

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

how to make UITextView height dynamic according to text length?

Here are two pitfalls in iOS 8.3 when coming with textView.textContainer.maximumNumberOfLines = 10

Refer to my gist, please.

textView.attributedText = originalContent

let lineLimit = 10
textView.isEditable = true
textView.isScrollEnabled = false
textView.textContainerInset = .zero // default is (8, 0, 8, 0)
textView.textContainer.maximumNumberOfLines = lineLimit // Important condition
textView.textContainer.lineBreakMode = .byTruncatingTail

// two incomplete methods, which do NOT work in iOS 8.3

// size.width???maxSize.width? ————???? iOS 8.3 ??????maximumNumberOfLines??,??????UILabel
// size.width may be less than maxSize.width, ---- Do NOT work in iOS 8.3, which disregards textView.textContainer.maximumNumberOfLines
// let size = textView.sizeThatFits(maxSize) 

// ???? iOS 8.3 ???????,????UILabel
// Does not work in iOS 8.3
// let size = textView.layoutManager.usedRectForTextContainer(textView.textContainer).size 

// Suggested method: use a temperary label to get its size
let label = UILabel(); label.attributedText = originalContent
let size = label.textRect(forBounds: CGRect(origin: .zero, size: maxSize), limitedToNumberOfLines: lineLimit).size
textView.frame.size = size

jQuery fade out then fade in

With async functions and promises, it now can work as simply as this:

async function foobar() {
  await $("#example").fadeOut().promise();
  doSomethingElse();
  await $("#example").fadeIn().promise();
}

How to sort a List<Object> alphabetically using Object name field

If you are using a List<Object> to hold objects of a subtype that has a name field (lets call the subtype NamedObject), you'll need to downcast the list elements in order to access the name. You have 3 options, the best of which is the first:

  1. Don't use a List<Object> in the first place if you can help it - keep your named objects in a List<NamedObject>
  2. Copy your List<Object> elements into a List<NamedObject>, downcasting in the process, do the sort, then copy them back
  3. Do the downcasting in the Comparator

Option 3 would look like this:

Collections.sort(p, new Comparator<Object> () {
        int compare (final Object a, final Object b) {
                return ((NamedObject) a).getName().compareTo((NamedObject b).getName());
        }
}

Extract digits from a string in Java

input.replaceAll("[^0-9?!\\.]","")

This will ignore the decimal points.

eg: if you have an input as 445.3kg the output will be 445.3.

How to get the first element of the List or Set?

See the javadoc

of List

list.get(0);

or Set

set.iterator().next();

and check the size before using the above methods by invoking isEmpty()

!list_or_set.isEmpty()

How do I set response headers in Flask?

We can set the response headers in Python Flask application using Flask application context using flask.g

This way of setting response headers in Flask application context using flask.g is thread safe and can be used to set custom & dynamic attributes from any file of application, this is especially helpful if we are setting custom/dynamic response headers from any helper class, that can also be accessed from any other file ( say like middleware, etc), this flask.g is global & valid for that request thread only.

Say if i want to read the response header from another api/http call that is being called from this app, and then extract any & set it as response headers for this app.

Sample Code: file: helper.py

import flask
from flask import request, g
from multidict import CIMultiDict
from asyncio import TimeoutError as HttpTimeout
from aiohttp import ClientSession

    def _extract_response_header(response)
      """
      extracts response headers from response object 
      and stores that required response header in flask.g app context
      """
      headers = CIMultiDict(response.headers)
      if 'my_response_header' not in g:
        g.my_response_header= {}
        g.my_response_header['x-custom-header'] = headers['x-custom-header']


    async def call_post_api(post_body):
      """
      sample method to make post api call using aiohttp clientsession
      """
      try:
        async with ClientSession() as session:
          async with session.post(uri, headers=_headers, json=post_body) as response:
            responseResult = await response.read()
            _extract_headers(response, responseResult)
            response_text = await response.text()
      except (HttpTimeout, ConnectionError) as ex:
        raise HttpTimeout(exception_message)

file: middleware.py

import flask
from flask import request, g

class SimpleMiddleWare(object):
    """
    Simple WSGI middleware
    """

    def __init__(self, app):
        self.app = app
        self._header_name = "any_request_header"

    def __call__(self, environ, start_response):
        """
        middleware to capture request header from incoming http request
        """
        request_id_header = environ.get(self._header_name)
        environ[self._header_name] = request_id_header

        def new_start_response(status, response_headers, exc_info=None):
            """
            set custom response headers
            """
            # set the request header as response header
            response_headers.append((self._header_name, request_id_header))
            # this is trying to access flask.g values set in helper class & set that as response header
            values = g.get(my_response_header, {})
            if values.get('x-custom-header'):
                response_headers.append(('x-custom-header', values.get('x-custom-header')))
            return start_response(status, response_headers, exc_info)

        return self.app(environ, new_start_response)

Calling the middleware from main class

file : main.py

from flask import Flask
import asyncio
from gevent.pywsgi import WSGIServer
from middleware import SimpleMiddleWare

    app = Flask(__name__)
    app.wsgi_app = SimpleMiddleWare(app.wsgi_app)

Count the number of times a string appears within a string

With Linq...

string s = "7,true,NA,false:67,false,NA,false:5,false,NA,false:5,false,NA,false";
var count = s.Split(new[] {',', ':'}).Count(s => s == "true" );

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

How do I convert datetime.timedelta to minutes, hours in Python?

Do you want to print the date in that format? This is the Python documentation: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

>>> a = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366)
>>> print a.strftime('%Y %d %B, %M:%S%p')
>>> 2013 07 January, 31:34AM

For the timedelta:

>>> a =  datetime.timedelta(0,5,41038)
>>> print '%s seconds, %s microseconds' % (a.seconds, a.microseconds)

But please notice, you should make sure it has the related value. For the above cases, it doesn't have the hours and minute values, and you should calculate from the seconds.

Regular expression to return text between parenthesis

contents_re = re.match(r'[^\(]*\((?P<contents>[^\(]+)\)', data)
if contents_re:
    print(contents_re.groupdict()['contents'])

Checking if a folder exists (and creating folders) in Qt, C++

When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.

You can see more on Qt Documentation

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

Angular cookies

Use NGX Cookie Service

Inastall this package: npm install ngx-cookie-service --save

Add the cookie service to your app.module.ts as a provider:

import { CookieService } from 'ngx-cookie-service';
@NgModule({
  declarations: [ AppComponent ],
  imports: [ BrowserModule, ... ],
  providers: [ CookieService ],
  bootstrap: [ AppComponent ]
})

Then call in your component:

import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService ) { }

ngOnInit(): void {
  this.cookieService.set( 'name', 'Test Cookie' ); // To Set Cookie
  this.cookieValue = this.cookieService.get('name'); // To Get Cookie
}

That's it!

How to abort makefile if variable not set?

Use the shell error handling for unset variables (note the double $):

$ cat Makefile
foo:
        echo "something is set to $${something:?}"

$ make foo
echo "something is set to ${something:?}"
/bin/sh: something: parameter null or not set
make: *** [foo] Error 127


$ make foo something=x
echo "something is set to ${something:?}"
something is set to x

If you need a custom error message, add it after the ?:

$ cat Makefile
hello:
        echo "hello $${name:?please tell me who you are via \$$name}"

$ make hello
echo "hello ${name:?please tell me who you are via \$name}"
/bin/sh: name: please tell me who you are via $name
make: *** [hello] Error 127

$ make hello name=jesus
echo "hello ${name:?please tell me who you are via \$name}"
hello jesus

Best way to get identity of inserted row?

@@IDENTITY is the last identity inserted using the current SQL Connection. This is a good value to return from an insert stored procedure, where you just need the identity inserted for your new record, and don't care if more rows were added afterward.

SCOPE_IDENTITY is the last identity inserted using the current SQL Connection, and in the current scope -- that is, if there was a second IDENTITY inserted based on a trigger after your insert, it would not be reflected in SCOPE_IDENTITY, only the insert you performed. Frankly, I have never had a reason to use this.

IDENT_CURRENT(tablename) is the last identity inserted regardless of connection or scope. You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into.

How to enter command with password for git pull?

If you are looking to do this in a CI/CD script on Gitlab (gitlab-ci.yml). You could use

git pull $CI_REPOSITORY_URL

which will translate to something like:

git pull https://gitlab-ci-token:[MASKED]@gitlab.com/gitlab-examples/ci-debug-trace.gi

And I'm pretty sure the token it uses is a ephemeral/per job token - so the security hole with this method is greatly reduced.

How can I get the username of the logged-in user in Django?

request.user.get_username() will return a string of the users email.

request.user.username will return a method.

XSLT counting elements with a given value

<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>

Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance

Creating a range of dates in Python

Matplotlib related

from matplotlib.dates import drange
import datetime

base = datetime.date.today()
end  = base + datetime.timedelta(days=100)
delta = datetime.timedelta(days=1)
l = drange(base, end, delta)

How to read an external local JSON file in JavaScript?

You must create a new XMLHttpRequest instance and load the contents of the json file.

This tip work for me (https://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript):

 function loadJSON(callback) {   

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', 'my_data.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
          }
    };
    xobj.send(null);  
 }

 loadJSON(function(response) {
    // Parse JSON string into object
    var actual_JSON = JSON.parse(response);
 });

Get hours difference between two dates in Moment Js

Or you can do simply:

var a = moment('2016-06-06T21:03:55');//now
var b = moment('2016-05-06T20:03:55');

console.log(a.diff(b, 'minutes')) // 44700
console.log(a.diff(b, 'hours')) // 745
console.log(a.diff(b, 'days')) // 31
console.log(a.diff(b, 'weeks')) // 4

docs: here

Add views below toolbar in CoordinatorLayout

To use collapsing top ToolBar or using ScrollFlags of your own choice we can do this way:From Material Design get rid of FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleGravity="top"
            app:layout_scrollFlags="scroll|enterAlways">


        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/ic_back"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_arrow_back" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="back"
                android:textSize="16sp"
                android:textStyle="bold" />

        </androidx.appcompat.widget.Toolbar>


        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/post_details_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

How to delete and update a record in Hive

Delete has been recently added in Hive version 0.14 Deletes can only be performed on tables that support ACID Below is the link from Apache .

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Delete

Pass by Reference / Value in C++

I think much confusion is generated by not communicating what is meant by passed by reference. When some people say pass by reference they usually mean not the argument itself, but rather the object being referenced. Some other say that pass by reference means that the object can't be changed in the callee. Example:

struct Object {
    int i;
};

void sample(Object* o) { // 1
    o->i++;
}

void sample(Object const& o) { // 2
    // nothing useful here :)
}

void sample(Object & o) { // 3
    o.i++;
}

void sample1(Object o) { // 4
    o.i++;
}

int main() {
    Object obj = { 10 };
    Object const obj_c = { 10 };

    sample(&obj); // calls 1
    sample(obj) // calls 3
    sample(obj_c); // calls 2
    sample1(obj); // calls 4
}

Some people would claim that 1 and 3 are pass by reference, while 2 would be pass by value. Another group of people say all but the last is pass by reference, because the object itself is not copied.

I would like to draw a definition of that here what i claim to be pass by reference. A general overview over it can be found here: Difference between pass by reference and pass by value. The first and last are pass by value, and the middle two are pass by reference:

    sample(&obj);
       // yields a `Object*`. Passes a *pointer* to the object by value. 
       // The caller can change the pointer (the parameter), but that 
       // won't change the temporary pointer created on the call side (the argument). 

    sample(obj)
       // passes the object by *reference*. It denotes the object itself. The callee
       // has got a reference parameter.

    sample(obj_c);
       // also passes *by reference*. the reference parameter references the
       // same object like the argument expression. 

    sample1(obj);
       // pass by value. The parameter object denotes a different object than the 
       // one passed in.

I vote for the following definition:

An argument (1.3.1) is passed by reference if and only if the corresponding parameter of the function that's called has reference type and the reference parameter binds directly to the argument expression (8.5.3/4). In all other cases, we have to do with pass by value.

That means that the following is pass by value:

void f1(Object const& o);
f1(Object()); // 1

void f2(int const& i);
f2(42); // 2

void f3(Object o);
f3(Object());     // 3
Object o1; f3(o1); // 4

void f4(Object *o);
Object o1; f4(&o1); // 5

1 is pass by value, because it's not directly bound. The implementation may copy the temporary and then bind that temporary to the reference. 2 is pass by value, because the implementation initializes a temporary of the literal and then binds to the reference. 3 is pass by value, because the parameter has not reference type. 4 is pass by value for the same reason. 5 is pass by value because the parameter has not got reference type. The following cases are pass by reference (by the rules of 8.5.3/4 and others):

void f1(Object *& op);
Object a; Object *op1 = &a; f1(op1); // 1

void f2(Object const& op);
Object b; f2(b); // 2

struct A { };
struct B { operator A&() { static A a; return a; } };
void f3(A &);
B b; f3(b); // passes the static a by reference

ASP.NET Web API session or something?

Now in 2017 with ASP.Net Core you can do it as explained here.

The Microsoft.AspNetCore.Session package provides middleware for managing session state.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
  // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();
}

From the Docs: Introduction to session and application state in ASP.NET Core

Already tested on a working project

Class 'DOMDocument' not found

You need to install the DOM extension. You can do so on Debian / Ubuntu using:

sudo apt-get install php-dom

And on Centos / Fedora / Red Hat:

yum install php-xml

If you get conflicts between PHP packages, you could try to see if the specific PHP version package exists instead: e.g. php53-xml if your system runs PHP5.3.

Find files and tar them (with spaces)

Another solution as seen here:

find var/log/ -iname "anaconda.*" -exec tar -cvzf file.tar.gz {} +

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

Multiplying across in a numpy array

I've compared the different options for speed and found that – much to my surprise – all options (except diag) are equally fast. I personally use

A * b[:, None]

(or (A.T * b).T) because it's short.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot


def newaxis(data):
    A, b = data
    return A * b[:, numpy.newaxis]


def none(data):
    A, b = data
    return A * b[:, None]


def double_transpose(data):
    A, b = data
    return (A.T * b).T


def double_transpose_contiguous(data):
    A, b = data
    return numpy.ascontiguousarray((A.T * b).T)


def diag_dot(data):
    A, b = data
    return numpy.dot(numpy.diag(b), A)


def einsum(data):
    A, b = data
    return numpy.einsum("ij,i->ij", A, b)


perfplot.save(
    "p.png",
    setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
    kernels=[
        newaxis,
        none,
        double_transpose,
        double_transpose_contiguous,
        diag_dot,
        einsum,
    ],
    n_range=[2 ** k for k in range(13)],
    xlabel="len(A), len(b)",
)

Selecting multiple columns in a Pandas dataframe

Try to use pandas.DataFrame.get (see the documentation):

import pandas as pd
import numpy as np

dates = pd.date_range('20200102', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
df.get(['A', 'C'])

Java and SQLite

sqlitejdbc code can be downloaded using git from https://github.com/crawshaw/sqlitejdbc.

# git clone https://github.com/crawshaw/sqlitejdbc.git sqlitejdbc
...
# cd sqlitejdbc
# make

Note: Makefile requires curl binary to download sqlite libraries/deps.

How to JSON serialize sets?

One shortcoming of the accepted solution is that its output is very python specific. I.e. its raw json output cannot be observed by a human or loaded by another language (e.g. javascript). example:

db = {
        "a": [ 44, set((4,5,6)) ],
        "b": [ 55, set((4,3,2)) ]
        }

j = dumps(db, cls=PythonObjectEncoder)
print(j)

Will get you:

{"a": [44, {"_python_object": "gANjYnVpbHRpbnMKc2V0CnEAXXEBKEsESwVLBmWFcQJScQMu"}], "b": [55, {"_python_object": "gANjYnVpbHRpbnMKc2V0CnEAXXEBKEsCSwNLBGWFcQJScQMu"}]}

I can propose a solution which downgrades the set to a dict containing a list on the way out, and back to a set when loaded into python using the same encoder, therefore preserving observability and language agnosticism:

from decimal import Decimal
from base64 import b64encode, b64decode
from json import dumps, loads, JSONEncoder
import pickle

class PythonObjectEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (list, dict, str, int, float, bool, type(None))):
            return super().default(obj)
        elif isinstance(obj, set):
            return {"__set__": list(obj)}
        return {'_python_object': b64encode(pickle.dumps(obj)).decode('utf-8')}

def as_python_object(dct):
    if '__set__' in dct:
        return set(dct['__set__'])
    elif '_python_object' in dct:
        return pickle.loads(b64decode(dct['_python_object'].encode('utf-8')))
    return dct

db = {
        "a": [ 44, set((4,5,6)) ],
        "b": [ 55, set((4,3,2)) ]
        }

j = dumps(db, cls=PythonObjectEncoder)
print(j)
ob = loads(j)
print(ob["a"])

Which gets you:

{"a": [44, {"__set__": [4, 5, 6]}], "b": [55, {"__set__": [2, 3, 4]}]}
[44, {'__set__': [4, 5, 6]}]

Note that serializing a dictionary which has an element with a key "__set__" will break this mechanism. So __set__ has now become a reserved dict key. Obviously feel free to use another, more deeply obfuscated key.

Set up a scheduled job?

I had exactly the same requirement a while ago, and ended up solving it using APScheduler (User Guide)

It makes scheduling jobs super simple, and keeps it independent for from request-based execution of some code. Following is a simple example.

from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()
job = None

def tick():
    print('One tick!')\

def start_job():
    global job
    job = scheduler.add_job(tick, 'interval', seconds=3600)
    try:
        scheduler.start()
    except:
        pass

Hope this helps somebody!

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

The accepted answer of how to create an Index inline a Table creation script did not work for me. This did:

CREATE TABLE [dbo].[TableToBeCreated]
(
    [Id] BIGINT IDENTITY(1, 1) NOT NULL PRIMARY KEY
    ,[ForeignKeyId] BIGINT NOT NULL
    ,CONSTRAINT [FK_TableToBeCreated_ForeignKeyId_OtherTable_Id] FOREIGN KEY ([ForeignKeyId]) REFERENCES [dbo].[OtherTable]([Id])
    ,INDEX [IX_TableToBeCreated_ForeignKeyId] NONCLUSTERED ([ForeignKeyId])
)

Remember, Foreign Keys do not create Indexes, so it is good practice to index them as you will more than likely be joining on them.

How can I find which tables reference a given table in Oracle SQL Developer?

To add to the above answer for sql developer plugin, using the below xml will help in getting the column associated with the foreign key.

    <items>
        <item type="editor" node="TableNode" vertical="true">
        <title><![CDATA[FK References]]></title>
        <query>
            <sql>
                <![CDATA[select a.owner,
                                a.constraint_name,
                                a.table_name,
                                b.column_name,
                                a.status
                         from   all_constraints a
                         join   all_cons_columns b ON b.constraint_name = a.constraint_name
                         where  a.constraint_type = 'R'
                                and exists(
                                   select 1
                                   from   all_constraints
                                   where  constraint_name=a.r_constraint_name
                                          and constraint_type in ('P', 'U')
                                          and table_name = :OBJECT_NAME
                                          and owner = :OBJECT_OWNER)
                                   order by table_name, constraint_name]]>
            </sql>
        </query>
        </item>
    </items>

Java random numbers using a seed

The easy way is to use:

Random rand = new Random(System.currentTimeMillis());

This is the best way to generate Random numbers.

Download file and automatically save it to folder

My program does exactly what you are after, no prompts or anything, please see the following code.

This code will create all of the necessary directories if they don't already exist:

Directory.CreateDirectory(C:\dir\dira\dirb);  // This code will create all of these directories  

This code will download the given file to the given directory (after it has been created by the previous snippet:

private void install()
    {
        WebClient webClient = new WebClient();                                                          // Creates a webclient
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);                   // Uses the Event Handler to check whether the download is complete
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);  // Uses the Event Handler to check for progress made
        webClient.DownloadFileAsync(new Uri("http://www.com/newfile.zip"), @"C\newfile.zip");           // Defines the URL and destination directory for the downloaded file
    }

So using these two pieces of code you can create all of the directories and then tell the downloader (that doesn't prompt you to download the file to that location.

How to save SELECT sql query results in an array in C# Asp.net

Use a SQL DATA READER:

In this example i use a List instead an array.

try
{
    SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);
    connection.Open();

    SqlDataReader reader = comm.ExecuteReader();
    List<string> str = new List<string>();
    int i=0;
    while (reader.Read())
    {
        str.Add( reader.GetValue(i).ToString() );
        i++;
    }
    reader.Close();
}
catch (Exception)
{
    throw;
}
finally
{
    connection.Close();
}

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

Combine two data frames by rows (rbind) when they have different sets of columns

rbind.fill from the package plyr might be what you are looking for.

Resizing SVG in html?

I have an SVG file in HTML [....] IS there any way to specify that you want an SVG image displayed smaller or larger than it actually is stored in the file system?

SVG graphics, like other creative works, are protected under copyright law in most countries. Depending on jurisdiction, license of the work or whether or not you are the copyright holder you may not be able to modify the SVG without violating copyright law, believe it or not.

But laws are tricky topics and sometimes you just want to get shit done. Therefore you may adjust the scale of the graphic without modifying the work itself using the img tag with width attribute within your HTML.

Using an external HTTP request to specify the size:

<img width="96" src="/path/to/image.svg">

Specifying size in markup using a Data URI:

<img width="96" src="data:image/svg+xml,...">

SVGs can be Optimized for Data URIs to create SVG Favicon images suitable for any size:

<link rel="icon" sizes="any" href="data:image/svg+xml,%3Csvg%20viewBox='0%200%2046%2045'%20xmlns='http://www.w3.org/2000/svg'%3E%3Ctitle%3EAfter%20Dark%3C/title%3E%3Cpath%20d='M.708%2045L23%20.416%2045.292%2045H.708zM35%2038L23%2019%2011%2038h24z'%20fill='%23000'/%3E%3C/svg%3E">

How to convert an int to a hex string?

This worked best for me

"0x%02X" % 5  # => 0x05
"0x%02X" % 17 # => 0x11

Change the (2) if you want a number with a bigger width (2 is for 2 hex printned chars) so 3 will give you the following

"0x%03X" % 5  # => 0x005
"0x%03X" % 17 # => 0x011

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

This is how I do it:

from datetime import datetime
from time import mktime

dt = datetime.now()
sec_since_epoch = mktime(dt.timetuple()) + dt.microsecond/1000000.0

millis_since_epoch = sec_since_epoch * 1000

How do you access the value of an SQL count () query in a Java program

It's similar to above but you can try like

public Integer count(String tableName) throws CrateException {
        String query = String.format("Select count(*) as size from %s", tableName);
        try (Statement s = connection.createStatement()) {
            try (ResultSet resultSet = queryExecutor.executeQuery(s, query)) {
                Preconditions.checkArgument(resultSet.next(), "Result set is empty");
                return resultSet.getInt("size");
            }
        } catch (SQLException e) {
            throw new CrateException(e);
        }
    }
}

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

The issue in my case was a typo in the PATH variable. Since vsvars32.bat uses the "reg" tool to query the registry, it was failing because the tool was not found (just typing reg on a command prompt was failing for me).

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

Remove all spaces from a string in SQL Server

if you want to remove spaces,-, and another text from string then use following :

suppose you have a mobile number in your Table like '718-378-4957' or ' 7183784957' and you want replace and get the mobile number then use following Text.

select replace(replace(replace(replace(MobileNo,'-',''),'(',''),')',''),' ','') from EmployeeContactNumber

Result :-- 7183784957

How to convert a byte array to Stream

I am using as what John Rasch said:

Stream streamContent = taxformUpload.FileContent;

Remove non-ascii character in string

You can use the following regex to replace non-ASCII characters

str = str.replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')

However, note that spaces, colons and commas are all valid ASCII, so the result will be

> str
"INFO] :, , ,  (Higashikurume)"

How to merge a specific commit in Git

We will have to use git cherry-pick <commit-number>

Scenario: I am on a branch called release and I want to add only few changes from master branch to release branch.

Step 1: checkout the branch where you want to add the changes

git checkout release

Step 2: get the commit number of the changes u want to add

for example

git cherry-pick 634af7b56ec

Step 3: git push

Note: Every time your merge there is a separate commit number create. Do not take the commit number for merge that won't work. Instead, the commit number for any regular commit u want to add.

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

How to execute the start script with Nodemon

To avoid a global install, add Nodemon as a dependency, then...

package.json

"scripts": {
    "start": "node ./bin/www",
    "start-dev": "./node_modules/nodemon/bin/nodemon.js ./bin/www"
  },

Display image at 50% of its "native" size

The zoom property sounds as though it's perfect for Adam Ernst as it suits his target device. However, for those who need a solution to this and have to support as many devices as possible you can do the following:

<img src="..." onload="this.width/=2;this.onload=null;" />

The reason for the this.onload=null addition is to avoid older browsers that sometimes trigger the load event twice (which means you can end up with quater-sized images). If you aren't worried about that though you could write:

<img src="..." onload="this.width/=2;" />

Which is quite succinct.

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something').attr('src', 'something.jpg');

Make a DIV fill an entire table cell

So, because everyone is posting their solution and none was good for me, here is mine (tested on Chrome & Firefox).

table { height: 1px; } /* Will be ignored, don't worry. */
tr { height: 100%; }
td { height: 100%; }
td > div { height: 100%; }

Fiddle: https://jsfiddle.net/nh6g5fzv/

--

Edit: one thing you might want to note, if you want to apply a padding to the div in the td, you must add box-sizing: border-box; because of height: 100%.

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

What throws an IOException in Java?

Assume you were:

  1. Reading a network file and got disconnected.
  2. Reading a local file that was no longer available.
  3. Using some stream to read data and some other process closed the stream.
  4. Trying to read/write a file, but don't have permission.
  5. Trying to write to a file, but disk space was no longer available.

There are many more examples, but these are the most common, in my experience.

Change private static final field using Java reflection

Even in spite of being final a field can be modified outside of static initializer and (at least JVM HotSpot) will execute the bytecode perfectly fine.

The problem is that Java compiler does not allow this, but this can be easily bypassed using objectweb.asm. Here is p?e?r?f?e?c?t?l?y? ?v?a?l?i?d? ?c?l?a?s?s?f?i?l?e? an invalid classfile from the JVMS specification standpoint, but it passes bytecode verification and then is successfully loaded and initialized under JVM HotSpot OpenJDK12:

ClassWriter cw = new ClassWriter(0);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Cl", null, "java/lang/Object", null);
{
    FieldVisitor fv = cw.visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "fld", "I", null, null);
    fv.visitEnd();
}
{
    // public void setFinalField1() { //... }
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "setFinalField1", "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitInsn(Opcodes.ICONST_5);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, "Cl", "fld", "I");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitEnd();
}
{
    // public void setFinalField2() { //... }
    MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "setFinalField2", "()V", null, null);
    mv.visitMaxs(2, 1);
    mv.visitInsn(Opcodes.ICONST_2);
    mv.visitFieldInsn(Opcodes.PUTSTATIC, "Cl", "fld", "I");
    mv.visitInsn(Opcodes.RETURN);
    mv.visitEnd();
}
cw.visitEnd();

In Java, the class looks roughly speaking as follows:

public class Cl{
    private static final int fld;

    public static void setFinalField1(){
        fld = 5;
    }

    public static void setFinalField2(){
        fld = 2;
    }
}

which cannot be compiled with javac, but can be loaded and executed by JVM.

JVM HotSpot has special treatment of such classes in the sense that it prevents such "constants" from participating in constant folding. This check is done on the bytecode rewriting phase of class initialization:

// Check if any final field of the class given as parameter is modified
// outside of initializer methods of the class. Fields that are modified
// are marked with a flag. For marked fields, the compilers do not perform
// constant folding (as the field can be changed after initialization).
//
// The check is performed after verification and only if verification has
// succeeded. Therefore, the class is guaranteed to be well-formed.
InstanceKlass* klass = method->method_holder();
u2 bc_index = Bytes::get_Java_u2(bcp + prefix_length + 1);
constantPoolHandle cp(method->constants());
Symbol* ref_class_name = cp->klass_name_at(cp->klass_ref_index_at(bc_index));
if (klass->name() == ref_class_name) {
   Symbol* field_name = cp->name_ref_at(bc_index);
   Symbol* field_sig = cp->signature_ref_at(bc_index);

   fieldDescriptor fd;
   if (klass->find_field(field_name, field_sig, &fd) != NULL) {
      if (fd.access_flags().is_final()) {
         if (fd.access_flags().is_static()) {
            if (!method->is_static_initializer()) {
               fd.set_has_initialized_final_update(true);
            }
          } else {
            if (!method->is_object_initializer()) {
              fd.set_has_initialized_final_update(true);
            }
          }
        }
      }
    }
}

The only restriction that JVM HotSpot checks is that the final field should not be modified outside of the class that the final field is declared at.

How do I clear my Jenkins/Hudson build history?

Use the script console (Manage Jenkins > Script Console) and something like this script to bulk delete a job's build history https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/bulkDeleteBuilds.groovy

That script assumes you want to only delete a range of builds. To delete all builds for a given job, use this (tested):

// change this variable to match the name of the job whose builds you want to delete
def jobName = "Your Job Name"
def job = Jenkins.instance.getItem(jobName)

job.getBuilds().each { it.delete() }
// uncomment these lines to reset the build number to 1:
//job.nextBuildNumber = 1
//job.save()

Multiple WHERE Clauses with LINQ extension methods

you can use && and write all conditions in to the same where clause, or you can .Where().Where().Where()... and so on.

What is the purpose of Order By 1 in SQL select statement?

This is useful when you use set based operators e.g. union

select cola
  from tablea
union
select colb
  from tableb
order by 1;

Creating an index on a table variable

The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.

SQL Server 2014

In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.

Example syntax for that is below.

/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
       INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);

Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"

/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)

SQL Server 2000 - 2012

Can I create a index on Name?

Short answer: Yes.

DECLARE @TEMPTABLE TABLE (
  [ID]   [INT] NOT NULL PRIMARY KEY,
  [Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
  UNIQUE NONCLUSTERED ([Name], [ID]) 
  ) 

A more detailed answer is below.

Traditional tables in SQL Server can either have a clustered index or are structured as heaps.

Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.

Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.

In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE or PRIMARY KEY constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULLs is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.

Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED or NONCLUSTERED explicitly with the constraint declaration (Example syntax)

DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)

As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.

+-------------------------------------+-------------------------------------+
|             Index Type              | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index              | Yes                                 |
| Nonunique Clustered Index           |                                     |
| Unique NCI on a heap                | Yes                                 |
| Non Unique NCI on a heap            |                                     |
| Unique NCI on a clustered index     | Yes                                 |
| Non Unique NCI on a clustered index | Yes                                 |
+-------------------------------------+-------------------------------------+

The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name is simulated by a unique index on Name,Id (recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).

A non unique clustered index can also be achieved by manually adding an IDENTITY column to act as a uniqueifier.

DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)

But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.

Ruby on Rails - Import Data from a CSV file

Use this gem: https://rubygems.org/gems/active_record_importer

class Moulding < ActiveRecord::Base
  acts_as_importable
end

Then you may now use:

Moulding.import!(file: File.open(PATH_TO_FILE))

Just be sure to that your headers match the column names of your table

Remove excess whitespace from within a string

There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.

In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.

function secureRip(string $str): string { /* Rips all whitespace securely. */
  $arr = str_split($str, 1);
  $retStr = '';
  foreach ($arr as $char) {
    $retStr .= trim($char);
  }
  return $retStr;
}

Get current controller in view

You can use any of the below code to get the controller name

@HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString();

If you are using MVC 3 you can use

@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue

MongoDB: How to find the exact version of installed MongoDB

From the Java API:

Document result = mongoDatabase.runCommand(new Document("buildInfo", 1));
String version = (String) result.get("version");
List<Integer> versionArray = (List<Integer>) result.get("versionArray");

Android Activity as a dialog

Create activity as dialog, Here is Full Example

enter image description here

  1. AndroidManife.xml

    <activity android:name=".appview.settings.view.DialogActivity" android:excludeFromRecents="true" android:theme="@style/Theme.AppCompat.Dialog"/>

  2. DialogActivity.kt

    class DialogActivity : AppCompatActivity() {
      override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dialog)
        this.setFinishOnTouchOutside(true)
    
        btnOk.setOnClickListener {
          finish()
        }
      }
    }
    
  3. activity_dialog.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#0072ff"
    android:gravity="center"
    android:orientation="vertical">
    
    <LinearLayout
        android:layout_width="@dimen/_300sdp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/txtTitle"
            style="@style/normal16Style"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="20dp"
            android:paddingBottom="20dp"
            android:text="Download"
            android:textColorHint="#FFF" />
    
        <View
            android:id="@+id/viewDivider"
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="#fff"
            android:backgroundTint="@color/white_90"
            app:layout_constraintBottom_toBottomOf="@id/txtTitle" />
    
        <TextView
            style="@style/normal14Style"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingTop="20dp"
            android:paddingBottom="20dp"
            android:text="Your file is download"
            android:textColorHint="#FFF" />
    
    
        <Button
            android:id="@+id/btnOk"
            style="@style/normal12Style"
            android:layout_width="100dp"
            android:layout_height="40dp"
            android:layout_marginBottom="20dp"
            android:background="@drawable/circle_corner_layout"
            android:text="Ok"
            android:textAllCaps="false" />
        </LinearLayout>
    
      </LinearLayout>
    

Change background color for selected ListBox item

<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

and

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

You just override the style of the listboxitem (see the: TargetType is ListBoxItem)

Reading JSON POST using PHP

Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");

getUserLocation($ip_srv);

Function:

function getUserLocation($services) {

        $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout

        for ($i = 0; $i < count($services); $i++) {

            // Configuring curl options
            $options = array (
                CURLOPT_RETURNTRANSFER => true, // return web page
                //CURLOPT_HEADER => false, // don't return headers
                CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                CURLOPT_FOLLOWLOCATION => true, // follow redirects
                CURLOPT_ENCODING => "", // handle compressed
                CURLOPT_USERAGENT => "test", // who am i
                CURLOPT_AUTOREFERER => true, // set referer on redirect
                CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
                CURLOPT_TIMEOUT => 5, // timeout on response
                CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
            ); 

            // Initializing curl
            $ch = curl_init($services[$i]);
            curl_setopt_array ( $ch, $options );

            $content = curl_exec ( $ch );
            $err = curl_errno ( $ch );
            $errmsg = curl_error ( $ch );
            $header = curl_getinfo ( $ch );
            $httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

            curl_close ( $ch );

            //echo 'service: ' . $services[$i] . '</br>';
            //echo 'err: '.$err.'</br>';
            //echo 'errmsg: '.$errmsg.'</br>';
            //echo 'httpCode: '.$httpCode.'</br>';
            //print_r($header);
            //print_r(json_decode($content, true));

            if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {

                return json_decode($content, true);

            } 

        }
    }

Truncate/round whole number in JavaScript?

I'll add my solution here. We can use floor when values are above 0 and ceil when they are less than zero:

function truncateToInt(x)
{
    if(x > 0)
    {
         return Math.floor(x);
    }
    else
    {
         return Math.ceil(x);
    }
 }

Then:

y = truncateToInt(2.9999); // results in 2
y = truncateToInt(-3.118); //results in -3

Notice: This answer was written when Math.trunc(x) was fairly new and not supported by a lot of browsers. Today, modern browsers support Math.trunc(x).

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

How would I stop a while loop after n amount of time?

Try this module: http://pypi.python.org/pypi/interruptingcow/

from interruptingcow import timeout
try:
    with timeout(60*5, exception=RuntimeError):
        while True:
            test = 0
            if test == 5:
                break
            test = test - 1
except RuntimeError:
    pass

The view or its master was not found or no view engine supports the searched locations

In my case, I needed to use RedirectToAction to solve the problem.

[HttpGet]
[ControleDeAcessoAuthorize("Report/ExportToPDF")]
public ActionResult ExportToPDF(int id, string month, string output)
{
    try
    {
        // Validate
        if (output != "PDF")
        {
            throw new Exception("Invalid output.");
        }
        else
        {
            ...// code to generate report in PDF format
        }
    }
    catch (Exception ex)
    {
        return RedirectToAction("Error");
    }
}

[ControleDeAcessoAuthorize("Report/Error")]
public ActionResult Error()
{
    return View();
}

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

Linux command for extracting war file?

Or

jar xvf myproject.war

Stretch and scale a CSS image in the background - with CSS only

CSS3 has a nice little attribute called background-size:cover.

This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too great.

How to get the nvidia driver version from the command line?

To expand on ccc's answer, if you want to incorporate querying the card with a script, here is information on Nvidia site on how to do so:

https://nvidia.custhelp.com/app/answers/detail/a_id/3751/~/useful-nvidia-smi-queries

Also, I found this thread researching powershell. Here is an example command that runs the utility to get the true memory available on the GPU to get you started.

# get gpu metrics
$cmd = "& 'C:\Program Files\NVIDIA Corporation\NVSMI\nvidia-smi' --query-gpu=name,utilization.memory,driver_version --format=csv"
$gpuinfo = invoke-expression $cmd | ConvertFrom-CSV
$gpuname = $gpuinfo.name
$gpuutil = $gpuinfo.'utilization.memory [%]'.Split(' ')[0]
$gpuDriver = $gpuinfo.driver_version

Defining private module functions in python

There may be confusion between class privates and module privates.

A module private starts with one underscore
Such a element is not copied along when using the from <module_name> import * form of the import command; it is however imported if using the import <moudule_name> syntax (see Ben Wilhelm's answer)
Simply remove one underscore from the a.__num of the question's example and it won't show in modules that import a.py using the from a import * syntax.

A class private starts with two underscores (aka dunder i.e. d-ouble under-score)
Such a variable has its name "mangled" to include the classname etc.
It can still be accessed outside of the class logic, through the mangled name.
Although the name mangling can serve as a mild prevention device against unauthorized access, its main purpose is to prevent possible name collisions with class members of the ancestor classes. See Alex Martelli's funny but accurate reference to consenting adults as he describes the convention used in regards to these variables.

>>> class Foo(object):
...    __bar = 99
...    def PrintBar(self):
...        print(self.__bar)
...
>>> myFoo = Foo()
>>> myFoo.__bar  #direct attempt no go
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
>>> myFoo.PrintBar()  # the class itself of course can access it
99
>>> dir(Foo)    # yet can see it
['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__
format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__
', '__subclasshook__', '__weakref__']
>>> myFoo._Foo__bar  #and get to it by its mangled name !  (but I shouldn't!!!)
99
>>>

multiple conditions for JavaScript .includes() method

That should work even if one, and only one of the conditions is true :

var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];

function contains(target, pattern){
    var value = 0;
    pattern.forEach(function(word){
      value = value + target.includes(word);
    });
    return (value === 1)
}

console.log(contains(str, arr));

How to allow http content within an iframe on a https site

Use your own HTTPS-to-HTTP reverse proxy.

If your use case is about a few, rarely changing URLs to embed into the iframe, you can simply set up a reverse proxy for this on your own server and configure it so that one https URL on your server maps to one http URL on the proxied server. Since a reverse proxy is fully serverside, the browser cannot discover that it is "only" talking to a proxy of the real website, and thus will not complain as the connection to the proxy uses SSL properly.

If for example you use Apache2 as your webserver, then see these instructions to create a reverse proxy.

Regex Match all characters between two strings

RegEx to match everything between two strings using the Java approach.

List<String> results = new ArrayList<>(); //For storing results
String example = "Code will save the world";

Let's use Pattern and Matcher objects to use RegEx (.?)*.

Pattern p = Pattern.compile("Code "(.*?)" world");   //java.util.regex.Pattern;
Matcher m = p.matcher(example);                      //java.util.regex.Matcher;

Since Matcher might contain more than one match, we need to loop over the results and store it.

while(m.find()){   //Loop through all matches
   results.add(m.group()); //Get value and store in collection.
}

This example will contain only "will save the" word, but in the bigger text it will probably find more matches.

How to make an AJAX call without jQuery?

This may help:

function doAjax(url, callback) {
    var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            callback(xmlhttp.responseText);
        }
    }

    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}