Programs & Examples On #Clause

The SQL OVER() clause - when and why is it useful?

prkey   whatsthat               cash   
890    "abb                "   32  32
43     "abbz               "   2   34
4      "bttu               "   1   35
45     "gasstuff           "   2   37
545    "gasz               "   5   42
80009  "hoo                "   9   51
2321   "ibm                "   1   52
998    "krk                "   2   54
42     "kx-5010            "   2   56
32     "lto                "   4   60
543    "mp                 "   5   65
465    "multipower         "   2   67
455    "O.N.               "   1   68
7887   "prem               "   7   75
434    "puma               "   3   78
23     "retractble         "   3   81
242    "Trujillo's stuff   "   4   85

That's a result of query. Table used as source is the same exept that it has no last column. This column is a moving sum of third one.

Query:

SELECT prkey,whatsthat,cash,SUM(cash) over (order by whatsthat)
    FROM public.iuk order by whatsthat,prkey
    ;

(table goes as public.iuk)

sql version:  2012

It's a little over dbase(1986) level, I don't know why 25+ years has been needed to finish it up.

How to call a php script/function on a html button click

Just try this:

<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
    $(document).ready(function(){
        $("button").click(function(){

            $.ajax({
                type: 'POST',
                url: 'script.php',
                success: function(data) {
                    alert(data);
                    $("p").text(data);

                }
            });
   });
});
</script>

In script.php

<?php 
  echo "You win";
 ?>

100% width Twitter Bootstrap 3 template

This is the complete basic structure for 100% width layout in Bootstrap v3.0.0. You shouldn't wrap your <div class="row"> with container class. Cause container class will take lots of margin and this will not provide you full screen (100% width) layout where bootstrap has removed container-fluid class from their mobile-first version v3.0.0.

So just start writing <div class="row"> without container class and you are ready to go with 100% width layout.

<!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap Basic 100% width Structure</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="http://getbootstrap.com/assets/js/html5shiv.js"></script>
  <script src="http://getbootstrap.com/assets/js/respond.min.js"></script>
<![endif]-->
<style>
    .red{
        background-color: red;
    }
    .green{
        background-color: green;
    }
</style>
</head>
<body>
    <div class="row">
        <div class="col-md-3 red">Test content</div>
        <div class="col-md-9 green">Another Content</div>
    </div>
    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="//code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
</body>
</html>

To see the result by yourself I have created a bootply. See the live output there. http://bootply.com/82136 And the complete basic bootstrap 3 100% width layout I have created a gist. you can use that. Get the gist from here

Reply me if you need more further assistance. Thanks.

Clear Cache in Android Application programmatically

I am not sure but I sow this code too. this cod will work faster and in my mind its simple too. just get your apps cache directory and delete all files in directory

public boolean clearCache() {
    try {

        // create an array object of File type for referencing of cache files   
        File[] files = getBaseContext().getCacheDir().listFiles();

        // use a for etch loop to delete files one by one
        for (File file : files) {

             /* you can use just [ file.delete() ] function of class File
              * or use if for being sure if file deleted
              * here if file dose not delete returns false and condition will
              * will be true and it ends operation of function by return 
              * false then we will find that all files are not delete
              */
             if (!file.delete()) {
                 return false;         // not success
             }
        }

        // if for loop completes and process not ended it returns true   
        return true;      // success of deleting files

    } catch (Exception e) {}

    // try stops deleting cache files
    return false;       // not success 
}

It gets all of cache files in File array by getBaseContext().getCacheDir().listFiles() and then deletes one by one in a loop by file.delet() method

Decimal to Hexadecimal Converter in Java

Check out the code below for decimal to hexadecimal conversion,

import java.util.Scanner;

public class DecimalToHexadecimal
{
   public static void main(String[] args)
   {
      int temp, decimalNumber;
      String hexaDecimal = "";
      char hexa[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};

      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter decimal number : ");
      decimalNumber = sc.nextInt();

      while(decimalNumber > 0)
      {
         temp = decimalNumber % 16;
         hexaDecimal = hexa[temp] + hexaDecimal;
         decimalNumber = decimalNumber / 16;
      }

      System.out.print("The hexadecimal value of " + decimalNumber + " is : " + hexaDecimal);      
      sc.close();
   }
}

You can learn more on different ways to convert decimal to hexadecimal in the following link >> java convert decimal to hexadecimal.

How do I add a new class to an element dynamically?

Using CSS only, no. You need to use jQuery to add it.

jQuery: count number of rows in a table

var trLength = jQuery('#tablebodyID >tr').length;

How to fix a header on scroll

You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.

HTML

<div class="sticky"></div>

CSS

.fixed {
    position: fixed;
    top:0; left:0;
    width: 100%; }

jQuery

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

Example fiddle: http://jsfiddle.net/gxRC9/501/


EDIT: Extended example

If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top can be used.

var stickyOffset = $('.sticky').offset().top;

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= stickyOffset) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

Extended example fiddle: http://jsfiddle.net/gxRC9/502/

Using Colormaps to set color of line in matplotlib

I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.

import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.jet(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')
plt.show()

This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.

cm.jet between 0.0 and 1.0 with 1000 graduations

Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.

enter image description here

So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:

colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]

In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:

>>> from matplotlib import cm
>>> dir(cm)

How to start a Process as administrator mode in C#

 Process proc = new Process();                                                              
                   ProcessStartInfo info = 
                   new ProcessStartInfo("Your Process name".exe, "Arguments");
                   info.WindowStyle = ProcessWindowStyle.Hidden;
                   info.UseShellExecute =true;
                   info.Verb ="runas";
                   proc.StartInfo = info;
                   proc.Start();

Hide strange unwanted Xcode logs

My solution is to use the debugger command and/or Log Message in breakpoints.

enter image description here

And change the output of console from All Output to Debugger Output like

enter image description here

Unresponsive KeyListener for JFrame

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:

myComponent.setFocusable(true);

Print second last column/field in awk

First decrements the value and then print it -

awk ' { print $(--NF)}' file

OR

rev file|cut -d ' ' -f2|rev

ImageMagick security policy 'PDF' blocking conversion

Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:

sudo apt install img2pdf

Convert one or more images to pdf:

img2pdf img.jpg -o output.pdf

It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.

Is there a way to compile node.js source files?

javascript does not not have a compiler like for example Java/C(You can compare it more to languages like PHP for example). If you want to write compiled code you should read the section about addons and learn C. Although this is rather complex and I don't think you need to do this but instead just write javascript.

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

Adding multiple class using ng-class

Here is an example comparing multiple angular-ui-router states using the OR || operator:

<li ng-class="
    {
        warning:
            $state.includes('out.pay.code.wrong')
            || $state.includes('out.pay.failed')
        ,
        active:
            $state.includes('out.pay')
    }
">

It will give the li the classes warning and/or active, depening on whether the conditions are met.

I want to exception handle 'list index out of range.'

A ternary will suffice. change:

gotdata = dlist[1]

to

gotdata = dlist[1] if len(dlist) > 1 else 'null'

this is a shorter way of expressing

if len(dlist) > 1:
    gotdata = dlist[1]
else: 
    gotdata = 'null'

How can I use jQuery to make an input readonly?

Perhaps it's meaningful to also add that

$('#fieldName').prop('readonly',false);

can be used as a toggle option..

How to add CORS request in header in Angular 5

The following worked for me after hours of trying

      $http.post("http://localhost:8080/yourresource", parameter, {headers: 
      {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }).

However following code did not work, I am unclear as to why, hopefully someone can improve this answer.

          $http({   method: 'POST', url: "http://localhost:8080/yourresource", 
                    parameter, 
                    headers: {'Content-Type': 'application/json', 
                              'Access-Control-Allow-Origin': '*',
                              'Access-Control-Allow-Methods': 'POST'} 
                })

How do I add an existing directory tree to a project in Visual Studio?

You need to put your directory structure in your project directory. And then click "Show All Files" icon in the top of Solution Explorer toolbox. After that, the added directory will be shown up. You will then need to select this directory, right click, and choose "Include in Project."

enter image description here

enter image description here

How do you set the title color for the new Toolbar?

With the Material Components Library you can use the app:titleTextColor attribute.

In the layout you can use something like:

<com.google.android.material.appbar.MaterialToolbar
    app:titleTextColor="@color/...."
    .../>

You can also use a custom style:

<com.google.android.material.appbar.MaterialToolbar
     style="@style/MyToolbarStyle"
    .../>

with (extending the Widget.MaterialComponents.Toolbar.Primary style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar.Primary">
       <item name="titleTextColor">@color/....</item>
  </style>

or (extending the Widget.MaterialComponents.Toolbar style) :

  <style name="MyToolbarStyle" parent="Widget.MaterialComponents.Toolbar">
       <item name="titleTextColor">@color/....</item>
  </style>

enter image description here

You can also override the color defined by the style using the android:theme attribute (using the Widget.MaterialComponents.Toolbar.Primary style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
        android:theme="@style/MyThemeOverlay_Toolbar"
        />

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is also used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/...</item>
  </style>

enter image description here

or (using the Widget.MaterialComponents.Toolbar style):

    <com.google.android.material.appbar.MaterialToolbar
        style="@style/Widget.MaterialComponents.Toolbar"
        android:theme="@style/MyThemeOverlay_Toolbar2"

with:

  <style name="MyThemeOverlay_Toolbar3" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- This attributes is used by title -->
    <item name="android:textColorPrimary">@color/white</item>

    <!-- This attributes is used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/secondaryColor</item>
  </style>

How to check version of a CocoaPods framework

pod --version

to get the version of installed pod

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

Django DoesNotExist

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code

How to delete a character from a string using Python

You can simply use list comprehension.

Assume that you have the string: my name is and you want to remove character m. use the following code:

"".join([x for x in "my name is" if x is not 'm'])

How do you rotate a two dimensional array?

Here is my attempt for matrix 90 deg rotation which is a 2 step solution in C. First transpose the matrix in place and then swap the cols.

#define ROWS        5
#define COLS        5

void print_matrix_b(int B[][COLS], int rows, int cols) 
{
    for (int i = 0; i <= rows; i++) {
        for (int j = 0; j <=cols; j++) {
            printf("%d ", B[i][j]);
        }
        printf("\n");
    }
}

void swap_columns(int B[][COLS], int l, int r, int rows)
{
    int tmp;
    for (int i = 0; i <= rows; i++) {
        tmp = B[i][l];
        B[i][l] = B[i][r];
        B[i][r] = tmp;
    }
}


void matrix_2d_rotation(int B[][COLS], int rows, int cols)
{
    int tmp;
    // Transpose the matrix first
    for (int i = 0; i <= rows; i++) {
        for (int j = i; j <=cols; j++) {
            tmp = B[i][j];
            B[i][j] = B[j][i];
            B[j][i] = tmp;
        }
    }
    // Swap the first and last col and continue until
    // the middle.
    for (int i = 0; i < (cols / 2); i++)
        swap_columns(B, i, cols - i, rows);
}



int _tmain(int argc, _TCHAR* argv[])
{
    int B[ROWS][COLS] = { 
                  {1, 2, 3, 4, 5}, 
                      {6, 7, 8, 9, 10},
                          {11, 12, 13, 14, 15},
                          {16, 17, 18, 19, 20},
                          {21, 22, 23, 24, 25}
                        };

    matrix_2d_rotation(B, ROWS - 1, COLS - 1);

    print_matrix_b(B, ROWS - 1, COLS -1);
    return 0;
}

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

How to fix java.net.SocketException: Broken pipe?

All the open streams & connections need to be properly closed, so the next time we try to use the urlConnection object, it does not throw an error. As an example, the following code change fixed the error for me.

Before:

OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write("Some text");
bw.close();
out.close();

After:

OutputStream os = urlConnection.getOutputStream();
OutputStream out = new BufferedOutputStream(os);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
bw.write("Some text");
bw.close();
out.close();
os.close(); // This is a must.

Different ways of clearing lists

There are two cases in which you might want to clear a list:

  1. You want to use the name old_list further in your code;
  2. You want the old list to be garbage collected as soon as possible to free some memory;

In case 1 you just go on with the assigment:

    old_list = []    # or whatever you want it to be equal to

In case 2 the del statement would reduce the reference count to the list object the name old list points at. If the list object is only pointed by the name old_list at, the reference count would be 0, and the object would be freed for garbage collection.

    del old_list

Difference between Activity and FragmentActivity

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

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

WebView link click open default browser

WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl(https://whatoplay.com/);

You don't have to include this code.

// webview.setWebViewClient(new WebViewClient());

Instead use below code.

webview.setWebViewClient(new WebViewClient()
{
  public boolean shouldOverrideUrlLoading(WebView view, String url)
  {
    String url2="https://whatoplay.com/";
     // all links  with in ur site will be open inside the webview 
     //links that start ur domain example(http://www.example.com/)
    if (url != null && url.startsWith(url2)){
      return false;
    } 
     // all links that points outside the site will be open in a normal android browser
    else
    {
      view.getContext().startActivity(
      new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
      return true;
    }
  }
});

MySQL how to join tables on two fields

JOIN t2 ON t1.id=t2.id AND t1.date=t2.date

How do you read a file into a list in Python?

The pythonic way to read a file and put every lines in a list:

from __future__ import with_statement #for python 2.5
with open('C:/path/numbers.txt', 'r') as f:
    lines = f.readlines()

Then, assuming that each lines contains a number,

numbers =[int(e.strip()) for e in lines]

how to change class name of an element by jquery

$('.IsBestAnswer').removeClass('IsBestAnswer').addClass('bestanswer');

Your code has two problems:

  1. The selector .IsBestAnswe does not match what you thought
  2. It's addClass(), not addclass().

Also, I'm not sure whether you want to replace the class or add it. The above will replace, but remove the .removeClass('IsBestAnswer') part to add only:

$('.IsBestAnswer').addClass('bestanswer');

You should decide whether to use camelCase or all-lowercase in your CSS classes too (e.g. bestAnswer vs. bestanswer).

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

I read all the comments and suggestions. 500 - HTTP ERROR CODE represents internal server error.

Reasons for this error:

  • These mainly cause due to permission issues
  • Environment variables not found or .env file not found on your root directory
  • PHP extensions problem
  • Database problem

Fix:

  • Set the correct permissions:
  • Run these commands (Ubuntu/Debian)
find /path/to/your/root/dir/ -type f -exec chmod 644 {} \;
find /path/to/your/root/dir/ -type d -exec chmod 755 {} \;

chown -R www-data:www-data /path/to/your/root/dir/

chgrp -R www-data storage bootstrap/cache
chmod -R ug+rwx storage bootstrap/cache
  • If .env file doesn't exist, create one by touch .env and paste your environment variables and then run
   php artisan key:generate
   php artisan cache:clear
   php artisan config:clear
   composer dump-autoload
  • Check your php.ini file and uncomment the extensions you need (In some case you have to install the extension by running this command apt-get install php7.2-[extension-name]
  • Check your database credentials and values in .env file. And grant permissions to the database user for that database.

These are some common problem you likely going to face when deploying your laravel app and once you start getting all these commands, I suggest you to make a script which will save your time.

Android - save/restore fragment state

You can get current Fragment from fragmentManager. And if there are non of them in fragment manager you can create Fragment_1

public class MainActivity extends FragmentActivity {


    public static Fragment_1 fragment_1;
    public static Fragment_2 fragment_2;
    public static Fragment_3 fragment_3;
    public static FragmentManager fragmentManager;


    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.main);

        fragment_1 = (Fragment_1) fragmentManager.findFragmentByTag("fragment1");

        fragment_2  =(Fragment_2) fragmentManager.findFragmentByTag("fragment2");

        fragment_3 = (Fragment_3) fragmentManager.findFragmentByTag("fragment3");


        if(fragment_1==null && fragment_2==null && fragment_3==null){           
            fragment_1 = new Fragment_1();          
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment_1, "fragment1").commit();
        }


    }


}

also you can use setRetainInstance to true what it will do it ignore onDestroy() method in fragment and your application going to back ground and os kill your application to allocate more memory you will need to save all data you need in onSaveInstanceState bundle

public class Fragment_1 extends Fragment {


    private EditText title;
    private Button go_next;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true); //Will ignore onDestroy Method (Nested Fragments no need this if parent have it)
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        onRestoreInstanceStae(savedInstanceState);
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    //Here you can restore saved data in onSaveInstanceState Bundle
    private void onRestoreInstanceState(Bundle savedInstanceState){
        if(savedInstanceState!=null){
            String SomeText = savedInstanceState.getString("title");            
        }
    }

    //Here you Save your data
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("title", "Some Text");
    }

}

What's the easy way to auto create non existing dir in ansible

AFAIK, the only way this could be done is by using the state=directory option. While template module supports most of copy options, which in turn supports most file options, you can not use something like state=directory with it. Moreover, it would be quite confusing (would it mean that {{project_root}}/conf/code.conf is a directory ? or would it mean that {{project_root}}/conf/ should be created first.

So I don't think this is possible right now without adding a previous file task.

- file: 
    path: "{{project_root}}/conf"
    state: directory
    recurse: yes

Angular ng-class if else

You can use the ternary operator notation:

<div id="homePage" ng-class="page.isSelected(1)? 'center' : 'left'">

pip install returning invalid syntax

Try:

pip3 install bs4

If you have python2 installed you typically have to make sure you are using the correct version of pip.

How to sort a file, based on its numerical values for a field?

Use sort -nr for sorting in descending order. Refer

Sort

Refer the above Man page for further reference

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

How to call one shell script from another shell script?

Just add in a line whatever you would have typed in a terminal to execute the script!
e.g.:

#!bin/bash
./myscript.sh &

if the script to be executed is not in same directory, just use the complete path of the script.
e.g.:`/home/user/script-directory/./myscript.sh &

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Problem solved, I've not added the index.html. Which is point out in the web.xml

enter image description here

Note: a project may have more than one web.xml file.

if there are another web.xml in

src/main/webapp/WEB-INF

Then you might need to add another index (this time index.jsp) to

src/main/webapp/WEB-INF/pages/

How can I find a file/directory that could be anywhere on linux command line?

The find command will take long time, the fastest way to search for file is using locate command, which looks for file names (and path) in a indexed database (updated by command updatedb).

The result will appear immediately with a simple command:

locate {file-name-or-path}

If the command is not found, you need to install mlocate package and run updatedb command first to prepare the search database for the first time.

More detail here: https://medium.com/@thucnc/the-fastest-way-to-find-files-by-filename-mlocate-locate-commands-55bf40b297ab

Read line with Scanner

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Read article :Difference between next() and nextLine()

Replace your while loop with :

while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.

mysql query: SELECT DISTINCT column1, GROUP BY column2

Replacing FROM tablename with FROM (SELECT DISTINCT * FROM tablename) should give you the result you want (ignoring duplicated rows) for example:

SELECT name, COUNT(*)
FROM (SELECT DISTINCT * FROM Table1) AS T1
GROUP BY name

Result for your test data:

dave 2
mark 2

How to run python script on terminal (ubuntu)?

This error:

python: can't open file 'test.py': [Errno 2] No such file or directory

Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)

I must save the file in any specific folder to make it run on terminal?

No, it can be where ever you want. However, if you just say, "test.py", you'll need to be in the directory containing test.py.

Your terminal (actually, the shell in the terminal) has a concept of "Current working directory", which is what directory (folder) it is currently "in".

Thus, if you type something like:

python test.py

test.py needs to be in the current working directory. In Linux, you can change the current working directory with cd. You might want a tutorial if you're new. (Note that the first hit on that search for me is this YouTube video. The author in the video is using a Mac, but both Mac and Linux use bash for a shell, so it should apply to you.)

Pad left or right with string.format (not padleft or padright) with arbitrary string

You could encapsulate the string in a struct that implements IFormattable

public struct PaddedString : IFormattable
{
   private string value;
   public PaddedString(string value) { this.value = value; }

   public string ToString(string format, IFormatProvider formatProvider)
   { 
      //... use the format to pad value
   }

   public static explicit operator PaddedString(string value)
   {
     return new PaddedString(value);
   }
}

Then use this like that :

 string.Format("->{0:x20}<-", (PaddedString)"Hello");

result:

"->xxxxxxxxxxxxxxxHello<-"

UILabel text margin

Maybe you could give this code a try

CGRect frame = btn.titleLabel.frame;
int indent = 20;
int inset = 20;
[btn.titleLabel setFrame:CGRectMake(frame.origin.x+inset,frame.origin.y,frame.size.width+indent,frame.size.height)];

How to place two divs next to each other?

It is very easy - you could do it the hard way

_x000D_
_x000D_
.clearfix:after {_x000D_
   content: " "; _x000D_
   visibility: hidden;_x000D_
   display: block;_x000D_
   height: 0;_x000D_
   clear: both;_x000D_
}_x000D_
_x000D_
#first, #second{_x000D_
  box-sizing: border-box;_x000D_
  -moz-box-sizing: border-box;_x000D_
  -webkit-box-sizing: border-box;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
    width: 500px;_x000D_
    border: 1px solid black;_x000D_
}_x000D_
#first {_x000D_
    border: 1px solid red;_x000D_
    float:left;_x000D_
    width:50%;_x000D_
}_x000D_
#second {_x000D_
    border: 1px solid green;_x000D_
    float:left;_x000D_
    width:50%;_x000D_
}
_x000D_
<div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
    <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

or the easy way

_x000D_
_x000D_
#wrapper {_x000D_
  display: flex;_x000D_
  border: 1px solid black;_x000D_
}_x000D_
#first {_x000D_
    border: 1px solid red;_x000D_
}_x000D_
#second {_x000D_
    border: 1px solid green;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
    <div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div>_x000D_
    <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

There's also like a million other ways.
But I'd just with the easy way. I would also like to tell you that a lot of the answers here are incorrect But both the ways that I have shown at least work in HTML 5.

How do you list volumes in docker containers?

if you want to list all the containers name with the relevant volumes that attached to each container you can try this:

docker ps -q | xargs docker container inspect -f '{{ .Name }} {{ .HostConfig.Binds }}'

example output:

/opt_rundeck_1 [/opt/var/lib/mysql:/var/lib/mysql:rw /var/lib/rundeck/var/storage:/var/lib/rundeck/var/storage:rw /opt/var/rundeck/.ssh:/var/lib/rundeck/.ssh:rw /opt/etc/rundeck:/etc/rundeck:rw /var/log/rundeck:/var/log/rundeck:rw /opt/rundeck-plugins:/opt/rundeck-plugins:rw /opt/var/rundeck:/var/rundeck:rw]

/opt_rundeck_1 - container name

[..] - volumes attached to the conatiner

How to "log in" to a website using Python's Requests module?

Find out the name of the inputs used on the websites form for usernames <...name=username.../> and passwords <...name=password../> and replace them in the script below. Also replace the URL to point at the desired site to log into.

login.py

#!/usr/bin/env python

import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
payload = { 'username': '[email protected]', 'password': 'blahblahsecretpassw0rd' }
url = 'https://website.com/login.html'
requests.post(url, data=payload, verify=False)

The use of disable_warnings(InsecureRequestWarning) will silence any output from the script when trying to log into sites with unverified SSL certificates.

Extra:

To run this script from the command line on a UNIX based system place it in a directory, i.e. home/scripts and add this directory to your path in ~/.bash_profile or a similar file used by the terminal.

# Custom scripts
export CUSTOM_SCRIPTS=home/scripts
export PATH=$CUSTOM_SCRIPTS:$PATH

Then create a link to this python script inside home/scripts/login.py

ln -s ~/home/scripts/login.py ~/home/scripts/login

Close your terminal, start a new one, run login

GCC -fPIC option

Code that is built into shared libraries should normally be position-independent code, so that the shared library can readily be loaded at (more or less) any address in memory. The -fPIC option ensures that GCC produces such code.

Hidden Features of C#?

I love using the @ character for SQL queries. It keeps the sql nice and formatted and without having to surround each line with a string delimiter.

string sql = @"SELECT firstname, lastname, email
               FROM users
               WHERE username = @username AND password = @password";

Adding <script> to WordPress in <head> element

Elaborating on the previous answer, you can gather all the required snippets before outputting the header, and only then use an action hook to inject all you need on the head.

In your functions.php file, add

$inject_required_scripts = array();

/**
 * Call this function before calling get_header() to request custom js code to be injected on head.
 *
 * @param code the javascript code to be injected.
 */
function require_script($code) {
  global $inject_required_scripts;
  $inject_required_scripts[] = $code; // store code snippet for later injection
}

function inject_required_scripts() {
  global $inject_required_scripts;
  foreach($inject_required_scripts as $script)
    // inject all code snippets, if any
    echo '<script type="text/javascript">'.$script.'</script>';
}
add_action('wp_head', 'inject_required_scripts');

And then in your page or template, use it like

<?php
/* Template Name: coolstuff */

require_script(<<<JS
  jQuery(function(){jQuery('div').wrap('<blink/>')});
JS
);

require_script(<<<JS
  jQuery(function(){jQuery('p,span,a').html('Internet is cool')});
JS
);

get_header();
[...]

I made it for javascript because it's the most common use, but it can be easily adapted to any tag in the head, and either with inline code or by passing a href/src to an external URL.

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link

https://www.postgresql.org/docs/current/xfunc-sql.html

EX:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

Reason to Pass a Pointer by Reference in C++?

Another situation when you may need this is if you have stl collection of pointers and want to change them using stl algorithm. Example of for_each in c++98.

struct Storage {
  typedef std::list<Object*> ObjectList;
  ObjectList objects;

  void change() {
    typedef void (*ChangeFunctionType)(Object*&);
    std::for_each<ObjectList::iterator, ChangeFunctionType>
                 (objects.begin(), objects.end(), &Storage::changeObject);
  }

  static void changeObject(Object*& item) {
    delete item;
    item = 0;
    if (someCondition) item = new Object();
  } 

};

Otherwise, if you use changeObject(Object* item) signature you have copy of pointer, not original one.

Python: Generate random number between x and y which is a multiple of 5

If you don't want to do it all by yourself, you can use the random.randrange function.

For example import random; print random.randrange(10, 25, 5) prints a number that is between 10 and 25 (10 included, 25 excluded) and is a multiple of 5. So it would print 10, 15, or 20.

Convert xlsx file to csv using batch

Needs installed excel as it uses the Excel.Application com object.Save this as .bat file:

@if (@X)==(@Y) @end /* JScript comment
    @echo off


    cscript //E:JScript //nologo "%~f0" %*

    exit /b %errorlevel%

@if (@X)==(@Y) @end JScript comment */


var ARGS = WScript.Arguments;

var xlCSV = 6;

var objExcel = WScript.CreateObject("Excel.Application");
var objWorkbook = objExcel.Workbooks.Open(ARGS.Item(0));
objExcel.DisplayAlerts = false;
objExcel.Visible = false;

var objWorksheet = objWorkbook.Worksheets(ARGS.Item(1))
objWorksheet.SaveAs( ARGS.Item(2), xlCSV);

objExcel.Quit();

It accepts three arguments - the absolute path to the xlsx file, the sheet name and the absolute path to the target csv file:

call toCsv.bat "%cd%\Book1.xlsx" Sheet1 "%cd%\csv.csv"

Unable to merge dex

./gradlew :app:assembleStubLiveDebug -debug -stacktrace

Or similar (get the task name (:app:assembleStubLiveDebug) from Android Studio).

Change connection string & reload app.config at run time

Had to do this exact thing. This is the code that worked for me:

var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["Blah"].ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah";
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");

Angularjs $q.all

$http is a promise too, you can make it simpler:

return $q.all(tasks.map(function(d){
        return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
    }));

What is Cache-Control: private?

The Expires entity-header field gives the date/time after which the response is considered stale.The Cache-control:maxage field gives the age value (in seconds) bigger than which response is consider stale.

Althought above header field give a mechanism to client to decide whether to send request to the server. In some condition, the client send a request to sever and the age value of response is bigger then the maxage value ,dose it means server needs to send the resource to client? Maybe the resource never changed.

In order to resolve this problem, HTTP1.1 gives last-modifided head. The server gives the last modified date of the response to client. When the client need this resource, it will send If-Modified-Since head field to server. If this date is before the modified date of the resouce, the server will sends the resource to client and gives 200 code.Otherwise,it will returns 304 code to client and this means client can use the resource it cached.

How do I use the Tensorboard callback of Keras?

If you are using google-colab simple visualization of the graph would be :

import tensorboardcolab as tb

tbc = tb.TensorBoardColab()
tensorboard = tb.TensorBoardColabCallback(tbc)


history = model.fit(x_train,# Features
                    y_train, # Target vector
                    batch_size=batch_size, # Number of observations per batch
                    epochs=epochs, # Number of epochs
                    callbacks=[early_stopping, tensorboard], # Early stopping
                    verbose=1, # Print description after each epoch
                    validation_split=0.2, #used for validation set every each epoch
                    validation_data=(x_test, y_test)) # Test data-set to evaluate the model in the end of training

PHP cURL error code 60

Use this certificate root certificate bundle:

https://curl.haxx.se/ca/cacert.pem

Copy this certificate bundle on your disk. And use this on php.ini

curl.cainfo = "path_to_cert\cacert.pem"

Use Excel pivot table as data source for another Pivot Table

As @nutsch implies, Excel won't do what you need directly, so you have to copy your data from the pivot table to somewhere else first. Rather than using copy and then paste values, however, a better way for many purposes is to create some hidden columns or a whole hidden sheet that copies values using simple formulae. The copy-paste approach isn't very useful when the original pivot table gets refreshed.

For instance, if Sheet1 contains the original pivot table, then:

  • Create Sheet2 and put =Sheet1!A1 into Sheet2!A1
  • Copy that formula around as many cells in Sheet2 as required to match the size of the original pivot table.
  • Assuming that the original pivot table could change size whenever it is refreshed, you could copy the formula in Sheet2 to cover the whole of the potential area the original pivot table could ever take. That will put lots of zeros in cells where the original cells are currently empty, but you could avoid that by using the formula =IF(Sheet1!A1="","",Sheet1!A1) instead.
  • Create your new pivot table based on a range within Sheet2, then hide Sheet2.

jQuery CSS Opacity

try using .animate instead of .css or even just on the opacity one and leave .css on the display?? may b

jQuery(document).ready(function(){
if (jQuery('#nav .drop').animate('display') === 'block') {
    jQuery('#main').animate('opacity') = '0.6';

Changing cell color using apache poi

Short version: Create styles only once, use them everywhere.

Long version: use a method to create the styles you need (beware of the limit on the amount of styles).

private static Map<String, CellStyle> styles;

private static Map<String, CellStyle> createStyles(Workbook wb){
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        DataFormat df = wb.createDataFormat();

        CellStyle style;
        Font headerFont = wb.createFont();
        headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
        headerFont.setFontHeightInPoints((short) 12);
        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFont(headerFont);
        styles.put("style1", style);

        style = createBorderedStyle(wb);
        style.setAlignment(CellStyle.ALIGN_CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(CellStyle.SOLID_FOREGROUND);
        style.setFont(headerFont);
        style.setDataFormat(df.getFormat("d-mmm"));
        styles.put("date_style", style);
        ...
        return styles;
    }

you can also use methods to do repetitive tasks while creating styles hashmap

private static CellStyle createBorderedStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        return style;
    }

then, in your "main" code, set the style from the styles map you have.

Cell cell = xssfCurrentRow.createCell( intCellPosition );       
cell.setCellValue( blah );
cell.setCellStyle( (CellStyle) styles.get("style1") );

what is reverse() in Django

The existing answers are quite clear. Just in case you do not know why it is called reverse: It takes an input of a url name and gives the actual url, which is reverse to having a url first and then give it a name.

JQuery $.ajax() post - data in a java servlet

Simple method to sending data using java script and ajex call.

First right your form like this

<form id="frm_details" method="post" name="frm_details">
<input  id="email" name="email" placeholder="Your Email id" type="text" />
    <button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form> 

javascript logic target on form id #frm_details after sumbit

$(function(){
        $("#frm_details").on("submit", function(event) {
            event.preventDefault();

            var formData = {
                'email': $('input[name=email]').val() //for get email 
            };
            console.log(formData);

            $.ajax({
                url: "/tsmisc/api/subscribe-newsletter",
                type: "post",
                data: formData,
                success: function(d) {
                    alert(d);
                }
            });
        });
    }) 





General 
Request URL:https://test.abc
Request Method:POST
Status Code:200 
Remote Address:13.76.33.57:443

From Data
email:[email protected]

how to do bitwise exclusive or of two strings in python?

Below illustrates XORing string s with m, and then again to reverse the process:

>>> s='hello, world'
>>> m='markmarkmark'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'hello, world'
>>>

PHP - Copy image to my server direct from URL

From Copy images from url to server, delete all images after

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

$imgurl = 'http://www.foodtest.ru/images/big_img/sausage_3.jpg'; 
$imagename= basename($imgurl);
if(file_exists('./tmp/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('tmp/'.$imagename,$image);       

Finding all cycles in a directed graph

If what you want is to find all elementary circuits in a graph you can use the EC algorithm, by JAMES C. TIERNAN, found on a paper since 1970.

The very original EC algorithm as I managed to implement it in php (hope there are no mistakes is shown below). It can find loops too if there are any. The circuits in this implementation (that tries to clone the original) are the non zero elements. Zero here stands for non-existence (null as we know it).

Apart from that below follows an other implementation that gives the algorithm more independece, this means the nodes can start from anywhere even from negative numbers, e.g -4,-3,-2,.. etc.

In both cases it is required that the nodes are sequential.

You might need to study the original paper, James C. Tiernan Elementary Circuit Algorithm

<?php
echo  "<pre><br><br>";

$G = array(
        1=>array(1,2,3),
        2=>array(1,2,3),
        3=>array(1,2,3)
);


define('N',key(array_slice($G, -1, 1, true)));
$P = array(1=>0,2=>0,3=>0,4=>0,5=>0);
$H = array(1=>$P, 2=>$P, 3=>$P, 4=>$P, 5=>$P );
$k = 1;
$P[$k] = key($G);
$Circ = array();


#[Path Extension]
EC2_Path_Extension:
foreach($G[$P[$k]] as $j => $child ){
    if( $child>$P[1] and in_array($child, $P)===false and in_array($child, $H[$P[$k]])===false ){
    $k++;
    $P[$k] = $child;
    goto EC2_Path_Extension;
}   }

#[EC3 Circuit Confirmation]
if( in_array($P[1], $G[$P[$k]])===true ){//if PATH[1] is not child of PATH[current] then don't have a cycle
    $Circ[] = $P;
}

#[EC4 Vertex Closure]
if($k===1){
    goto EC5_Advance_Initial_Vertex;
}
//afou den ksana theoreitai einai asfales na svisoume
for( $m=1; $m<=N; $m++){//H[P[k], m] <- O, m = 1, 2, . . . , N
    if( $H[$P[$k-1]][$m]===0 ){
        $H[$P[$k-1]][$m]=$P[$k];
        break(1);
    }
}
for( $m=1; $m<=N; $m++ ){//H[P[k], m] <- O, m = 1, 2, . . . , N
    $H[$P[$k]][$m]=0;
}
$P[$k]=0;
$k--;
goto EC2_Path_Extension;

#[EC5 Advance Initial Vertex]
EC5_Advance_Initial_Vertex:
if($P[1] === N){
    goto EC6_Terminate;
}
$P[1]++;
$k=1;
$H=array(
        1=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        2=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        3=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        4=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        5=>array(1=>0,2=>0,3=>0,4=>0,5=>0)
);
goto EC2_Path_Extension;

#[EC5 Advance Initial Vertex]
EC6_Terminate:
print_r($Circ);
?>

then this is the other implementation, more independent of the graph, without goto and without array values, instead it uses array keys, the path, the graph and circuits are stored as array keys (use array values if you like, just change the required lines). The example graph start from -4 to show its independence.

<?php

$G = array(
        -4=>array(-4=>true,-3=>true,-2=>true),
        -3=>array(-4=>true,-3=>true,-2=>true),
        -2=>array(-4=>true,-3=>true,-2=>true)
);


$C = array();


EC($G,$C);
echo "<pre>";
print_r($C);
function EC($G, &$C){

    $CNST_not_closed =  false;                          // this flag indicates no closure
    $CNST_closed        = true;                         // this flag indicates closure
    // define the state where there is no closures for some node
    $tmp_first_node  =  key($G);                        // first node = first key
    $tmp_last_node  =   $tmp_first_node-1+count($G);    // last node  = last  key
    $CNST_closure_reset = array();
    for($k=$tmp_first_node; $k<=$tmp_last_node; $k++){
        $CNST_closure_reset[$k] = $CNST_not_closed;
    }
    // define the state where there is no closure for all nodes
    for($k=$tmp_first_node; $k<=$tmp_last_node; $k++){
        $H[$k] = $CNST_closure_reset;   // Key in the closure arrays represent nodes
    }
    unset($tmp_first_node);
    unset($tmp_last_node);


    # Start algorithm
    foreach($G as $init_node => $children){#[Jump to initial node set]
        #[Initial Node Set]
        $P = array();                   // declare at starup, remove the old $init_node from path on loop
        $P[$init_node]=true;            // the first key in P is always the new initial node
        $k=$init_node;                  // update the current node
                                        // On loop H[old_init_node] is not cleared cause is never checked again
        do{#Path 1,3,7,4 jump here to extend father 7
            do{#Path from 1,3,8,5 became 2,4,8,5,6 jump here to extend child 6
                $new_expansion = false;
                foreach( $G[$k] as $child => $foo ){#Consider each child of 7 or 6
                    if( $child>$init_node and isset($P[$child])===false and $H[$k][$child]===$CNST_not_closed ){
                        $P[$child]=true;    // add this child to the path
                        $k = $child;        // update the current node
                        $new_expansion=true;// set the flag for expanding the child of k
                        break(1);           // we are done, one child at a time
            }   }   }while(($new_expansion===true));// Do while a new child has been added to the path

            # If the first node is child of the last we have a circuit
            if( isset($G[$k][$init_node])===true ){
                $C[] = $P;  // Leaving this out of closure will catch loops to
            }

            # Closure
            if($k>$init_node){                  //if k>init_node then alwaya count(P)>1, so proceed to closure
                $new_expansion=true;            // $new_expansion is never true, set true to expand father of k
                unset($P[$k]);                  // remove k from path
                end($P); $k_father = key($P);   // get father of k
                $H[$k_father][$k]=$CNST_closed; // mark k as closed
                $H[$k] = $CNST_closure_reset;   // reset k closure
                $k = $k_father;                 // update k
        }   } while($new_expansion===true);//if we don't wnter the if block m has the old k$k_father_old = $k;
        // Advance Initial Vertex Context
    }//foreach initial


}//function

?>

I have analized and documented the EC but unfortunately the documentation is in Greek.

Detect HTTP or HTTPS then force HTTPS in JavaScript

Not a Javascript way to answer this but if you use CloudFlare you can write page rules that redirect the user much faster to HTTPS and it's free. Looks like this in CloudFlare's Page Rules:

enter image description here

Angularjs ng-model doesn't work inside ng-if

The ng-if directive, like other directives creates a child scope. See the script below (or this jsfiddle)

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>_x000D_
_x000D_
<script>_x000D_
    function main($scope) {_x000D_
        $scope.testa = false;_x000D_
        $scope.testb = false;_x000D_
        $scope.testc = false;_x000D_
        $scope.obj = {test: false};_x000D_
    }_x000D_
</script>_x000D_
_x000D_
<div ng-app >_x000D_
    <div ng-controller="main">_x000D_
        _x000D_
        Test A: {{testa}}<br />_x000D_
        Test B: {{testb}}<br />_x000D_
        Test C: {{testc}}<br />_x000D_
        {{obj.test}}_x000D_
        _x000D_
        <div>_x000D_
            testa (without ng-if): <input type="checkbox" ng-model="testa" />_x000D_
        </div>_x000D_
        <div ng-if="!testa">_x000D_
            testb (with ng-if): <input type="checkbox" ng-model="testb" /> {{testb}}_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            testc (with ng-if): <input type="checkbox" ng-model="testc" />_x000D_
        </div>_x000D_
        <div ng-if="!someothervar">_x000D_
            object (with ng-if): <input type="checkbox" ng-model="obj.test" />_x000D_
        </div>_x000D_
        _x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

So, your checkbox changes the testb inside of the child scope, but not the outer parent scope.

Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.

Simple PHP form: Attachment to email (code golf)

In order to add the file to the email as an attachment, it will need to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.

As for emailing, Zend Mail has a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.

With Zend_Mail, sending an email with an attachment is as simple as:

$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();

If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.

href overrides ng-click in Angular.js

You can also try this:

<div ng-init="myVar = 'www.thesoftdesign'">
        <h1>Tutorials</h1>
        <p>Go to <a ng-href="{{myVar}}">{{myVar}}</a> to learn!</p>
</div>

Inject service in app.config

Using $injector to call service methods in config

I had a similar issue and resolved it by using the $injector service as shown above. I tried injecting the service directly but ended up with a circular dependency on $http. The service displays a modal with the error and I am using ui-bootstrap modal which also has a dependency on $https.

    $httpProvider.interceptors.push(function($injector) {
    return {
        "responseError": function(response) {

            console.log("Error Response status: " + response.status);

            if (response.status === 0) {
                var myService= $injector.get("myService");
                myService.showError("An unexpected error occurred. Please refresh the page.")
            }
        }
    }

jQuery: how to change title of document during .ready()?

The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.

<script type="text/javascript">

    $(document).ready(function() {
        document.title = 'blah';
    });

</script>

Match whitespace but not newlines

Perl versions 5.10 and later support subsidiary vertical and horizontal character classes, \v and \h, as well as the generic whitespace character class \s

The cleanest solution is to use the horizontal whitespace character class \h. This will match tab and space from the ASCII set, non-breaking space from extended ASCII, or any of these Unicode characters

U+0009 CHARACTER TABULATION
U+0020 SPACE
U+00A0 NO-BREAK SPACE (not matched by \s)

U+1680 OGHAM SPACE MARK
U+2000 EN QUAD
U+2001 EM QUAD
U+2002 EN SPACE
U+2003 EM SPACE
U+2004 THREE-PER-EM SPACE
U+2005 FOUR-PER-EM SPACE
U+2006 SIX-PER-EM SPACE
U+2007 FIGURE SPACE
U+2008 PUNCTUATION SPACE
U+2009 THIN SPACE
U+200A HAIR SPACE
U+202F NARROW NO-BREAK SPACE
U+205F MEDIUM MATHEMATICAL SPACE
U+3000 IDEOGRAPHIC SPACE

The vertical space pattern \v is less useful, but matches these characters

U+000A LINE FEED
U+000B LINE TABULATION
U+000C FORM FEED
U+000D CARRIAGE RETURN
U+0085 NEXT LINE (not matched by \s)

U+2028 LINE SEPARATOR
U+2029 PARAGRAPH SEPARATOR

There are seven vertical whitespace characters which match \v and eighteen horizontal ones which match \h. \s matches twenty-three characters

All whitespace characters are either vertical or horizontal with no overlap, but they are not proper subsets because \h also matches U+00A0 NO-BREAK SPACE, and \v also matches U+0085 NEXT LINE, neither of which are matched by \s

PHP array: count or sizeof?

According to phpbench:

Is it worth the effort to calculate the length of the loop in advance?

//pre-calculate the size of array
$size = count($x); //or $size = sizeOf($x);

for ($i=0; $i<$size; $i++) {
    //...
}

//don't pre-calculate
for ($i=0; $i<count($x); $i++) { //or $i<sizeOf($x);
    //...
}

A loop with 1000 keys with 1 byte values are given.

                  +---------+----------+
                  | count() | sizeof() |
+-----------------+---------+----------+
| With precalc    |     152 |      212 |
| Without precalc |   70401 |    50644 |
+-----------------+---------+----------+  (time in µs)

So I personally prefer to use count() instead of sizeof() with pre calc.

Html.EditorFor Set Default Value

The clean way to do so is to pass a new instance of the created entity through the controller:

//GET
public ActionResult CreateNewMyEntity(string default_value)
{
    MyEntity newMyEntity = new MyEntity();
    newMyEntity._propertyValue = default_value;

    return View(newMyEntity);
}

If you want to pass the default value through ActionLink

@Html.ActionLink("Create New", "CreateNewMyEntity", new { default_value = "5" })

How do I concatenate two arrays in C#?

Try the following:

T[] r1 = new T[size1];
T[] r2 = new T[size2];

List<T> targetList = new List<T>(r1);
targetList.Concat(r2);
T[] targetArray = targetList.ToArray();

Request string without GET arguments

I had the same problem when I wanted a link back to homepage. I tried this and it worked:

<a href="<?php echo $_SESSION['PHP_SELF']; ?>?">

Note the question mark at the end. I believe that tells the machine stop thinking on behalf of the coder :)

How to change XAMPP apache server port?

If the XAMPP server is running for the moment, stop XAMPP server.

Follow these steps to change the port number.

Open the file in following location.

[XAMPP Installation Folder]/apache/conf/httpd.conf

Open the httpd.conf file and search for the String:

Listen 80

This is the port number used by XAMMP.

Then search for the string ServerName and update the Port Number which you entered earlier for Listen

Now save and re-start XAMPP server.

Best practice for localization and globalization of strings and labels

As far as I know, there's a good library called localeplanet for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)

Here's the website of library: http://www.localeplanet.com/

Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/

The common part of all those articles/libraries is that they use a i18n class and a get method (in some ways also defining an smaller function name like _) for retrieving/converting the key to the value. In my explaining the key means that string you want to translate and the value means translated string.
Then, you just need a JSON document to store key's and value's.

For example:

var _ = document.webL10n.get;
alert(_('test'));

And here the JSON:

{ test: "blah blah" }

I believe using current popular libraries solutions is a good approach.

Parsing JSON Object in Java

public class JsonParsing {

public static Properties properties = null;

public static JSONObject jsonObject = null;

static {
    properties = new Properties();
}

public static void main(String[] args) {

    try {

        JSONParser jsonParser = new JSONParser();

        File file = new File("src/main/java/read.json");

        Object object = jsonParser.parse(new FileReader(file));

        jsonObject = (JSONObject) object;

        parseJson(jsonObject);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static void getArray(Object object2) throws ParseException {

    JSONArray jsonArr = (JSONArray) object2;

    for (int k = 0; k < jsonArr.size(); k++) {

        if (jsonArr.get(k) instanceof JSONObject) {
            parseJson((JSONObject) jsonArr.get(k));
        } else {
            System.out.println(jsonArr.get(k));
        }

    }
}

public static void parseJson(JSONObject jsonObject) throws ParseException {

    Set<Object> set = jsonObject.keySet();
    Iterator<Object> iterator = set.iterator();
    while (iterator.hasNext()) {
        Object obj = iterator.next();
        if (jsonObject.get(obj) instanceof JSONArray) {
            System.out.println(obj.toString());
            getArray(jsonObject.get(obj));
        } else {
            if (jsonObject.get(obj) instanceof JSONObject) {
                parseJson((JSONObject) jsonObject.get(obj));
            } else {
                System.out.println(obj.toString() + "\t"
                        + jsonObject.get(obj));
            }
        }
    }
}}

Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Here is another way of doing it, similar to Dan Allan's answer but without the lambda function:

>>> pd.options.display.float_format = '{:.2f}'.format
>>> Series(np.random.randn(3))
0    0.41
1    0.99
2    0.10

or

>>> pd.set_option('display.float_format', '{:.2f}'.format)

How to clear input buffer in C?

unsigned char a=0;
if(kbhit()){
    a=getch();
    while(kbhit())
        getch();
}
cout<<hex<<(static_cast<unsigned int:->(a) & 0xFF)<<endl;

-or-

use maybe use _getch_nolock() ..???

Group a list of objects by an attribute

Using Java 8

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Student {

    String stud_id;
    String stud_name;
    String stud_location;

    public String getStud_id() {
        return stud_id;
    }

    public String getStud_name() {
        return stud_name;
    }

    public String getStud_location() {
        return stud_location;
    }



    Student(String sid, String sname, String slocation) {

        this.stud_id = sid;
        this.stud_name = sname;
        this.stud_location = slocation;

    }
}

class Temp
{
    public static void main(String args[])
    {

        Stream<Student> studs = 
        Stream.of(new Student("1726", "John", "New York"),
                new Student("4321", "Max", "California"),
                new Student("2234", "Max", "Los Angeles"),
                new Student("7765", "Sam", "California"));
        Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location)));
                System.out.println(map);//print by name and then location
    }

}

The result will be:

{
    Max={
        Los Angeles=[Student@214c265e], 
        California=[Student@448139f0]
    }, 
    John={
        New York=[Student@7cca494b]
    }, 
    Sam={
        California=[Student@7ba4f24f]
    }
}

How do I get the different parts of a Flask request's url?

another example:

request:

curl -XGET http://127.0.0.1:5000/alert/dingding/test?x=y

then:

request.method:              GET
request.url:                 http://127.0.0.1:5000/alert/dingding/test?x=y
request.base_url:            http://127.0.0.1:5000/alert/dingding/test
request.url_charset:         utf-8
request.url_root:            http://127.0.0.1:5000/
str(request.url_rule):       /alert/dingding/test
request.host_url:            http://127.0.0.1:5000/
request.host:                127.0.0.1:5000
request.script_root:
request.path:                /alert/dingding/test
request.full_path:           /alert/dingding/test?x=y

request.args:                ImmutableMultiDict([('x', 'y')])
request.args.get('x'):       y

How can I fetch all items from a DynamoDB table without specifying the primary key?

I figured you are using PHP but not mentioned (edited). I found this question by searching internet and since I got solution working , for those who use nodejs here is a simple solution using scan :

  var dynamoClient = new AWS.DynamoDB.DocumentClient();
  var params = {
    TableName: config.dynamoClient.tableName, // give it your table name 
    Select: "ALL_ATTRIBUTES"
  };

  dynamoClient.scan(params, function(err, data) {
    if (err) {
       console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
       console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
  });

I assume same code can be translated to PHP too using different AWS SDK

How to reference a file for variables using Bash?

For preventing naming conflicts, only import the variables that you need:

variableInFile () {
    variable="${1}"
    file="${2}"

    echo $(
        source "${file}";
        eval echo \$\{${variable}\}
    )
}

Download a file by jQuery.Ajax

I faced the same issue and successfully solved it. My use-case is this.

"Post JSON data to the server and receive an excel file. That excel file is created by the server and returned as a response to the client. Download that response as a file with custom name in browser"

$("#my-button").on("click", function(){

// Data to post
data = {
    ids: [1, 2, 3, 4, 5]
};

// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    var a;
    if (xhttp.readyState === 4 && xhttp.status === 200) {
        // Trick for making downloadable link
        a = document.createElement('a');
        a.href = window.URL.createObjectURL(xhttp.response);
        // Give filename you wish to download
        a.download = "test-file.xls";
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
    }
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(data));
});

The above snippet is just doing following

  • Posting an array as JSON to the server using XMLHttpRequest.
  • After fetching content as a blob(binary), we are creating a downloadable URL and attaching it to invisible "a" link then clicking it. I did a POST request here. Instead, you can go for a simple GET too. We cannot download the file through Ajax, must use XMLHttpRequest.

Here we need to carefully set few things on the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you use other programming languages.

# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type. You can use this technique to download any kind of files.

Understanding dispatch_async

The main reason you use the default queue over the main queue is to run tasks in the background.

For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});

Google Maps: Auto close open InfoWindows?

There is a close() function for InfoWindows. Just keep track of the last opened window, and call the close function on it when a new window is created.

Traverse a list in reverse order in Python

If you don't mind the index being negative, you can do:

>>> a = ["foo", "bar", "baz"]
>>> for i in range(len(a)):
...     print(~i, a[~i]))
-1 baz
-2 bar
-3 foo

What is the recommended project structure for spring boot rest projects?

You do not need to do anything special to start. Start with a normal java project, either maven or gradle or IDE project layout with starter dependency.

You need just one main class, as per guide here and rest...

There is no constrained package structure. Actual structure will be driven by your requirement/whim and the directory structure is laid by build-tool / IDE

You can follow same structure that you might be following for a Spring MVC application.

You can follow either way

  • A project is divided into layers:

    for example: DDD style

    • Service layer : service package contains service classes
    • DAO/REPO layer : dao package containing dao classes
    • Entity layers


    or

    any layer structure suitable to your problem for which you are writing problem.

  • A project divided into modules or functionalities or features and A module is divided into layers like above

I prefer the second, because it follows Business context. Think in terms of concepts.

What you do is dependent upon how you see the project. It is your code organization skills.

Creating a segue programmatically

You have to link your code to the UIStoryboard that you're using. Make sure you go into YourViewController in your UIStoryboard, click on the border around it, and then set its identifier field to a NSString that you call in your code.

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" 
                                                     bundle:nil];
YourViewController *yourViewController = 
 (YourViewController *)
  [storyboard instantiateViewControllerWithIdentifier:@"yourViewControllerID"];
[self.navigationController pushViewController:yourViewController animated:YES];

find -exec with multiple commands

I don't know if you can do this with find, but an alternate solution would be to create a shell script and to run this with find.

lastline.sh:

echo $(tail -1 $1),$1

Make the script executable

chmod +x lastline.sh

Use find:

find . -name "*.txt" -exec ./lastline.sh {} \;

Two divs side by side - Fluid display

Try a system like this instead:

_x000D_
_x000D_
.container {_x000D_
  width: 80%;_x000D_
  height: 200px;_x000D_
  background: aqua;_x000D_
  margin: auto;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.one {_x000D_
  width: 15%;_x000D_
  height: 200px;_x000D_
  background: red;_x000D_
  float: left;_x000D_
}_x000D_
_x000D_
.two {_x000D_
  margin-left: 15%;_x000D_
  height: 200px;_x000D_
  background: black;_x000D_
}
_x000D_
<section class="container">_x000D_
  <div class="one"></div>_x000D_
  <div class="two"></div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

You only need to float one div if you use margin-left on the other equal to the first div's width. This will work no matter what the zoom and will not have sub-pixel problems.

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

As of VS2019 - 16.8.4, I used Microsoft Edge to make this work. I hope Microsoft will fix it in Firefox.

Hive load CSV with commas in quoted fields

Add a backward slash in FIELDS TERMINATED BY '\;'

For Example:

CREATE  TABLE demo_table_1_csv
COMMENT 'my_csv_table 1'
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '\;'
LINES TERMINATED BY '\n'
STORED AS TEXTFILE
LOCATION 'your_hdfs_path'
AS 
select a.tran_uuid,a.cust_id,a.risk_flag,a.lookback_start_date,a.lookback_end_date,b.scn_name,b.alerted_risk_category,
CASE WHEN (b.activity_id is not null ) THEN 1 ELSE 0 END as Alert_Flag 
FROM scn1_rcc1_agg as a LEFT OUTER JOIN scenario_activity_alert as b ON a.tran_uuid = b.activity_id;

I have tested it, and it worked.

SQL: parse the first, middle and last name from a fullname field

Alternative simple way is to use parsename :

select full_name,
   parsename(replace(full_name, ' ', '.'), 3) as FirstName,
   parsename(replace(full_name, ' ', '.'), 2) as MiddleName,
   parsename(replace(full_name, ' ', '.'), 1) as LastName 
from YourTableName

source

How to replace substrings in windows batch file

To avoid blank line skipping just replace this:

echo !modified! >> %OUTTEXTFILE%

with this:

echo.!modified! >> %OUTTEXTFILE%

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Execute a SQL Stored Procedure and process the results

Simplest way? It works. :)

    Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
    Try
        Using connection As New SqlConnection(ConnStrg)
            connection.Open()
            Dim command As New SqlCommand(queryString, connection)
            Dim reader As SqlDataReader = command.ExecuteReader()
            Dim DTResults As New DataTable

            DTResults.Load(reader)
            MsgBox(DTResults.Rows(0)(0).ToString)

        End Using
    Catch ex As Exception
        MessageBox.Show("Error while executing .. " & ex.Message, "")
    Finally
    End Try

Less than or equal to

There is no => for if.
Use if %energy% GEQ %m2enc%

See if /? for some other details.

Reloading/refreshing Kendo Grid

You can always use $('#GridName').data('kendoGrid').dataSource.read();. You don't really need to .refresh(); after that, .dataSource.read(); will do the trick.

Now if you want to refresh your grid in a more angular way, you can do:

<div kendo-grid="vm.grid" id="grid" options="vm.gridOptions"></div>

vm.grid.dataSource.read();`

OR

vm.gridOptions.dataSource.read();

And don't forget to declare your datasource as kendo.data.DataSource type

Bootstrap Element 100% Width

Sometimes it's not possible to close the content container. The solution we are using is a bit different but prevent a overflow because of the firefox scrollbar size!

.full-width {
 margin-top: 15px;
 margin-bottom: 15px;
 position: relative;
 width: calc(100vw - 10px);
 margin-left: calc(-50vw + 5px);
 left: 50%;
}

Here is a example: https://jsfiddle.net/RubbelDeKatz/wvt9253q

Writing a Python list of lists to a csv file

If for whatever reason you wanted to do it manually (without using a module like csv,pandas,numpy etc.):

with open('myfile.csv','w') as f:
    for sublist in mylist:
        for item in sublist:
            f.write(item + ',')
        f.write('\n')

Of course, rolling your own version can be error-prone and inefficient ... that's usually why there's a module for that. But sometimes writing your own can help you understand how they work, and sometimes it's just easier.

Difference between JSON.stringify and JSON.parse

var log = { "page": window.location.href, 
        "item": "item", 
        "action": "action" };

log = JSON.stringify(log);
console.log(log);
console.log(JSON.parse(log));

//The output will be:

//For 1st Console is a String Like:

'{ "page": window.location.href,"item": "item","action": "action" }'

//For 2nd Console is a Object Like:

Object {
page   : window.location.href,  
item   : "item",
action : "action" }

MySQL SELECT DISTINCT multiple columns

This will give DISTINCT values across all the columns:

SELECT DISTINCT value
FROM (
    SELECT DISTINCT a AS value FROM my_table
    UNION SELECT DISTINCT b AS value FROM my_table
    UNION SELECT DISTINCT c AS value FROM my_table
) AS derived

How to get last month/year in java?

You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0

    Calendar c = Calendar.getInstance();
    c.set(2011, 2, 1);
    c.add(Calendar.MONTH, -1);
    int month = c.get(Calendar.MONTH) + 1;
    assertEquals(1, month);

How do I get AWS_ACCESS_KEY_ID for Amazon?

Amazon changes the admin console from time to time, hence the previous answers above are irrelevant in 2020.

The way to get the secret access key (Oct.2020) is:

  1. go to IAM console: https://console.aws.amazon.com/iam
  2. click on "Users". (see image) enter image description here
  3. go to the user you need his access key. enter image description here

As i see the answers above, I can assume my answer will become irrelevant in a year max :-)

HTH

Convert pyspark string to date format

from datetime import datetime
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DateType



# Creation of a dummy dataframe:
df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"), 
                            ("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third'])

# Setting an user define function:
# This function converts the string cell into a date:
func =  udf (lambda x: datetime.strptime(x, '%m/%d/%Y'), DateType())

df = df1.withColumn('test', func(col('first')))

df.show()

df.printSchema()

Here is the output:

+----------+----------+----------+----------+
|     first|    second|     third|      test|
+----------+----------+----------+----------+
|11/25/1991|11/24/1991|11/30/1991|1991-01-25|
|11/25/1391|11/24/1992|11/30/1992|1391-01-17|
+----------+----------+----------+----------+

root
 |-- first: string (nullable = true)
 |-- second: string (nullable = true)
 |-- third: string (nullable = true)
 |-- test: date (nullable = true)

Create a .txt file if doesn't exist, and if it does append a new line

Use the correct constructor:

else if (File.Exists(path))
{
    using(var tw = new StreamWriter(path, true))
    {
        tw.WriteLine("The next line!");
    }
}

How to get address of a pointer in c/c++?

You can use the %p formatter. It's always best practice cast your pointer void* before printing.

The C standard says:

The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

Here's how you do it:

printf("%p", (void*)p);

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

correct PHP headers for pdf file download

There are some things to be considered in your code.

First, write those headers correctly. You will never see any server sending Content-type:application/pdf, the header is Content-Type: application/pdf, spaced, with capitalized first letters etc.

The file name in Content-Disposition is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in " not '. Also, your last ' is missing.

Content-Disposition: inline implies the file should be displayed, not downloaded. Use attachment instead.

In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)

All that being said, your code should look more like this:

<?php

    $filename = './pdf/jobs/pdffile.pdf';

    $fileinfo = pathinfo($filename);
    $sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);

    header('Content-Type: application/pdf');
    header("Content-Disposition: attachment; filename=\"$sendname\"");
    header('Content-Length: ' . filesize($filename));
    readfile($filename);

Content-Length is optional but is also important if you want the user to be able to keep track of the download progress and detect if the download was interrupted. But when using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php or after ?>, not even an empty line.

Android dex gives a BufferOverflowException when building

I fixed this problem without downloading the support library or reverting the build tools to 18.1.1. I simply changed the API level to 16+ and the problem vanished. Hope it will help.

how to destroy an object in java?

Here is the code:

public static void main(String argso[]) {
int big_array[] = new int[100000];

// Do some computations with big_array and get a result. 
int result = compute(big_array);

// We no longer need big_array. It will get garbage collected when there
// are no more references to it. Since big_array is a local variable,
// it refers to the array until this method returns. But this method
// doesn't return. So we've got to explicitly get rid of the reference
// ourselves, so the garbage collector knows it can reclaim the array. 
big_array = null;

// Loop forever, handling the user's input
for(;;) handle_input(result);
}

Changing the text on a label

self.labelText = 'change the value'

The above sentence makes labelText change the value, but not change depositLabel's text.

To change depositLabel's text, use one of following setences:

self.depositLabel['text'] = 'change the value'

OR

self.depositLabel.config(text='change the value')

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

How to disable "prevent this page from creating additional dialogs"?

You should better use jquery-confirm rather than trying to remove that checkbox.

$.confirm({
    title: 'Confirm!',
    content: 'Are you sure you want to refund invoice ?',
    confirm: function(){
       //do something 
    },
    cancel: function(){
       //do something
    }
}); 

Byte array to image conversion

Most of the time when this happens it is bad data in the SQL column. This is the proper way to insert into an image column:

INSERT INTO [TableX] (ImgColumn) VALUES (
(SELECT * FROM OPENROWSET(BULK N'C:\....\Picture 010.png', SINGLE_BLOB) as tempimg))

Most people do it incorrectly this way:

INSERT INTO [TableX] (ImgColumn) VALUES ('C:\....\Picture 010.png'))

Replace tabs with spaces in vim

expand is a unix utility to convert tabs to spaces. If you do not want to set anything in vim, you can use a shell command from vim:

:!% expand -t8

How the int.TryParse actually works

Check this simple program to understand int.TryParse

 class Program
 {
    static void Main()
    {
        string str = "7788";
        int num1;
        bool n = int.TryParse(str, out num1);
        Console.WriteLine(num1);
        Console.ReadLine();
    }
}

Output is : 7788

Convert a tensor to numpy array in Tensorflow?

You can use keras backend function.

import tensorflow as tf
from tensorflow.python.keras import backend 

sess = backend.get_session()
array = sess.run(< Tensor >)

print(type(array))

<class 'numpy.ndarray'>

I hope it helps!

Parse strings to double with comma and point

try this... it works for me.

double vdouble = 0;
string sparam = "2,1";

if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
{
    if ( sparam.IndexOf( '.' ) != -1 )
    {
        sparam = sparam.Replace( '.', ',' );
    }
    else
    {
        sparam = sparam.Replace( ',', '.' );
    }

    if ( !Double.TryParse( sparam, NumberStyles.Float, CultureInfo.InvariantCulture, out vdouble ) )
    {
        vdouble = 0;
    }
}

How to kill a nodejs process in Linux?

You can use the killall command as follows:

killall node

Checking if jquery is loaded using Javascript

A quick way is to run a jQuery command in the developer console. On any browser hit F12 and try to access any of the element .

 $("#sideTab2").css("background-color", "yellow");

enter image description here

Get the current script file name

Try This

$current_file_name = $_SERVER['PHP_SELF'];
echo $current_file_name;

Launch an app on OS X with command line

You can launch apps using open:

open -a APP_YOU_WANT

This should open the application that you want.

How to check if running as root in a bash script

As @wrikken mentioned in his comments, id -u is a much better check for root.

In addition, with proper use of sudo, you could have the script check and see if it is running as root. If not, have it recall itself via sudo and then run with root permissions.

Depending on what the script does, another option may be to set up a sudo entry for whatever specialized commands the script may need.

How to select only 1 row from oracle sql?

This syntax is available in Oracle 12c:

select * from some_table fetch first 1 row only;
select * from some_table fetch first 1 rows only;
select * from some_table fetch first 10 row only;
select * from some_table fetch first 10 rows only;

^^I just wanted to demonstrate that either row or rows (plural) can be used regardless of the plurality of the desired number of rows.)

Getting Spring Application Context

Note that by storing any state from the current ApplicationContext, or the ApplicationContext itself in a static variable - for example using the singleton pattern - you will make your tests unstable and unpredictable if you're using Spring-test. This is because Spring-test caches and reuses application contexts in the same JVM. For example:

  1. Test A run and it is annotated with @ContextConfiguration({"classpath:foo.xml"}).
  2. Test B run and it is annotated with @ContextConfiguration({"classpath:foo.xml", "classpath:bar.xml})
  3. Test C run and it is annotated with @ContextConfiguration({"classpath:foo.xml"})

When Test A runs, an ApplicationContext is created, and any beans implemeting ApplicationContextAware or autowiring ApplicationContext might write to the static variable.

When Test B runs the same thing happens, and the static variable now points to Test B's ApplicationContext

When Test C runs, no beans are created as the TestContext (and herein the ApplicationContext) from Test A is resused. Now you got a static variable pointing to another ApplicationContext than the one currently holding the beans for your test.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

In my case it happened when I've tried to use my default user profile:

...
options.addArguments("user-data-dir=D:\\MyHomeDirectory\\Google\\Chrome\\User Data");
...

This triggered chrome to reuse processes already running in background, in such a way, that process started by chromedriver.exe was simply ended.

Resolution: kill all chrome.exe processes running in background.

Chart.js - Formatting Y axis

As Nevercom said the scaleLable should contain javascript so to manipulate the y value just apply the required formatting.

Note the the value is a string.

var options = {      
    scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>"
};

jsFiddle example

if you wish to set a manual y scale you can use scaleOverride

var options = {      
    scaleLabel : "<%= value + ' + two = ' + (Number(value) + 2)   %>",

    scaleOverride: true,
    scaleSteps: 10,
    scaleStepWidth: 10,
    scaleStartValue: 0

};

jsFiddle example

Disable all Database related auto configuration in Spring Boot

There's a way to exclude specific auto-configuration classes using @SpringBootApplication annotation.

@Import(MyPersistenceConfiguration.class)
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class, 
        DataSourceTransactionManagerAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class})
public class MySpringBootApplication {         
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

@SpringBootApplication#exclude attribute is an alias for @EnableAutoConfiguration#exclude attribute and I find it rather handy and useful.
I added @Import(MyPersistenceConfiguration.class) to the example to demonstrate how you can apply your custom database configuration.

constant pointer vs pointer on a constant value

Now that you know the difference between char * const a and const char * a. Many times we get confused if its a constant pointer or pointer to a constant variable.

How to read it? Follow the below simple step to identify between upper two.

Lets see how to read below declaration

char * const a;

read from Right to Left

Now start with a,

1 . adjacent to a there is const.

char * (const a);

---> So a is a constant (????).

2 . Now go along you get *

char (* (const a));

---> So a is a constant pointer to (????).

3 . Go along and there is char

(char (* (const a)));

---> a is a constant pointer to character variable

a is constant pointer to character variable. 

Isn't it easy to read?

Similarily for second declaration

const char * a;

Now again start with a,

1 . Adjacent to a there is *

---> So a is a pointer to (????)

2 . Now there is char

---> so a is pointer character,

Well that doesn't make any sense!!! So shuffle pointer and character

---> so a is character pointer to (?????)

3 . Now you have constant

---> so a is character pointer to constant variable

But though you can make out what declaration means, lets make it sound more sensible.

a is pointer to constant character variable

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I needed to use this as a cell function (like SUM or VLOOKUP) and found that it was easy to:

  1. Make sure you are in a Macro Enabled Excel File (save as xlsm).
  2. Open developer tools Alt + F11
  3. Add Microsoft VBScript Regular Expressions 5.5 as in other answers
  4. Create the following function either in workbook or in its own module:

    Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
        Dim regex As New VBScript_RegExp_55.RegExp
        Dim strInput As String
    
        strInput = myRange.Value
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
    
        REGPLACE = regex.Replace(strInput, outputPattern)
    
    End Function
    
  5. Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2") (ex: "A 243" to "A243")

How to change status bar color in Flutter?

It can be achieved in 2 steps:

  1. Set the status bar color to match to your page background using FlutterStatusbarcolor package
  2. Set the status bar buttons' (battery, wifi etc.) colors using the AppBar.brightness property

If you have an AppBar:

  @override
  Widget build(BuildContext context) {
    FlutterStatusbarcolor.setStatusBarColor(Colors.white);
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        // Other AppBar properties
      ),
      body: Container()
    );
  }

If you don't want to show the app bar in the page:

  @override
  Widget build(BuildContext context) {
    FlutterStatusbarcolor.setStatusBarColor(Colors.white);
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.light,
        elevation: 0.0,
        toolbarHeight: 0.0, // Hide the AppBar
      ),
      body: Container()
  }

Iterate through dictionary values?

You can just look for the value that corresponds with the key and then check if the input is equal to the key.

for key in PIX0:
    NUM = input("Which standard has a resolution of %s " % PIX0[key])
    if NUM == key:

Also, you will have to change the last line to fit in, so it will print the key instead of the value if you get the wrong answer.

print("I'm sorry but thats wrong. The correct answer was: %s." % key )

Also, I would recommend using str.format for string formatting instead of the % syntax.

Your full code should look like this (after adding in string formatting)

PIX0 = {"QVGA":"320x240", "VGA":"640x480", "SVGA":"800x600"}

for key in PIX0:
    NUM = input("Which standard has a resolution of {}".format(PIX0[key]))
    if NUM == key:
        print ("Nice Job!")
        count = count + 1
    else:
        print("I'm sorry but that's wrong. The correct answer was: {}.".format(key))

jQuery click events not working in iOS

There is an issue with iOS not registering click/touch events bound to elements added after DOM loads.

While PPK has this advice: http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html

I've found this the easy fix, simply add this to the css:

cursor: pointer;

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can use the code below.

<script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>

<script type="text/javascript">
    function initialize() {
        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('city2').value = place.name;
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
            //alert("This function is working!");
            //alert(place.name);
           // alert(place.address_components[0].long_name);

        });
    }
    google.maps.event.addDomListener(window, 'load', initialize); 
</script>

and this part is inside your form:

<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />  

I hope it helps.

Filter element based on .data() key/value

Sounds like more work than its worth.

1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.

2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

Subprocess changing directory

just use os.chdir
Example:

>>> import os
>>> import subprocess
>>> # Lets Just Say WE want To List The User Folders
>>> os.chdir("/home/")
>>> subprocess.run("ls")
user1 user2 user3 user4

TextFX menu is missing in Notepad++

Plugins -> Plugin Manager -> Show Plugin Manager -> Setting -> Check mark On Force HTTP instead of HTTPS for downloading Plugin List & Use development plugin list (may contain untested, unvalidated or un-installable plugins). -> OK.

How to convert rdd object to dataframe in spark

On newer versions of spark (2.0+)

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._
import org.apache.spark.sql._
import org.apache.spark.sql.types._

val spark = SparkSession
  .builder()
  .getOrCreate()
import spark.implicits._

val dfSchema = Seq("col1", "col2", "col3")
rdd.toDF(dfSchema: _*)

How to flush output of print function?

On Python 3, print can take an optional flush argument

print("Hello world!", flush=True)

On Python 2 you'll have to do

import sys
sys.stdout.flush()

after calling print. By default, print prints to sys.stdout (see the documentation for more about file objects).

Execute a shell script in current shell with sudo permission

Easiest method is to type:

sudo /bin/sh example.sh

SQL where datetime column equals today's date?

Easy way out is to use a condition like this ( use desired date > GETDATE()-1)

your sql statement "date specific" > GETDATE()-1

How to remove all of the data in a table using Django

If you want to remove all the data from all your tables, you might want to try the command python manage.py flush. This will delete all of the data in your tables, but the tables themselves will still exist.

See more here: https://docs.djangoproject.com/en/1.8/ref/django-admin/

Android Dialog: Removing title bar

create your XML which is shown in dialog here it is activity_no_title_dialog

final Dialog dialog1 = new Dialog(context);
dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog1.setContentView(R.layout.activity_no_title_dialog);
dialog1.show();

How to generate a random String in Java

The first question you need to ask is whether you really need the ID to be random. Sometime, sequential IDs are good enough.

Now, if you do need it to be random, we first note a generated sequence of numbers that contain no duplicates can not be called random. :p Now that we get that out of the way, the fastest way to do this is to have a Hashtable or HashMap containing all the IDs already generated. Whenever a new ID is generated, check it against the hashtable, re-generate if the ID already occurs. This will generally work well if the number of students is much less than the range of the IDs. If not, you're in deeper trouble as the probability of needing to regenerate an ID increases, P(generate new ID) = number_of_id_already_generated / number_of_all_possible_ids. In this case, check back the first paragraph (do you need the ID to be random?).

Hope this helps.

How do you change library location in R?

This post is just to mention an additional option. In case you need to set custom R libs in your Linux shell script you may easily do so by

export R_LIBS="~/R/lib"

See R admin guide on complete list of options.

There is an error in XML document (1, 41)

I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.

How do I convert a IPython Notebook into a Python file via commandline?

For converting all *.ipynb format files in current directory to python scripts recursively:

for i in *.ipynb **/*.ipynb; do 
    echo "$i"
    jupyter nbconvert  "$i" "$i"
done

How to give Jenkins more heap space when it´s started as a service under Windows?

From the Jenkins wiki:

The JVM launch parameters of these Windows services are controlled by an XML file jenkins.xml and jenkins-slave.xml respectively. These files can be found in $JENKINS_HOME and in the slave root directory respectively, after you've install them as Windows services.

The file format should be self-explanatory. Tweak the arguments for example to give JVM a bigger memory.

https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+as+a+Windows+service

Disposing WPF User Controls

I use the following Interactivity Behavior to provide an unloading event to WPF UserControls. You can include the behavior in the UserControls XAML. So you can have the functionality without placing the logic it in every single UserControl.

XAML declaration:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<i:Interaction.Behaviors>
    <behaviors:UserControlSupportsUnloadingEventBehavior UserControlClosing="UserControlClosingHandler" />
</i:Interaction.Behaviors>

CodeBehind handler:

private void UserControlClosingHandler(object sender, EventArgs e)
{
    // to unloading stuff here
}

Behavior Code:

/// <summary>
/// This behavior raises an event when the containing window of a <see cref="UserControl"/> is closing.
/// </summary>
public class UserControlSupportsUnloadingEventBehavior : System.Windows.Interactivity.Behavior<UserControl>
{
    protected override void OnAttached()
    {
        AssociatedObject.Loaded += UserControlLoadedHandler;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Loaded -= UserControlLoadedHandler;
        var window = Window.GetWindow(AssociatedObject);
        if (window != null)
            window.Closing -= WindowClosingHandler;
    }

    /// <summary>
    /// Registers to the containing windows Closing event when the UserControl is loaded.
    /// </summary>
    private void UserControlLoadedHandler(object sender, RoutedEventArgs e)
    {
        var window = Window.GetWindow(AssociatedObject);
        if (window == null)
            throw new Exception(
                "The UserControl {0} is not contained within a Window. The UserControlSupportsUnloadingEventBehavior cannot be used."
                    .FormatWith(AssociatedObject.GetType().Name));

        window.Closing += WindowClosingHandler;
    }

    /// <summary>
    /// The containing window is closing, raise the UserControlClosing event.
    /// </summary>
    private void WindowClosingHandler(object sender, CancelEventArgs e)
    {
        OnUserControlClosing();
    }

    /// <summary>
    /// This event will be raised when the containing window of the associated <see cref="UserControl"/> is closing.
    /// </summary>
    public event EventHandler UserControlClosing;

    protected virtual void OnUserControlClosing()
    {
        var handler = UserControlClosing;
        if (handler != null) 
            handler(this, EventArgs.Empty);
    }
}

Retrofit 2 - Dynamic URL

You can use the encoded flag on the @Path annotation:

public interface APIService {
  @GET("{fullUrl}")
  Call<Users> getUsers(@Path(value = "fullUrl", encoded = true) String fullUrl);
}
  • This will prevent the replacement of / with %2F.
  • It will not save you from ? being replaced by %3F, however, so you still can't pass in dynamic query strings.

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Options for initializing a string array

You have several options:

string[] items = { "Item1", "Item2", "Item3", "Item4" };

string[] items = new string[]
{
  "Item1", "Item2", "Item3", "Item4"
};

string[] items = new string[10];
items[0] = "Item1";
items[1] = "Item2"; // ...

ADB No Devices Found

I had the same problem with my Windows 8. The Android/SDK USB driver was installed correctly, but I forgot to install the USB driver from my phone. After installing the phone USB driver ADB works fine.

I hope this will help.

Ignore files that have already been committed to a Git repository

If you need to stop tracking a lot of ignored files, you can combine some commands:

git ls-files -i --exclude-standard | xargs -L1 git rm --cached

This would stop tracking the ignored files. If you want to actually remove files from filesystem, do not use the --cached option. You can also specify a folder to limit the search, such as:

git ls-files -i --exclude-standard -- ${FOLDER} | xargs -L1 git rm

Clip/Crop background-image with CSS

Another option is to use linear-gradient() to cover up the edges of your image. Note that this is a stupid solution, so I'm not going to put much effort into explaining it...

_x000D_
_x000D_
.flair {_x000D_
  min-width: 50px; /* width larger than sprite */_x000D_
  text-indent: 60px;_x000D_
  height: 25px;_x000D_
  display: inline-block;_x000D_
  background:_x000D_
    linear-gradient(#F00, #F00) 50px 0/999px 1px repeat-y,_x000D_
    url('https://championmains.github.io/dynamicflairs/riven/spritesheet.png') #F00;_x000D_
}_x000D_
_x000D_
.flair-classic {_x000D_
  background-position: 50px 0, 0 -25px;_x000D_
}_x000D_
_x000D_
.flair-r2 {_x000D_
  background-position: 50px 0, -50px -175px;_x000D_
}_x000D_
_x000D_
.flair-smite {_x000D_
  text-indent: 35px;_x000D_
  background-position: 25px 0, -50px -25px;_x000D_
}
_x000D_
<img src="https://championmains.github.io/dynamicflairs/riven/spritesheet.png" alt="spritesheet" /><br />_x000D_
<br />_x000D_
<span class="flair flair-classic">classic sprite</span><br /><br />_x000D_
<span class="flair flair-r2">r2 sprite</span><br /><br />_x000D_
<span class="flair flair-smite">smite sprite</span><br /><br />
_x000D_
_x000D_
_x000D_

I'm using this method on this page: https://championmains.github.io/dynamicflairs/riven/ and can't use ::before or ::after elements because I'm already using them for another hack.

how to find my angular version in my project?

There are several ways you can do that:

  1. Go into node_modules/@angular/core/package.json and check version field.
  2. If you need to use it in your code, you can import it from the @angular/core:

    import { VERSION } from '@angular/core';

  3. Inspect the rendered DOM - Angular adds the version to the main component element:

    <my-app ng-version="4.1.3">

Print <div id="printarea"></div> only?

Could you use a print stylesheet, and use CSS to arrange the content you wanted printed? Read this article for more pointers.

Java double comparison epsilon

As other commenters correctly noted, you should never use floating-point arithmetic when exact values are required, such as for monetary values. The main reason is indeed the rounding behaviour inherent in floating-points, but let's not forget that dealing with floating-points means also having to deal with infinite and NaN values.

As an illustration that your approach simply doesn't work, here is some simple test code. I simply add your EPSILON to 10.0 and look whether the result is equal to 10.0 -- which it shouldn't be, as the difference is clearly not less than EPSILON:

    double a = 10.0;
    double b = 10.0 + EPSILON;
    if (!equals(a, b)) {
        System.out.println("OK: " + a + " != " + b);
    } else {
        System.out.println("ERROR: " + a + " == " + b);
    }

Surprise:

    ERROR: 10.0 == 10.00001

The errors occurs because of the loss if significant bits on subtraction if two floating-point values have different exponents.

If you think of applying a more advanced "relative difference" approach as suggested by other commenters, you should read Bruce Dawson's excellent article Comparing Floating Point Numbers, 2012 Edition, which shows that this approach has similar shortcomings and that there is actually no fail-safe approximate floating-point comparison that works for all ranges of floating-point numbers.

To make things short: Abstain from doubles for monetary values, and use exact number representations such as BigDecimal. For the sake of efficiency, you could also use longs interpreted as "millis" (tenths of cents), as long as you reliably prevent over- and underflows. This yields a maximum representable values of 9'223'372'036'854'775.807, which should be enough for most real-world applications.

Programmatically Creating UILabel

In Swift -

var label:UILabel = UILabel(frame: CGRectMake(0, 0, 70, 20))
label.center = CGPointMake(50, 70)
label.textAlignment = NSTextAlignment.Center
label.text = "message"
label.textColor = UIColor.blackColor()
self.view.addSubview(label)

Highlight Bash/shell code in Markdown files

I found a good description at Markdown Cheatsheet:

Code blocks are part of the Markdown spec, but syntax highlighting isn't.

However, many renderers -- like GitHub's and Markdown Here -- support syntax highlighting. Which languages are supported and how those language names should be written will vary from renderer to renderer. Markdown Here supports highlighting for dozens of languages (and not-really-languages, like diffs and HTTP headers); to see the complete list, and how to write the language names, see the highlight.js demo page.

Although I could not find any official GitHub documentation about using highlight.js, I've tested lots of languages and seemed to be working

To see list of languages I used https://github.com/highlightjs/highlight.js/blob/master/SUPPORTED_LANGUAGES.md

Some shell samples:

Shell:      console, shell
Bash:       bash, sh, zsh
PowerShell: powershell, ps
DOS:        dos, bat, cmd

Example:

```bat
cd \
copy a b
ping 192.168.0.1
```

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

i don't see any for loop to initalize the variables.you can do something like this.

for(i=0;i<50;i++){
 /* Code which is necessary with a simple if statement*/

   }

How to delete large data of table in SQL without log?

Shorter syntax

select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
  DELETE TOP (10000) LargeTable 
  WHERE readTime < dateadd(MONTH,-7,GETDATE())
END

MATLAB error: Undefined function or method X for input arguments of type 'double'

You get this error when the function isn't on the MATLAB path or in pwd.

First, make sure that you are able to find the function using:

>> which divrat
c:\work\divrat\divrat.m

If it returns:

>> which divrat
'divrat' not found.

It is not on the MATLAB path or in PWD.

Second, make sure that the directory that contains divrat is on the MATLAB path using the PATH command. It may be that a directory that you thought was on the path isn't actually on the path.

Finally, make sure you aren't using a "private" directory. If divrat is in a directory named private, it will be accessible by functions in the parent directory, but not from the MATLAB command line:

>> foo

ans =

     1

>> divrat(1,1)
??? Undefined function or method 'divrat' for input arguments of type 'double'.

>> which -all divrat
c:\work\divrat\private\divrat.m  % Private to divrat

Detect whether there is an Internet connection available on Android

Also another important note. You have to set android.permission.ACCESS_NETWORK_STATE in your AndroidManifest.xml for this to work.

_ how could I have found myself the information I needed in the online documentation?

You just have to read the documentation the the classes properly enough and you'll find all answers you are looking for. Check out the documentation on ConnectivityManager. The description tells you what to do.

More elegant way of declaring multiple variables at the same time

I like the top voted answer; however, it has problems with list as shown.

  >> a, b = ([0]*5,)*2
  >> print b
  [0, 0, 0, 0, 0]
  >> a[0] = 1
  >> print b
  [1, 0, 0, 0, 0]

This is discussed in great details (here), but the gist is that a and b are the same object with a is b returning True (same for id(a) == id(b)). Therefore if you change an index, you are changing the index of both a and b, since they are linked. To solve this you can do (source)

>> a, b = ([0]*5 for i in range(2))
>> print b
[0, 0, 0, 0, 0]
>> a[0] = 1
>> print b
[0, 0, 0, 0, 0]

This can then be used as a variant of the top answer, which has the "desired" intuitive results

>> a, b, c, d, e, g, h, i = (True for i in range(9))
>> f = (False for i in range(1)) #to be pedantic

ImportError: Couldn't import Django

You need to install Django, this error is giving because django is not installed.

pip install django

Allow all remote connections, MySQL

You can disable all security by editing /etc/my.cnf:

[mysqld]
skip-grant-tables

ojdbc14.jar vs. ojdbc6.jar

Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet, OracleStatement) moved from package oracle.jdbc.driver to oracle.jdbc.

Read XLSX file in Java

I had to do this in .NET and I couldn't find any API's out there. My solution was to unzip the .xlsx, and dive right into manipulating the XML. It's not so bad once you create your helper classes and such.

There are some "gotchas" like the nodes all have to be sorted according to the way excel expects them, that I didn't find in the official docs. Excel has its own date timestamping, so you'll need to make a conversion formula.

How to see the values of a table variable at debug time in T-SQL?

DECLARE @v XML = (SELECT * FROM <tablename> FOR XML AUTO)

Insert the above statement at the point where you want to view the table's contents. The table's contents will be rendered as XML in the locals window, or you can add @v to the watches window.

enter image description here

libxml/tree.h no such file or directory

Another solution. do all the steps in header search path etc. and make sure your selected configuration in project in Project settings is the correct one. When you double click on project build settings ,you may be changing in Distribution settings, But you are trying to add header search path in "Debug" settings. So make sure you are in correct settings. or choose all settings

Oracle 11g SQL to get unique values in one column of a multi-column query

Eric Petroelje almost has it right:

SELECT * FROM TableA
WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language )

Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set)

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

How to correctly display .csv files within Excel 2013?

I know that an answer has already been accepted, but one item to check is the encoding of the CSV file. I have a Powershell script that generates CSV files. By default, it was encoding them as UCS-2 Little Endian (per Notepad++). It would open the file in a single column in Excel and I'd have to do the Text to Columns conversion to split the columns. Changing the script to encode the same output as "ASCII" (UTF-8 w/o BOM per Notepad++) allowed me to open the CSV directly with the columns split out. You can change the encoding of the CSV in Notepad++ too.

  • Menu Encoding > Convert to UTF-8 without BOM
  • Save the CSV file
  • Open in Excel, columns should be split

Design Patterns web based applications

IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.

Deep-Learning Nan loss reasons

Although most of the points are already discussed. But I would like to highlight again one more reason for NaN which is missing.

tf.estimator.DNNClassifier(
    hidden_units, feature_columns, model_dir=None, n_classes=2, weight_column=None,
    label_vocabulary=None, optimizer='Adagrad', activation_fn=tf.nn.relu,
    dropout=None, config=None, warm_start_from=None,
    loss_reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE, batch_norm=False
)

By default activation function is "Relu". It could be possible that intermediate layer's generating a negative value and "Relu" convert it into the 0. Which gradually stops training.

I observed the "LeakyRelu" able to solve such problems.

Bash script to cd to directory with spaces in pathname

When working under Linux the syntax below is right:

cd ~/My\ Code

However when you're executing your file, use the syntax below:

$ . cdcode

(just '.' and not './')

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

How can I get the current page's full URL on a Windows/IIS server?

Add:

function my_url(){
    $url = (!empty($_SERVER['HTTPS'])) ?
               "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
               "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
    echo $url;
}

Then just call the my_url function.

Can I get Unix's pthread.h to compile in Windows?

As @Ninefingers mentioned, pthreads are unix-only. Posix only, really.

That said, Microsoft does have a library that duplicates pthreads:

Microsoft Windows Services for UNIX Version 3.5

Library Download

USB Debugging option greyed out

FYI My Motorola Xyboard had an "Off" icon at the top of developer options. Once I tapped that it worked.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

How to play only the audio of a Youtube video using HTML 5?

VIDEO_ID with actual ID of your YouTube video.

<div data-video="VIDEO_ID"  
        data-autoplay="0"         
        data-loop="1"             
        id="youtube-audio">
 </div>

 <script src="https://www.youtube.com/iframe_api"></script>
 <script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>