Programs & Examples On #Swingutilities

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

Find unused npm packages in package.json

If you're using a Unix like OS (Linux, OSX, etc) then you can use a combination of find and egrep to search for require statements containing your package name:

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'name-of-package' {} \;

If you search for the entire require('name-of-package') statement, remember to use the correct type of quotation marks:

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'require("name-of-package")' {} \;

or

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni "require('name-of-package')" {} \;

The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.json and check them. You need to do this for each package yourself. Since package.json is just JSON this could be remedied by writing a small script that uses child_process.exec to run this command for each dependency. And make it a module. And add it to the NPM repo...

Multi-key dictionary in c#?

Is there anything wrong with

new Dictionary<KeyValuePair<object, object>, object>
?

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)' -- Missing /var/run/mysqld/mysqld.sock

I tried almost all the listed solutions, none worked for me until I restarted the machine and then mysql server restarted when I issued the command "service mysql restart".

Generate a random point within a circle (uniformly)

A programmer solution:

  • Create a bit map (a matrix of boolean values). It can be as large as you want.
  • Draw a circle in that bit map.
  • Create a lookup table of the circle's points.
  • Choose a random index in this lookup table.
const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;

bool matrix[MATRIX_SIZE][MATRIX_SIZE] = {0};

struct Point { int x; int y; };

Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];

void init()
{
  int numberOfOnBits = 0;

  for (int x = 0 ; x < MATRIX_SIZE ; ++x)
  {
    for (int y = 0 ; y < MATRIX_SIZE ; ++y)
    {
      if (x * x + y * y < RADIUS * RADIUS) 
      {
        matrix[x][y] = true;

        loopUpTable[numberOfOnBits].x = x;
        loopUpTable[numberOfOnBits].y = y;

        ++numberOfOnBits;

      } // if
    } // for
  } // for
} // ()

Point choose()
{
  int randomIndex = randomInt(numberOfBits);

  return loopUpTable[randomIndex];
} // ()

The bitmap is only necessary for the explanation of the logic. This is the code without the bitmap:

const int RADIUS = 64;
const int MATRIX_SIZE = RADIUS * 2;

struct Point { int x; int y; };

Point lookupTable[MATRIX_SIZE * MATRIX_SIZE];

void init()
{
  int numberOfOnBits = 0;

  for (int x = 0 ; x < MATRIX_SIZE ; ++x)
  {
    for (int y = 0 ; y < MATRIX_SIZE ; ++y)
    {
      if (x * x + y * y < RADIUS * RADIUS) 
      {
        loopUpTable[numberOfOnBits].x = x;
        loopUpTable[numberOfOnBits].y = y;

        ++numberOfOnBits;
      } // if
    } // for
  } // for
} // ()

Point choose()
{
  int randomIndex = randomInt(numberOfBits);

  return loopUpTable[randomIndex];
} // ()

How to find out the location of currently used MySQL configuration file in linux

You should find them by default in a folder like /etc/my.cnf, maybe also depends on versions. From MySQL Configuration File:

Interestingly, the scope of this file can be set according to its location. The settings will be considered global to all MySQL servers if stored in /etc/my.cnf. It will be global to a specific server if located in the directory where the MySQL databases are stored (/usr/local/mysql/data for a binary installation, or /usr/local/var for a source installation). Finally, its scope could be limited to a specific user if located in the home directory of the MySQL user (~/.my.cnf). Keep in mind that even if MySQL does locate a my.cnf file in /etc/my.cnf (global to all MySQL servers on that machine), it will continue its search for a server-specific file, and then a user-specific file. You can think of the final configuration settings as being the result of the /etc/my.cnf, mysql-data-dir/my.cnf, and ~/.my.cnf files.

There are a few switches to package managers to list specific files.

RPM Sytems:

There are switches to rpm command, -q for query, and -c or --configfiles to list config files. There is also -l or --list

The --configfiles one didn't quiet work for me, but --list did list a few .cnf files held by mysql-server

rpm -q --list mysql-server

DEB Systems:

Also with limited success: dpkg --listfiles mysql-server

Are complex expressions possible in ng-hide / ng-show?

Use a controller method if you need to run arbitrary JavaScript code, or you could define a filter that returned true or false.

I just tested (should have done that first), and something like ng-show="!a && b" worked as expected.

How do I create a comma-separated list using a SQL query?

To be agnostic, drop back and punt.

Select a.name as a_name, r.name as r_name
  from ApplicationsResource ar, Applications a, Resources r
 where a.id = ar.app_id
   and r.id = ar.resource_id
 order by r.name, a.name;

Now user your server programming language to concatenate a_names while r_name is the same as the last time.

WCF timeout exception detailed investigation

I'm not a WCF expert but I'm wondering if you aren't running into a DDOS protection on IIS. I know from experience that if you run a bunch of simultaneous connections from a single client to a server at some point the server stops responding to the calls as it suspects a DDOS attack. It will also hold the connections open until they time-out in order to slow the client down in his attacks.

Multiple connection coming from different machines/IP's should not be a problem however.

There's more info in this MSDN post:

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

Check out the MaxConcurrentSession sproperty.

Python datetime to string without microsecond component

I usually do:

import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0)  # To print now without microsecond.

# To print now:
print(now)

output:

2019-01-13 14:40:28

Laravel 5 – Remove Public from URL

Even if i do not recommend putting Laravel on the root folder there are some cases when it could not be avoided; for those cases the above methods do not work for assets so i made a quick fix changing the htaccess: after copying server.php to index.php edit the .htaccess file like so:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    ### fix file rewrites on root path ###
    #select file url
    RewriteCond %{REQUEST_URI} ^(.*)$
    #if file exists in /public/<filename>
    RewriteCond %{DOCUMENT_ROOT}/public/$1 -f
    #redirect to /public/<filename>
    RewriteRule ^(.*)$ public/$1 [L]
    ###############

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...

    #RewriteCond %{REQUEST_FILENAME} -d # comment this rules or the user will read non-public file and folders!
    #RewriteCond %{REQUEST_FILENAME} -f #
    RewriteRule ^ index.php [L]
</IfModule>

This was a quick fix i had to make so anyone is welcome to upgrade it.

What are the differences between a clustered and a non-clustered index?

A clustered index is essentially a sorted copy of the data in the indexed columns.

The main advantage of a clustered index is that when your query (seek) locates the data in the index then no additional IO is needed to retrieve that data.

The overhead of maintaining a clustered index, especially in a frequently updated table, can lead to poor performance and for that reason it may be preferable to create a non-clustered index.

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

pod deintegrate <PROJECT>.XCODEPROJ // will deintegrate cocoapods
pod install // installs the pods

Prevent scrolling of parent element when inner element scroll position reaches top/bottom?

jQuery plugin with emulate natural scrolling for Internet Explorer

  $.fn.mousewheelStopPropagation = function(options) {
    options = $.extend({
        // defaults
        wheelstop: null // Function
        }, options);

    // Compatibilities
    var isMsIE = ('Microsoft Internet Explorer' === navigator.appName);
    var docElt = document.documentElement,
        mousewheelEventName = 'mousewheel';
    if('onmousewheel' in docElt) {
        mousewheelEventName = 'mousewheel';
    } else if('onwheel' in docElt) {
        mousewheelEventName = 'wheel';
    } else if('DOMMouseScroll' in docElt) {
        mousewheelEventName = 'DOMMouseScroll';
    }
    if(!mousewheelEventName) { return this; }

    function mousewheelPrevent(event) {
        event.preventDefault();
        event.stopPropagation();
        if('function' === typeof options.wheelstop) {
            options.wheelstop(event);
        }
    }

    return this.each(function() {
        var _this = this,
            $this = $(_this);
        $this.on(mousewheelEventName, function(event) {
            var origiEvent = event.originalEvent;
            var scrollTop = _this.scrollTop,
                scrollMax = _this.scrollHeight - $this.outerHeight(),
                delta = -origiEvent.wheelDelta;
            if(isNaN(delta)) {
                delta = origiEvent.deltaY;
            }
            var scrollUp = delta < 0;
            if((scrollUp && scrollTop <= 0) || (!scrollUp && scrollTop >= scrollMax)) {
                mousewheelPrevent(event);
            } else if(isMsIE) {
                // Fix Internet Explorer and emulate natural scrolling
                var animOpt = { duration:200, easing:'linear' };
                if(scrollUp && -delta > scrollTop) {
                    $this.stop(true).animate({ scrollTop:0 }, animOpt);
                    mousewheelPrevent(event);
                } else if(!scrollUp && delta > scrollMax - scrollTop) {
                    $this.stop(true).animate({ scrollTop:scrollMax }, animOpt);
                    mousewheelPrevent(event);
                }
            }
        });
    });
};

https://github.com/basselin/jquery-mousewheel-stop-propagation/blob/master/mousewheelStopPropagation.js

Get git branch name in Jenkins Pipeline/Jenkinsfile

This is for simple Pipeline type - not multibranch. Using Jenkins 2.150.1

environment { FULL_PATH_BRANCH = "${sh(script:'git name-rev --name-only HEAD', returnStdout: true)}" GIT_BRANCH = FULL_PATH_BRANCH.substring(FULL_PATH_BRANCH.lastIndexOf('/') + 1, FULL_PATH_BRANCH.length()) }

then use it env.GIT_BRANCH

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

I found another solution for new Sonar versions where JaCoCo's binary report format (*.exec) was deprecated and the preferred format is XML (SonarJava 5.12 and higher). The solution is very simple and similar to the previous solution with *.exec reports in parent directory from this topic: https://stackoverflow.com/a/15535970/4448263.

Assuming that our project structure is:

moduleC - aggregate project's pom
  |- moduleA - some classes without tests
  |- moduleB - some classes depending from moduleA and tests for classes in both modules: moduleA and moduleB

You need following maven build plugin configuration in aggregate project's pom:

<plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.5</version>
    <executions>
        <execution>
            <id>prepare-and-report</id>
            <goals>
                <goal>prepare-agent</goal>
                <goal>report</goal>
            </goals>
        </execution>
        <execution>
            <id>report-aggregate</id>
            <phase>verify</phase>
            <goals>
                <goal>report-aggregate</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.basedir}/../target/site/jacoco-aggregate</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

Then build project with maven:

mvn clean verify

And for Sonar you should set property in administration GUI:

sonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml,../target/site/jacoco-aggregate/jacoco.xml

or using command line:

mvn sonar:sonar -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml,../target/site/jacoco-aggregate/jacoco.xml

Description

This creates binary reports for each module in default directories: target/jacoco.exec. Then creates XML reports for each module in default directories: target/site/jacoco/jacoco.xml. Then creates an aggregate report for each module in custom directory ${project.basedir}/../target/site/jacoco-aggregate/ that is relative to parent directory for each module. For moduleA and moduleB this will be common path moduleC/target/site/jacoco-aggregate/.

As moduleB depends on moduleA, moduleB will be built last and its report will be used as an aggregate coverage report in Sonar for both modules A and B.

In addition to the aggregate report, we need a normal module report as JaCoCo aggregate reports contain coverage data only for dependencies.

Together, these two types of reports providing full coverage data for Sonar.

There is one little restriction: you should be able to write a report in the project's parent directory (should have permission). Or you can set property jacoco.skip=true in root project's pom.xml (moduleC) and jacoco.skip=false in modules with classes and tests (moduleA and moduleB).

How do I search for an object by its ObjectId in the mongo console?

If you are working on the mongo shell, Please refer this : Answer from Tyler Brock

I wrote the answer if you are using mongodb using node.js

You don't need to convert the id into an ObjectId. Just use :

db.collection.findById('4ecbe7f9e8c1c9092c000027');

this collection method will automatically convert id into ObjectId.

On the other hand :

db.collection.findOne({"_id":'4ecbe7f9e8c1c9092c000027'}) doesn't work as expected. You've manually convert id into ObjectId.

That can be done like this :

let id = '58c85d1b7932a14c7a0a320d';

let o_id = new ObjectId(id);   // id as a string is passed

db.collection.findOne({"_id":o_id});

Prevent redirect after form is submitted

Instead of return false, you could try event.preventDefault(); like this:

$(function() {
$('#registerform').submit(function(event) {
    event.preventDefault();
    $(this).submit();
    }); 
});

Validate Dynamically Added Input fields

The one mahesh posted is not working because the attribute name is missing:

So instead of

<input id="list" class="required"  />

You can use:

<input id="list" name="list" class="required"  />

Modified version

Changing API level Android Studio

As well as updating the manifest, update the module's build.gradle file too (it's listed in the project pane just below the manifest - if there's no minSdkVersion key in it, you're looking at the wrong one, as there's a couple). A rebuild and things should be fine...

Converting string to Date and DateTime

to create date from any string use:
$date = DateTime::createFromFormat('d-m-y H:i', '01-01-01 01:00'); echo $date->format('Y-m-d H:i');

Html attributes for EditorFor() in ASP.NET MVC

Update MVC 5.1 now supports the below approach directly, so it works for built in editor too. http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features (It's either a case of Great mind thinking alike or they read my answer :)

End Update

If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.

@Html.EditorFor(modelItem => item.YourProperty, 
  new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px"  } })

then in your template (not required for simple types in MVC 5.1)

@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])

MySQL: How to copy rows, but change a few fields?

As long as Event_ID is Integer, do this:

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, (Event_ID + 155)
  FROM Table
WHERE Event_ID = "120"

How to find all trigger associated with a table with SQL Server?

you can open your trigger with sp_helptext yourtriggername

C# static class constructor

C# has a static constructor for this purpose.

static class YourClass
{
    static YourClass()
    {
        // perform initialization here
    }
}

From MSDN:

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced

MSDN link

.

Fatal error: Call to undefined function socket_create()

For a typical XAMPP install on windows you probably have the php_sockets.dll in your C:\xampp\php\ext directory. All you got to do is go to php.ini in the C:\xampp\php directory and change the ;extension=php_sockets.dll to extension=php_sockets.dll.

Best way to pretty print a hash

Under Rails, arrays and hashes in Ruby have built-in to_json functions. I would use JSON just because it is very readable within a web browser, e.g. Google Chrome.

That being said if you are concerned about it looking too "tech looking" you should probably write your own function that replaces the curly braces and square braces in your hashes and arrays with white-space and other characters.

Look up the gsub function for a very good way to do it. Keep playing around with different characters and different amounts of whitespace until you find something that looks appealing. http://ruby-doc.org/core-1.9.3/String.html#method-i-gsub

Vim and Ctags tips and tricks

Another iteration on the SetCscope() function above. That sets cscope pre-path to get matches without being on the dir where "cscope.out" is:

function s:FindFile(file)
    let curdir = getcwd()
    let found = curdir
    while !filereadable(a:file) && found != "/"
        cd ..
        let found = getcwd()
    endwhile
    execute "cd " . curdir
    return found
endfunction

if has('cscope')    
    let $CSCOPE_DIR=s:FindFile("cscope.out")
    let $CSCOPE_DB=$CSCOPE_DIR."/cscope.out"
    if filereadable($CSCOPE_DB)
        cscope add $CSCOPE_DB $CSCOPE_DIR
    endif

    command -nargs=0 Cscope !cscope -ub -R &
endif

Update statement using with clause

You can always do something like this:

update  mytable t
set     SomeColumn = c.ComputedValue
from    (select *, 42 as ComputedValue from mytable where id = 1) c
where t.id = c.id 

You can now also use with statement inside update

update  mytable t
set     SomeColumn = c.ComputedValue
from    (with abc as (select *, 43 as ComputedValue_new from mytable where id = 1
         select *, 42 as ComputedValue, abc.ComputedValue_new  from mytable n1
           inner join abc on n1.id=abc.id) c
where t.id = c.id 

Check if an element is present in an array

Single line code.. will return true or false

!!(arr.indexOf("val")+1)

Show/Hide Multiple Divs with Jquery

_x000D_
_x000D_
jQuery(function() {_x000D_
  jQuery('#showall').click(function() {_x000D_
    jQuery('.targetDiv').show();_x000D_
  });_x000D_
  jQuery('.showSingle').click(function() {_x000D_
    jQuery('.targetDiv').hide();_x000D_
    jQuery('#div' + $(this).attr('target')).show();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="buttons">_x000D_
  <a id="showall">All</a>_x000D_
  <a class="showSingle" target="1">Div 1</a>_x000D_
  <a class="showSingle" target="2">Div 2</a>_x000D_
  <a class="showSingle" target="3">Div 3</a>_x000D_
  <a class="showSingle" target="4">Div 4</a>_x000D_
</div>_x000D_
_x000D_
<div id="div1" class="targetDiv">Lorum Ipsum1</div>_x000D_
<div id="div2" class="targetDiv">Lorum Ipsum2</div>_x000D_
<div id="div3" class="targetDiv">Lorum Ipsum3</div>_x000D_
<div id="div4" class="targetDiv">Lorum Ipsum4</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/XwN2L/

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.

Find the paths between two given nodes?

For those who are not PYTHON expert ,the same code in C++

//@Author :Ritesh Kumar Gupta
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
vector<vector<int> >GRAPH(100);
inline void print_path(vector<int>path)
{
    cout<<"[ ";
    for(int i=0;i<path.size();++i)
    {
        cout<<path[i]<<" ";
    }
    cout<<"]"<<endl;
}
bool isadjacency_node_not_present_in_current_path(int node,vector<int>path)
{
    for(int i=0;i<path.size();++i)
    {
        if(path[i]==node)
        return false;
    }
    return true;
}
int findpaths(int source ,int target ,int totalnode,int totaledge )
{
    vector<int>path;
    path.push_back(source);
    queue<vector<int> >q;
    q.push(path);

    while(!q.empty())
    {
        path=q.front();
        q.pop();

        int last_nodeof_path=path[path.size()-1];
        if(last_nodeof_path==target)
        {
            cout<<"The Required path is:: ";
            print_path(path);
        }
        else
        {
            print_path(path);
        }

        for(int i=0;i<GRAPH[last_nodeof_path].size();++i)
        {
            if(isadjacency_node_not_present_in_current_path(GRAPH[last_nodeof_path][i],path))
            {

                vector<int>new_path(path.begin(),path.end());
                new_path.push_back(GRAPH[last_nodeof_path][i]);
                q.push(new_path);
            }
        }




    }
    return 1;
}
int main()
{
    //freopen("out.txt","w",stdout);
    int T,N,M,u,v,source,target;
    scanf("%d",&T);
    while(T--)
    {
        printf("Enter Total Nodes & Total Edges\n");
        scanf("%d%d",&N,&M);
        for(int i=1;i<=M;++i)
        {
            scanf("%d%d",&u,&v);
            GRAPH[u].push_back(v);
        }
        printf("(Source, target)\n");
        scanf("%d%d",&source,&target);
        findpaths(source,target,N,M);
    }
    //system("pause");
    return 0;
}

/*
Input::
1
6 11
1 2 
1 3
1 5
2 1
2 3
2 4
3 4
4 3
5 6
5 4
6 3
1 4

output:
[ 1 ]
[ 1 2 ]
[ 1 3 ]
[ 1 5 ]
[ 1 2 3 ]
The Required path is:: [ 1 2 4 ]
The Required path is:: [ 1 3 4 ]
[ 1 5 6 ]
The Required path is:: [ 1 5 4 ]
The Required path is:: [ 1 2 3 4 ]
[ 1 2 4 3 ]
[ 1 5 6 3 ]
[ 1 5 4 3 ]
The Required path is:: [ 1 5 6 3 4 ]


*/

How to read all files in a folder from Java?

If you want more options, you can use this function which aims to populate an arraylist of files present in a folder. Options are : recursivility and pattern to match.

public static ArrayList<File> listFilesForFolder(final File folder,
        final boolean recursivity,
        final String patternFileFilter) {

    // Inputs
    boolean filteredFile = false;

    // Ouput
    final ArrayList<File> output = new ArrayList<File> ();

    // Foreach elements
    for (final File fileEntry : folder.listFiles()) {

        // If this element is a directory, do it recursivly
        if (fileEntry.isDirectory()) {
            if (recursivity) {
                output.addAll(listFilesForFolder(fileEntry, recursivity, patternFileFilter));
            }
        }
        else {
            // If there is no pattern, the file is correct
            if (patternFileFilter.length() == 0) {
                filteredFile = true;
            }
            // Otherwise we need to filter by pattern
            else {
                filteredFile = Pattern.matches(patternFileFilter, fileEntry.getName());
            }

            // If the file has a name which match with the pattern, then add it to the list
            if (filteredFile) {
                output.add(fileEntry);
            }
        }
    }

    return output;
}

Best, Adrien

How to change the color of a SwitchCompat from AppCompat library

My working example of using style and android:theme simultaneously (API >= 21)

<android.support.v7.widget.SwitchCompat
    android:id="@+id/wan_enable_nat_switch"
    style="@style/Switch"
    app:layout_constraintBaseline_toBaselineOf="@id/wan_enable_nat_label"
    app:layout_constraintEnd_toEndOf="parent" />

<style name="Switch">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:paddingEnd">16dp</item>
    <item name="android:focusableInTouchMode">true</item>
    <item name="android:theme">@style/ThemeOverlay.MySwitchCompat</item>
</style>

<style name="ThemeOverlay.MySwitchCompat" parent="">
    <item name="colorControlActivated">@color/colorPrimaryDark</item>
    <item name="colorSwitchThumbNormal">@color/text_outline_not_active</item>
    <item name="android:colorForeground">#42221f1f</item>
</style>

How to count lines of Java code using IntelliJ IDEA?

You can to use Count Lines of Code (CLOC)

On Settings -> External Tools add a new tool

  • Name: Count Lines of Code
  • Group: Statistics
  • Program: path/to/cloc
  • Parameters: $ProjectFileDir$ or $FileParentDir$

Spring MVC UTF-8 Encoding

Depending on how you render your view, you may also need:

@Bean
public StringHttpMessageConverter stringHttpMessageConverter() {
    return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}

Should I use `import os.path` or `import os`?

Common sense works here: os is a module, and os.path is a module, too. So just import the module you want to use:

  • If you want to use functionalities in the os module, then import os.

  • If you want to use functionalities in the os.path module, then import os.path.

  • If you want to use functionalities in both modules, then import both modules:

    import os
    import os.path
    

For reference:

HTML 5 input type="number" element for floating point numbers on Chrome

Note: If you're using AngularJS, then in addition to changing the step value, you may have to set ng-model-options="{updateOn: 'blur change'}" on the html input.

The reason for this is in order to have the validators run less often, as they are preventing the user from entering a decimal point. This way, the user can type in a decimal point and the validators go into effect after the user blurs.

Incrementing a variable inside a Bash loop

Using the following 1 line command for changing many files name in linux using phrase specificity:

find -type f -name '*.jpg' | rename 's/holiday/honeymoon/'

For all files with the extension ".jpg", if they contain the string "holiday", replace it with "honeymoon". For instance, this command would rename the file "ourholiday001.jpg" to "ourhoneymoon001.jpg".

This example also illustrates how to use the find command to send a list of files (-type f) with the extension .jpg (-name '*.jpg') to rename via a pipe (|). rename then reads its file list from standard input.

Using Page_Load and Page_PreRender in ASP.Net

Page_Load happens after ViewState and PostData is sent into all of your server side controls by ASP.NET controls being created on the page. Page_Init is the event fired prior to ViewState and PostData being reinstated. Page_Load is where you typically do any page wide initilization. Page_PreRender is the last event you have a chance to handle prior to the page's state being rendered into HTML. Page_Load is the more typical event to work with.

How can I add a .npmrc file?

In MacOS Catalina 10.15.5 the .npmrc file path can be found at

/Users/<user-name>/.npmrc

Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.

You are ready to go.

Note: As mentioned by @oligofren, the command npm config ls -l will npm configurations. You will get the .npmrc file from config parameter userconfig

Set Culture in an ASP.Net MVC app

If using Subdomains, for example like "pt.mydomain.com" to set portuguese for example, using Application_AcquireRequestState won't work, because it's not called on subsequent cache requests.

To solve this, I suggest an implementation like this:

  1. Add the VaryByCustom parameter to the OutPutCache like this:

    [OutputCache(Duration = 10000, VaryByCustom = "lang")]
    public ActionResult Contact()
    {
        return View("Contact");
    }
    
  2. In global.asax.cs, get the culture from the host using a function call:

    protected void Application_AcquireRequestState(object sender, EventArgs e)
    {
        System.Threading.Thread.CurrentThread.CurrentUICulture = GetCultureFromHost();
    }
    
  3. Add the GetCultureFromHost function to global.asax.cs:

    private CultureInfo GetCultureFromHost()
    {
        CultureInfo ci = new CultureInfo("en-US"); // en-US
        string host = Request.Url.Host.ToLower();
        if (host.Equals("mydomain.com"))
        {
            ci = new CultureInfo("en-US");
        }
        else if (host.StartsWith("pt."))
        {
            ci = new CultureInfo("pt");
        }
        else if (host.StartsWith("de."))
        {
            ci = new CultureInfo("de");
        }
        else if (host.StartsWith("da."))
        {
            ci = new CultureInfo("da");
        }
    
        return ci;
    }
    
  4. And finally override the GetVaryByCustomString(...) to also use this function:

    public override string GetVaryByCustomString(HttpContext context, string value)
    {
        if (value.ToLower() == "lang")
        {
            CultureInfo ci = GetCultureFromHost();
            return ci.Name;
        }
        return base.GetVaryByCustomString(context, value);
    }
    

The function Application_AcquireRequestState is called on non-cached calls, which allows the content to get generated and cached. GetVaryByCustomString is called on cached calls to check if the content is available in cache, and in this case we examine the incoming host domain value, again, instead of relying on just the current culture info, which could have changed for the new request (because we are using subdomains).

Java 32-bit vs 64-bit compatibility

All byte code is 8-bit based. (That's why its called BYTE code) All the instructions are a multiple of 8-bits in size. We develop on 32-bit machines and run our servers with 64-bit JVM.

Could you give some detail of the problem you are facing? Then we might have a chance of helping you. Otherwise we would just be guessing what the problem is you are having.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

It may be because of the installation of Cors nuget packages.

If you facing the problem after installing and enabaling cors from nuget , then you may try reinstalling web Api.

From the package manager, run Update-Package Microsoft.AspNet.WebApi -reinstall

How to transfer paid android apps from one google account to another google account

You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.

There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).

What does git push -u mean?

This is no longer up-to-date!

Push.default is unset; its implicit value has changed in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the traditional behavior, use:

  git config --global push.default matching

To squelch this message and adopt the new behavior now, use:

  git config --global push.default simple

When push.default is set to 'matching', git will push local branches
to the remote branches that already exist with the same name.

Since Git 2.0, Git defaults to the more conservative 'simple'
behavior, which only pushes the current branch to the corresponding
remote branch that 'git pull' uses to update the current branch.

How to run eclipse in clean mode? what happens if we do so?

Using the -clean option is the way to go, as mentioned by the other answers.

Make sure that you remove it from your .ini or shortcut after you've fixed the problem. It causes Eclipse to reevaluate all of the plugins everytime it starts and can dramatically increase startup time, depending on how many Eclipse plugins you have installed.

Regular expression which matches a pattern, or is an empty string

\b matches a word boundary. I think you can use ^$ for empty string.

Trim last character from a string

Very easy and simple:

str = str.Remove( str.Length - 1 );

How to delete an SVN project from SVN repository

It's easy to believe that deleting the whole Subversion repository requires "informing" Subversion that you're going to delete the repository. But Subversion only cares about managing a repository once it's created, not whether the repository exists or not ( if that makes sense ). It goes like this: the Subversion tools and commands are not adversely affected by just deleting your repository directory with the regular operating system utilities (like rm -R). A repository directory is not the same thing as an installed program directory, where deleting a program without uninstalling it might leave behind erratic config files or other dependencies. A repository is 100% self-contained in its directory, and deleting it is harmless (besides losing your project history). You just clean the slate to create a new Subversion repository and import your next project.

How to programmatically set the Image source

{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

Git SSH error: "Connect to host: Bad file number"

The key information is written in @Sam's answer but not really salient, so let's make it clear.

"Bad file number" is not informative, it's only a sign of running git's ssh on Windows.

The line which appears even without -v switch:

ssh: connect to host (some host or IP address) port 22: Bad file number

is actually irrelevant.

If you focus on it you'll waste your time as it is not a hint about what the actual problem is, just an effect of running git's ssh on Windows. It's not even a sign that the git or ssh install or configuration is wrong. Really, ignore it.

The very same command on Linux produced instead this message for me, which gave an actual hint about the problem:

ssh: connect to host (some host or IP address) port 22: Connection timed out

Actual solution: ignore "bad file number" and get more information

Focus on lines being added with -v on command line. In my case it was:

debug1: connect to address (some host or IP address) port 22: Attempt to connect timed out without establishing a connection

My problem was a typo in the IP address, but yours may be different.

Is this question about "bad file number", or about the many reasons why a connection could time out ?

If someone can prove that "bad file number" only appears when the actual reason is "connection time out" then it makes some sense to address why connection could time out.

Until that, "bad file number" is only a generic error message and this question is fully answered by saying "ignore it and look for other error messages".

EDIT: Qwertie mentioned that the error message is indeed generic, as it can happen on "Connection refused" also. This confirms the analysis.

Please don't clutter this question with general hints and answer, they have nothing to do with the actual topic (and title) of this question which is "Git SSH error: “Connect to host: Bad file number”". If using -v you have more informative message that deserve their own question, then open another question, then you can make a link to it.

Prevent Caching in ASP.NET MVC for specific actions using an attribute

Correct attribute value for Asp.Net MVC Core to prevent browser caching (including Internet Explorer 11) is:

[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]

as described in Microsoft documentation:

Response caching in ASP.NET Core - NoStore and Location.None

Can a unit test project load the target application's app.config file?

The simplest way to do this is to add the .config file in the deployment section on your unit test.

To do so, open the .testrunconfig file from your Solution Items. In the Deployment section, add the output .config files from your project's build directory (presumably bin\Debug).

Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.

Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output .config to match the unit test's name.

HAProxy redirecting http to https (ssl)

A slight variation of user2966600's solution...

To redirect all except a single URL (In case of multiple frontend/backend):

redirect scheme https if !{ hdr(Host) -i www.mydomain.com } !{ ssl_fc }

Get operating system info

Took the following code from php manual for get_browser.

$browser = get_browser(null, true);
print_r($browser);

The $browser array has platform information included which gives you the specific Operating System in use.

Please make sure to see the "Notes" section in that page. This might be something (thismachine.info) is using if not something already pointed in other answers.

Delete many rows from a table using id in Mysql

how about using IN

DELETE FROM tableName
WHERE ID IN (1,2) -- add as many ID as you want.

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

Just to share, I've developed my own script to do it. Feel free to use it. It generates "SELECT" statements that you can then run on the tables to generate the "INSERT" statements.

select distinct 'SELECT ''INSERT INTO ' + schema_name(ta.schema_id) + '.' + so.name + ' (' + substring(o.list, 1, len(o.list)-1) + ') VALUES ('
+ substring(val.list, 1, len(val.list)-1) + ');''  FROM ' + schema_name(ta.schema_id) + '.' + so.name + ';'
from    sys.objects so
join sys.tables ta on ta.object_id=so.object_id
cross apply
(SELECT '  ' +column_name + ', '
 from information_schema.columns c
 join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
 where table_name = so.name
 order by ordinal_position
FOR XML PATH('')) o (list)
cross apply
(SELECT '''+' +case
         when data_type = 'uniqueidentifier' THEN 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
         WHEN data_type = 'timestamp' then '''''''''+CONVERT(NVARCHAR(MAX),CONVERT(BINARY(8),[' + COLUMN_NAME + ']),1)+'''''''''
         WHEN data_type = 'nvarchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'varchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'char' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         WHEN data_type = 'nchar' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE([' + COLUMN_NAME + '],'''''''','''''''''''')+'''''''' END'
         when DATA_TYPE='datetime' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
         when DATA_TYPE='datetime2' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],121)+'''''''' END '
         when DATA_TYPE='geography' and column_name<>'Shape' then 'ST_GeomFromText(''POINT('+column_name+'.Lat '+column_name+'.Long)'') '
         when DATA_TYPE='geography' and column_name='Shape' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
         when DATA_TYPE='bit' then '''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''''
         when DATA_TYPE='xml' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+REPLACE(CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + ']),'''''''','''''''''''')+'''''''' END '
         WHEN DATA_TYPE='image' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),CONVERT(VARBINARY(MAX),[' + COLUMN_NAME + ']),1)+'''''''' END '
         WHEN DATA_TYPE='varbinary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
         WHEN DATA_TYPE='binary' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '],1)+'''''''' END '
         when DATA_TYPE='time' then 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE ''''''''+CONVERT(NVARCHAR(MAX),[' + COLUMN_NAME + '])+'''''''' END '
         ELSE 'CASE WHEN [' + column_name+'] IS NULL THEN ''NULL'' ELSE CONVERT(NVARCHAR(MAX),['+column_name+']) END' end
   + '+'', '
 from information_schema.columns c
 join syscolumns co on co.name=c.COLUMN_NAME and object_name(co.id)=so.name and OBJECT_NAME(co.id)=c.TABLE_NAME and co.id=so.object_id and c.TABLE_SCHEMA=SCHEMA_NAME(so.schema_id)
 where table_name = so.name
 order by ordinal_position
FOR XML PATH('')) val (list)
where   so.type = 'U'

How to enter in a Docker container already running with a new TTY

docker exec -ti 'CONTAINER_NAME' sh

or

docker exec -ti 'CONTAINER_ID' sh

START_STICKY and START_NOT_STICKY

The documentation for START_STICKY and START_NOT_STICKY is quite straightforward.

START_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Example: Local Service Sample

START_NOT_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.

Example: ServiceStartArguments.java

Limit the length of a string with AngularJS

Here is the simple one line fix without css.

{{ myString | limitTo: 20 }}{{myString.length > 20 ? '...' : ''}}

What datatype to use when storing latitude and longitude data in SQL databases?

I would use a decimal with the proper precision for your data.

Php header location redirect not working

I had also the similar issue in godaddy hosting. But after putting ob_start(); at the beginning of the php page from where page was redirecting, it was working fine.

Please find the example of the fix:

fileName:index.php

<?php
ob_start();
...
header('Location: page1.php');
...
ob_end_flush();
?>

Python: "TypeError: __str__ returned non-string" but still prints to output?

I Had the same problem, in my case, was because i was returned a digit:

def __str__(self):
    return self.code

str is waiting for a str, not another.

now work good with:

def __str__(self):
    return self.name

where name is a STRING.

How can one develop iPhone apps in Java?

If you plan on integrating app functionality with a website, I'd highly recommend the GWT + PhoneGap model:

http://blog.daniel-kurka.de/2012/02/mgwt-and-phonegap-talk-at-webmontag-in.html http://turbomanage.wordpress.com/2010/09/24/gwt-phonegap-native-mobile-apps-quickly/

Here's my two cents from my own experience: We use the same Java POJOs for our Hibernate database, our REST API, our website, and our iPhone app. The workflow is simple and beautiful:

Database ---1---> REST API ---2---> iPhone App / Website

  • 1: Hibernate
  • 2: GSON Serialization and GWT JSON Deserialization

There is another benefit to this approach as well - any Java code that can be compiled with GWT and any JavaScript library become available for use in your iPhone app.

How to remove all white spaces in java

Replace all the spaces in the String with empty character.

String lineWithoutSpaces = line.replaceAll("\\s+","");

bower proxy configuration

There is no way to configure an exclusion to the proxy settings, but a colleague of mine had an create solution for that particular problem. He installed a local proxy server called cntlm. That server supports ntlm authentication and exclusions to the general proxy settings. A perfect match.

Finding rows that don't contain numeric data in Oracle

After doing some testing, i came up with this solution, let me know in case it helps.

Add this below 2 conditions in your query and it will find the records which don't contain numeric data

 and REGEXP_LIKE(<column_name>, '\D') -- this selects non numeric data
 and not REGEXP_LIKE(column_name,'^[-]{1}\d{1}') -- this filters out negative(-) values

What was the strangest coding standard rule that you were forced to follow?

Applying s_ to variables and methods which were deemed "safety critical" for software that was part of a control system. Couple this with the other rule about putting m_ on the front of member variables and you'd get something ridiculous like "s_m_blah()", which is darn annoying to write and not very readable in my opinion. In the end some 'safety expert' was supposed to gain insight by looking at the code and determining something from it by using those "s_" - in practice, they didn't know c++ too well so they couldn't do much other than make reports on the number of identifiers that we'd marked as 'safety critical'. Utter nonsense...

How to decompile an APK or DEX file on Android platform?

You need Three Tools to decompile an APK file.

  1. Dex2jar - Tools to work with android .dex and java .class files

  2. ApkTool - A tool for reverse engineering Android apk files

  3. JD-GUI - Java Decompiler is a tools to decompile and analyze Java 5 “byte code” and the later versions.

for more how-to-use-dextojar. Hope this will help You and all! :)

C++ multiline string literal

Since an ounce of experience is worth a ton of theory, I tried a little test program for MULTILINE:

#define MULTILINE(...) #__VA_ARGS__

const char *mstr[] =
{
    MULTILINE(1, 2, 3),       // "1, 2, 3"
    MULTILINE(1,2,3),         // "1,2,3"
    MULTILINE(1 , 2 , 3),     // "1 , 2 , 3"
    MULTILINE( 1 , 2 , 3 ),   // "1 , 2 , 3"
    MULTILINE((1,  2,  3)),   // "(1,  2,  3)"
    MULTILINE(1
              2
              3),             // "1 2 3"
    MULTILINE(1\n2\n3\n),     // "1\n2\n3\n"
    MULTILINE(1\n
              2\n
              3\n),           // "1\n 2\n 3\n"
    MULTILINE(1, "2" \3)      // "1, \"2\" \3"
};

Compile this fragment with cpp -P -std=c++11 filename to reproduce.

The trick behind #__VA_ARGS__ is that __VA_ARGS__ does not process the comma separator. So you can pass it to the stringizing operator. Leading and trailing spaces are trimmed, and spaces (including newlines) between words are compressed to a single space then. Parentheses need to be balanced. I think these shortcomings explain why the designers of C++11, despite #__VA_ARGS__, saw the need for raw string literals.

How to sum all values in a column in Jaspersoft iReport Designer?

It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.

In your case the variable can be declared like this:

<variable name="total" class="java.lang.Integer" calculation="Sum">
    <variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
  • the Calculation type is Sum;
  • the Reset type is Report;
  • the Variable expression is $F{payment}, where $F{payment} is the name of a field contains sum (Doctor Payment).

The working example.

CSV datasource:

doctor_id,payment
A1,123
B1,223
C2,234
D3,678
D1,343

The template:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="doctor_id" class="java.lang.String"/>
    <field name="payment" class="java.lang.Integer"/>
    <variable name="total" class="java.lang.Integer" calculation="Sum">
        <variableExpression><![CDATA[$F{payment}]]></variableExpression>
    </variable>
    <columnHeader>
        <band height="20" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor Payment]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <summary>
        <band height="20">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Total]]></text>
            </staticText>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true" isItalic="true"/>
                </textElement>
                <textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
            </textField>
        </band>
    </summary>
</jasperReport>

The result will be:

Generated report via iReport's preview


You can find a lot of info in the JasperReports Ultimate Guide.

Vue.js—Difference between v-model and v-bind

There are cases where you don't want to use v-model. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.

In these cases, it's not a good idea to use either watchers or computed properties.

Instead, take your v-model and split it as above answer indicates

<input
   :value="something"
   @input="something = $event.target.value"
>

In practice, if you are decoupling your logic this way, you'll probably be calling a method.

This is what it would look like in a real world scenario:

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
  <input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
  <p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
  var app = new Vue({_x000D_
    el: "#app",_x000D_
    data: function(){_x000D_
      return {_x000D_
        extendedCost: 0,_x000D_
      }_x000D_
    },_x000D_
    methods: {_x000D_
      _onInputExtendedCost: function($event) {_x000D_
        this.extendedCost = parseInt($event.target.value);_x000D_
        // Go update other inputs here_x000D_
    }_x000D_
  }_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Converting a Pandas GroupBy output from Series to DataFrame

Maybe I misunderstand the question but if you want to convert the groupby back to a dataframe you can use .to_frame(). I wanted to reset the index when I did this so I included that part as well.

example code unrelated to question

df = df['TIME'].groupby(df['Name']).min()
df = df.to_frame()
df = df.reset_index(level=['Name',"TIME"])

Second line in li starts under the bullet after CSS-reset

I second Dipaks' answer, but often just the text-indent is enough as you may/maynot be positioning the ul for better layout control.

ul li{
text-indent: -1em;
}

Error 1022 - Can't write; duplicate key in table

You are probably trying to create a foreign key in some table which exists with the same name in previously existing tables. Use the following format to name your foreign key

tablename_columnname_fk

How can I insert into a BLOB column from an insert statement in sqldeveloper?

Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:

insert into blob_fun values(1, hextoraw('453d7a34'));

453d7a34 is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.

Reliable method to get machine's MAC address in C#

WMI is the best solution if the machine you are connecting to is a windows machine, but if you are looking at a linux, mac, or other type of network adapter, then you will need to use something else. Here are some options:

  1. Use the DOS command nbtstat -a . Create a process, call this command, parse the output.
  2. First Ping the IP to make sure your NIC caches the command in it's ARP table, then use the DOS command arp -a . Parse the output of the process like in option 1.
  3. Use a dreaded unmanaged call to sendarp in the iphlpapi.dll

Heres a sample of item #3. This seems to be the best option if WMI isn't a viable solution:

using System.Runtime.InteropServices;
...
[DllImport("iphlpapi.dll", ExactSpelling = true)]
        public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
...
private string GetMacUsingARP(string IPAddr)
{
    IPAddress IP = IPAddress.Parse(IPAddr);
    byte[] macAddr = new byte[6];
    uint macAddrLen = (uint)macAddr.Length;

    if (SendARP((int)IP.Address, 0, macAddr, ref macAddrLen) != 0)
        throw new Exception("ARP command failed");

    string[] str = new string[(int)macAddrLen];
    for (int i = 0; i < macAddrLen; i++)
        str[i] = macAddr[i].ToString("x2");

    return string.Join(":", str);
}

To give credit where it is due, this is the basis for that code: http://www.pinvoke.net/default.aspx/iphlpapi.sendarp#

How do I `jsonify` a list in Flask?

You can't but you can do it anyway like this. I needed this for jQuery-File-Upload

import json
# get this object
from flask import Response

#example data:

    js = [ { "name" : filename, "size" : st.st_size , 
        "url" : url_for('show', filename=filename)} ]
#then do this
    return Response(json.dumps(js),  mimetype='application/json')

What do $? $0 $1 $2 mean in shell script?

They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

How to count the number of lines of a string in javascript

Here is the working sample fiddle

Just remove additional \r\n and "|" from your reg ex.

Using getopts to process long and short command line options

The built-in getopts can't do this. There is an external getopt(1) program that can do this, but you only get it on Linux from the util-linux package. It comes with an example script getopt-parse.bash.

There is also a getopts_long written as a shell function.

how to read certain columns from Excel using Pandas - Python

parse_cols is deprecated, use usecols instead

that is:

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")

jQuery find and replace string

You could do something this way:

$(document.body).find('*').each(function() {
    if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
        $(this).removeClass('lollypops');
        $(this).addClass('marshmellows');
    }
    var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
    var text = $(this).text(); //getting just current node text
    text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
    $(this).text(text); //setting text
    $(this).append(tmp); //re-append 'foundlings'
});

example: http://jsfiddle.net/steweb/MhQZD/

Error checking for NULL in VBScript

From your code, it looks like provider is a variant or some other variable, and not an object.

Is Nothing is for objects only, yet later you say it's a value that should either be NULL or NOT NULL, which would be handled by IsNull.

Try using:

If Not IsNull(provider) Then 
    url = url & "&provider=" & provider 
End if

Alternately, if that doesn't work, try:

If provider <> "" Then 
    url = url & "&provider=" & provider 
End if

How to convert an XML file to nice pandas dataframe?

Here is another way of converting a xml to pandas data frame. For example i have parsing xml from a string but this logic holds good from reading file as well.

import pandas as pd
import xml.etree.ElementTree as ET

xml_str = '<?xml version="1.0" encoding="utf-8"?>\n<response>\n <head>\n  <code>\n   200\n  </code>\n </head>\n <body>\n  <data id="0" name="All Categories" t="2018052600" tg="1" type="category"/>\n  <data id="13" name="RealEstate.com.au [H]" t="2018052600" tg="1" type="publication"/>\n </body>\n</response>'

etree = ET.fromstring(xml_str)
dfcols = ['id', 'name']
df = pd.DataFrame(columns=dfcols)

for i in etree.iter(tag='data'):
    df = df.append(
        pd.Series([i.get('id'), i.get('name')], index=dfcols),
        ignore_index=True)

df.head()

Windows could not start the Apache2 on Local Computer - problem

I had the same problem. I checked netstat, other processes running, firewall and changed httpd.conf, stopped antivirus, But all my efforts were in vain. :(

So finally the solution was to stop the IIS. And it worked :)

I guess IIS and apache cant work together. If anybody know any work around let us know.

Get difference between two dates in months using Java

You can try this:

Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);

I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar from a Date and just get the month's diff.

HttpServletRequest - Get query string parameters, no form data

Contrary to what cularis said there can be both in the parameter map.

The best way I see is to proxy the parameterMap and for each parameter retrieval check if queryString contains "&?<parameterName>=".

Note that parameterName needs to be URL encoded before this check can be made, as Qerub pointed out.

That saves you the parsing and still gives you only URL parameters.

What is the 'new' keyword in JavaScript?

Summary:

The new keyword is used in javascript to create a object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things:

  1. Creates a new object
  2. Sets the prototype of this object to the constructor function's prototype property
  3. Binds the this keyword to the newly created object and executes the constructor function
  4. Returns the newly created object

Example:

_x000D_
_x000D_
function Dog (age) {
  this.age = age;
}

const doggie = new Dog(12);

console.log(doggie);
console.log(Object.getPrototypeOf(doggie) === Dog.prototype) // true
_x000D_
_x000D_
_x000D_

What exactly happens:

  1. const doggie says: We need memory for declaring a variable.
  2. The assigment operator = says: We are going to initialize this variable with the expression after the =
  3. The expression is new Dog(12). The JS engine sees the new keyword, creates a new object and sets the prototype to Dog.prototype
  4. The constructor function is executed with the this value set to the new object. In this step is where the age is assigned to the new created doggie object.
  5. The newly created object is returned and assigned to the variable doggie.

Code-first vs Model/Database-first

Working with large models were very slow before the SP1, (have not tried it after the SP1, but it is said that is a snap now).

I still Design my tables first, then an in-house built tool generates the POCOs for me, so it takes the burden of doing repetitive tasks for each poco object.

when you are using source control systems, you can easily follow the history of your POCOs, it is not that easy with designer generated code.

I have a base for my POCO, which makes a lot of things quite easy.

I have views for all of my tables, each base view brings basic info for my foreign keys and my view POCOs derive from my POCO classes, which is quite usefull again.

And finally I dont like designers.

Local and global temporary tables in SQL Server

It is worth mentioning that there is also: database scoped global temporary tables(currently supported only by Azure SQL Database).

Global temporary tables for SQL Server (initiated with ## table name) are stored in tempdb and shared among all users’ sessions across the whole SQL Server instance.

Azure SQL Database supports global temporary tables that are also stored in tempdb and scoped to the database level. This means that global temporary tables are shared for all users’ sessions within the same Azure SQL Database. User sessions from other databases cannot access global temporary tables.

-- Session A creates a global temp table ##test in Azure SQL Database testdb1
-- and adds 1 row
CREATE TABLE ##test ( a int, b int);
INSERT INTO ##test values (1,1);

-- Session B connects to Azure SQL Database testdb1 
-- and can access table ##test created by session A
SELECT * FROM ##test
---Results
1,1

-- Session C connects to another database in Azure SQL Database testdb2 
-- and wants to access ##test created in testdb1.
-- This select fails due to the database scope for the global temp tables 
SELECT * FROM ##test
---Results
Msg 208, Level 16, State 0, Line 1
Invalid object name '##test'

ALTER DATABASE SCOPED CONFIGURATION

GLOBAL_TEMPORARY_TABLE_AUTODROP = { ON | OFF }

APPLIES TO: Azure SQL Database (feature is in public preview)

Allows setting the auto-drop functionality for global temporary tables. The default is ON, which means that the global temporary tables are automatically dropped when not in use by any session. When set to OFF, global temporary tables need to be explicitly dropped using a DROP TABLE statement or will be automatically dropped on server restart.

With Azure SQL Database single databases and elastic pools, this option can be set in the individual user databases of the SQL Database server. In SQL Server and Azure SQL Database managed instance, this option is set in TempDB and the setting of the individual user databases has no effect.

VB.NET: how to prevent user input in a ComboBox

Even if the question is marked answered, I would like to add some points to it.

Set the DropDownStyle property of the combobox to DropDownList works for sure.

BUT what if the drop down list is longer, the user will have to scroll it to the desired item as he has no access to keyboard.

 Private Sub cbostate_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cbostate.Validating
    If cbostate.SelectedValue Is Nothing AndAlso cbostate.Text <> String.Empty Then
        e.Cancel = True
        MsgBox("Invalid State")
    End If
End Sub

I did it like this. I wanted to restrict the user entering 'random values' instead of 'state' but keeping he should be able to type and search states.

This validating event occurs when the control loses focus. So if user enters wrong value in combobox, It will not allow user to do anything on the form, perhaps it will not even allow to change the focus from the combobox

Connecting to SQL Server with Visual Studio Express Editions

If you are using this to get a LINQ to SQL which I do and wanted for my Visual Developer, 1) get the free Visual WEB Developer, use that to connect to SQL Server instance, create your LINQ interface, then copy the generated files into your Vis-Dev project (I don't use VD because it sounds funny). Include only the *.dbml files. The Vis-Dev environment will take a second or two to recognize the supporting files. It is a little extra step but for sure better than doing it by hand or giving up on it altogether or EVEN WORSE, paying for it. Mooo ha ha haha.

release Selenium chromedriver.exe from memory

Code c#

using System.Diagnostics;

using System.Management;

        public void KillProcessAndChildren(string p_name)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher
          ("Select * From Win32_Process Where Name = '"+ p_name +"'");

        ManagementObjectCollection moc = searcher.Get();
        foreach (ManagementObject mo in moc)
        {

            try
            {
                KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
            }
            catch (ArgumentException)
            {
                break;
            }
        }

    }

and this function

        public void KillProcessAndChildren(int pid)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher
         ("Select * From Win32_Process Where ParentProcessID=" + pid);
        ManagementObjectCollection moc = searcher.Get();
        foreach (ManagementObject mo in moc)
        {

            try
            {
                KillProcessAndChildren(Convert.ToInt32(mo["ProcessID"]));
            }
            catch
            {
                break;
            }
        }

        try
        {
            Process proc = Process.GetProcessById(pid);

            proc.Kill();
        }
        catch (ArgumentException)
        {
            // Process already exited.
        }
    }

Calling

                try
            {
                 KillProcessAndChildren("chromedriver.exe");
            }
            catch
            {

            }

Changing minDate and maxDate on the fly using jQuery DatePicker

I know you are using Datepicker, but for some people who are just using HTML5 input date like me, there is an example how you can do the same: JSFiddle Link

$('#start_date').change(function(){
  var start_date = $(this).val();
  $('#end_date').prop({
    min: start_date
  });
});


/*  prop() method works since jquery 1.6, if you are using a previus version, you can use attr() method.*/

Why is Java Vector (and Stack) class considered obsolete or deprecated?

java.util.Stack inherits the synchronization overhead of java.util.Vector, which is usually not justified.

It inherits a lot more than that, though. The fact that java.util.Stack extends java.util.Vector is a mistake in object-oriented design. Purists will note that it also offers a lot of methods beyond the operations traditionally associated with a stack (namely: push, pop, peek, size). It's also possible to do search, elementAt, setElementAt, remove, and many other random-access operations. It's basically up to the user to refrain from using the non-stack operations of Stack.

For these performance and OOP design reasons, the JavaDoc for java.util.Stack recommends ArrayDeque as the natural replacement. (A deque is more than a stack, but at least it's restricted to manipulating the two ends, rather than offering random access to everything.)

Schedule automatic daily upload with FileZilla

FileZilla does not have any command line arguments (nor any other way) that allow an automatic transfer.

Some references:


Though you can use any other client that allows automation.

You have not specified, what protocol you are using. FTP or SFTP? You will definitely be able to use WinSCP, as it supports all protocols that FileZilla does (and more).

Combine WinSCP scripting capabilities with Windows Scheduler:

A typical WinSCP script for upload (with SFTP) looks like:

open sftp://user:[email protected]/ -hostkey="ssh-rsa 2048 xxxxxxxxxxx...="
put c:\mypdfs\*.pdf /home/user/
close

With FTP, just replace the sftp:// with the ftp:// and remove the -hostkey="..." switch.


Similarly for download: How to schedule an automatic FTP download on Windows?


WinSCP can even generate a script from an imported FileZilla session.

For details, see the guide to FileZilla automation.

(I'm the author of WinSCP)


Another option, if you are using SFTP, is the psftp.exe client from PuTTY suite.

Javascript reduce on array of objects

In the first step, it will work fine as the value of a will be 1 and that of b will be 2 but as 2+1 will be returned and in the next step the value of b will be the return value from step 1 i.e 3 and so b.x will be undefined...and undefined + anyNumber will be NaN and that is why you are getting that result.

Instead you can try this by giving initial value as zero i.e

arr.reduce(function(a,b){return a + b.x},0);

How to extract img src, title and alt from html using php?

I have read the many comments on this page that complain that using a dom parser is unnecessary overhead. Well, it may be more expensive than a mere regex call, but the OP has stated that there is no control over the order of the attributes in the img tags. This fact leads to unnecessary regex pattern convolution. Beyond that, using a dom parser provides the additional benefits of readability, maintainability, and dom-awareness (regex is not dom-aware).

I love regex and I answer lots of regex questions, but when dealing with valid HTML there is seldom a good reason to regex over a parser.

In the demonstration below, see how easy and clean DOMDocument handles img tag attributes in any order with a mixture of quoting (and no quoting at all). Also notice that tags without a targeted attribute are not disruptive at all -- an empty string is provided as a value.

Code: (Demo)

$test = <<<HTML
<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />
<img src='/image/pricklycactus.jpg' title='Roger the cactus' alt='a big green prickly cactus' />
<p>This is irrelevant text.</p>
<img alt="an annoying white cockatoo" title="Polly the cockatoo" src="/image/noisycockatoo.jpg">
<img title=something src=somethingelse>
HTML;

libxml_use_internal_errors(true);  // silences/forgives complaints from the parser (remove to see what is generated)
$dom = new DOMDocument();
$dom->loadHTML($test);
foreach ($dom->getElementsByTagName('img') as $i => $img) {
    echo "IMG#{$i}:\n";
    echo "\tsrc = " , $img->getAttribute('src') , "\n";
    echo "\ttitle = " , $img->getAttribute('title') , "\n";
    echo "\talt = " , $img->getAttribute('alt') , "\n";
    echo "---\n";
}

Output:

IMG#0:
    src = /image/fluffybunny.jpg
    title = Harvey the bunny
    alt = a cute little fluffy bunny
---
IMG#1:
    src = /image/pricklycactus.jpg
    title = Roger the cactus
    alt = a big green prickly cactus
---
IMG#2:
    src = /image/noisycockatoo.jpg
    title = Polly the cockatoo
    alt = an annoying white cockatoo
---
IMG#3:
    src = somethingelse
    title = something
    alt = 
---

Using this technique in professional code will leave you with a clean script, fewer hiccups to contend with, and fewer colleagues that wish you worked somewhere else.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

HTML/CSS Approach

If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper <div> and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:

JS Fiddle

HTML

<div id="wrapper">
  <div id="fixed">
    [Fixed Content]
  </div><!-- /fixed -->
  <div id="scroller">
    [Scrolling Content]
  </div><!-- /scroller -->
</div><!-- /wrapper -->

CSS

#wrapper { position: relative; }
#fixed { position: fixed; top: 0; right: 0; }
#scroller { height: 100px; overflow: auto; }

JS

//Compensate for the scrollbar (otherwise #fixed will be positioned over it).
$(function() {
  //Determine the difference in widths between
  //the wrapper and the scroller. This value is
  //the width of the scroll bar (if any).
  var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;

  //Set the right offset
  $('#fixed').css('right', offset + 'px');?
});

Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

Basic CSS - how to overlay a DIV with semi-transparent DIV on top

For a div-Element you could just set the opacity via a class to enable or disable the effect.

.mute-all {
   opacity: 0.4;
}

:: (double colon) operator in Java 8

Since many answers here explained well :: behaviour, additionally I would like to clarify that :: operator doesnt need to have exactly same signature as the referring Functional Interface if it is used for instance variables. Lets assume we need a BinaryOperator which has type of TestObject. In traditional way its implemented like this:

BinaryOperator<TestObject> binary = new BinaryOperator<TestObject>() {

        @Override
        public TestObject apply(TestObject t, TestObject u) {

            return t;
        }
    };

As you see in anonymous implementation it requires two TestObject argument and returns a TestObject object as well. To satisfy this condition by using :: operator we can start with a static method:

public class TestObject {


    public static final TestObject testStatic(TestObject t, TestObject t2){
        return t;
    }
}

and then call:

BinaryOperator<TestObject> binary = TestObject::testStatic;

Ok it compiled fine. What about if we need an instance method? Lets update TestObject with instance method:

public class TestObject {

    public final TestObject testInstance(TestObject t, TestObject t2){
        return t;
    }

    public static final TestObject testStatic(TestObject t, TestObject t2){
        return t;
    }
}

Now we can access instance as below:

TestObject testObject = new TestObject();
BinaryOperator<TestObject> binary = testObject::testInstance;

This code compiles fine, but below one not:

BinaryOperator<TestObject> binary = TestObject::testInstance;

My eclipse tell me "Cannot make a static reference to the non-static method testInstance(TestObject, TestObject) from the type TestObject ..."

Fair enough its an instance method, but if we overload testInstance as below:

public class TestObject {

    public final TestObject testInstance(TestObject t){
        return t;
    }

    public final TestObject testInstance(TestObject t, TestObject t2){
        return t;
    }

    public static final TestObject testStatic(TestObject t, TestObject t2){
        return t;
    }
}

And call:

BinaryOperator<TestObject> binary = TestObject::testInstance;

The code will just compile fine. Because it will call testInstance with single parameter instead of double one. Ok so what happened our two parameter? Lets printout and see:

public class TestObject {

    public TestObject() {
        System.out.println(this.hashCode());
    }

    public final TestObject testInstance(TestObject t){
        System.out.println("Test instance called. this.hashCode:" 
    + this.hashCode());
        System.out.println("Given parameter hashCode:" + t.hashCode());
        return t;
    }

    public final TestObject testInstance(TestObject t, TestObject t2){
        return t;
    }

    public static final TestObject testStatic(TestObject t, TestObject t2){
        return t;
    }
}

Which will output:

 1418481495  
 303563356  
 Test instance called. this.hashCode:1418481495
 Given parameter hashCode:303563356

Ok so JVM is smart enough to call param1.testInstance(param2). Can we use testInstance from another resource but not TestObject, i.e.:

public class TestUtil {

    public final TestObject testInstance(TestObject t){
        return t;
    }
}

And call:

BinaryOperator<TestObject> binary = TestUtil::testInstance;

It will just not compile and compiler will tell: "The type TestUtil does not define testInstance(TestObject, TestObject)". So compiler will look for a static reference if it is not the same type. Ok what about polymorphism? If we remove final modifiers and add our SubTestObject class:

public class SubTestObject extends TestObject {

    public final TestObject testInstance(TestObject t){
        return t;
    }

}

And call:

BinaryOperator<TestObject> binary = SubTestObject::testInstance;

It will not compile as well, compiler will still look for static reference. But below code will compile fine since it is passing is-a test:

public class TestObject {

    public SubTestObject testInstance(Object t){
        return (SubTestObject) t;
    }

}

BinaryOperator<TestObject> binary = TestObject::testInstance;

*I am just studying so I have figured out by try and see, feel free to correct me if I am wrong

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

How to test if a DataSet is empty?

This should work

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
da.Fill(ds);

if(ds.Tables.Count > 0)
{
  // enter code here
}

Python send UDP packet

Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.

#!/usr/bin/python

import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))
    fp.close()

main(sys.argv)

The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

$ python send-udp 192.168.1.2 30088

Remap values in pandas column with a dict

You can use .replace. For example:

>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
  col1 col2
0    w    a
1    1    2
2    2  NaN
>>> df.replace({"col1": di})
  col1 col2
0    w    a
1    A    2
2    B  NaN

or directly on the Series, i.e. df["col1"].replace(di, inplace=True).

How to Disable landscape mode in Android?

Add this android:screenOrientation="portrait" in your manifest file where you declare your activity like this

<activity android:name=".yourActivity"
    ....
    android:screenOrientation="portrait" />

If you want to do using java code try

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 

before you call setContentView method for your activity in onCreate().

Hope this help and easily understandable for all...

Java substring: 'string index out of range'

I"m guessing i'm getting this error because the string is trying to substring a Null value. But wouldn't the ".length() > 0" part eliminate that issue?

No, calling itemdescription.length() when itemdescription is null would not generate a StringIndexOutOfBoundsException, but rather a NullPointerException since you would essentially be trying to call a method on null.

As others have indicated, StringIndexOutOfBoundsException indicates that itemdescription is not at least 38 characters long. You probably want to handle both conditions (I assuming you want to truncate):

final String value;
if (itemdescription == null || itemdescription.length() <= 0) {
    value = "_";
} else if (itemdescription.length() <= 38) {
    value = itemdescription;
} else { 
    value = itemdescription.substring(0, 38);
}
pstmt2.setString(3, value);

Might be a good place for a utility function if you do that a lot...

REST API using POST instead of GET

In REST, each HTTP verbs has its place and meaning.

For example,

  • GET is to get the 'resource(s)' that is pointed to in the URL.

  • POST is to instructure the backend to 'create' a resource of the 'type' pointed to in the URL. You can supplement the POST operation with parameters or additional data in the body of the POST call.

In you case, since you are interested in 'getting' the info using query, thus it should be a GET operation instead of a POST operation.

This wiki may help to further clarify things.

Hope this help!

Determine the size of an InputStream

you can get the size of InputStream using getBytes(inputStream) of Utils.java check this following link

Get Bytes from Inputstream

CSS: Position loading indicator in the center of the screen

This is what I've done for Angular 4:

<style type="text/css">  
  .centered {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transform: -webkit-translate(-50%, -50%);
    transform: -moz-translate(-50%, -50%);
    transform: -ms-translate(-50%, -50%);
    color:darkred;
  }
</style>

</head>

<body>
  <app-root>
        <div class="centered">
          <h1>Loading...</h1>
        </div>
  </app-root>
</body>

Gradients on UIView and UILabels On iPhone

Mirko Froehlich's answer worked for me, except when i wanted to use custom colors. The trick is to specify UI color with Hue, saturation and brightness instead of RGB.

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = myView.bounds;
UIColor *startColour = [UIColor colorWithHue:.580555 saturation:0.31 brightness:0.90 alpha:1.0];
UIColor *endColour = [UIColor colorWithHue:.58333 saturation:0.50 brightness:0.62 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[startColour CGColor], (id)[endColour CGColor], nil];
[myView.layer insertSublayer:gradient atIndex:0];

To get the Hue, Saturation and Brightness of a color, use the in built xcode color picker and go to the HSB tab. Hue is measured in degrees in this view, so divide the value by 360 to get the value you will want to enter in code.

How to set text size in a button in html

Try this, its working in FF

body,
input,
select,
button {
 font-family: Arial,Helvetica,sans-serif;
 font-size: 14px;
}

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

Class 'DOMDocument' not found

I'm using Centos and the followings worked for me , I run this command

yum --enablerepo remi install php-xml

And restarted the Apache with this command

sudo service httpd restart

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

Scheduling recurring task in Android

I realize this is an old question and has been answered but this could help someone. In your activity

private ScheduledExecutorService scheduleTaskExecutor;

In onCreate

  scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

    //Schedule a task to run every 5 seconds (or however long you want)
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            // Do stuff here!

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // Do stuff to update UI here!
                    Toast.makeText(MainActivity.this, "Its been 5 seconds", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }, 0, 5, TimeUnit.SECONDS); // or .MINUTES, .HOURS etc.

How to save a spark DataFrame as csv on disk?

I had similar issue where i had to save the contents of the dataframe to a csv file of name which i defined. df.write("csv").save("<my-path>") was creating directory than file. So have to come up with the following solutions. Most of the code is taken from the following dataframe-to-csv with little modifications to the logic.

def saveDfToCsv(df: DataFrame, tsvOutput: String, sep: String = ",", header: Boolean = false): Unit = {
    val tmpParquetDir = "Posts.tmp.parquet"

    df.repartition(1).write.
        format("com.databricks.spark.csv").
        option("header", header.toString).
        option("delimiter", sep).
        save(tmpParquetDir)

    val dir = new File(tmpParquetDir)
    val newFileRgex = tmpParquetDir + File.separatorChar + ".part-00000.*.csv"
    val tmpTsfFile = dir.listFiles.filter(_.toPath.toString.matches(newFileRgex))(0).toString
    (new File(tmpTsvFile)).renameTo(new File(tsvOutput))

    dir.listFiles.foreach( f => f.delete )
    dir.delete
    }

Delete duplicate records from a SQL table without a primary key

Code

DELETE DUP 
FROM 
( 
    SELECT ROW_NUMBER() OVER (PARTITION BY Clientid ORDER BY Clientid ) AS Val 
    FROM ClientMaster 
) DUP 
WHERE DUP.Val > 1

Explanation

Use an inner query to construct a view over the table which includes a field based on Row_Number(), partitioned by those columns you wish to be unique.

Delete from the results of this inner query, selecting anything which does not have a row number of 1; i.e. the duplicates; not the original.

The order by clause of the row_number window function is needed for a valid syntax; you can put any column name here. If you wish to change which of the results is treated as a duplicate (e.g. keep the earliest or most recent, etc), then the column(s) used here do matter; i.e. you want to specify the order such that the record you wish to keep will come first in the result.

How to hide Android soft keyboard on EditText

Three ways based on the same simple instruction:

a). Results as easy as locate (1):

android:focusableInTouchMode="true"

among the configuration of any precedent element in the layout, example:

if your whole layout is composed of:

<ImageView>

<EditTextView>

<EditTextView>

<EditTextView>

then you can write the (1) among ImageView parameters and this will grab android's attention to the ImageView instead of the EditText.

b). In case you have another precedent element than an ImageView you may need to add (2) to (1) as:

android:focusable="true"

c). you can also simply create an empty element at the top of your view elements:

<LinearLayout
  android:focusable="true"
  android:focusableInTouchMode="true"
  android:layout_width="0px"
  android:layout_height="0px" />

This alternative until this point results as the simplest of all I've seen. Hope it helps...

How to ignore the first line of data when processing CSV data?

The documentation for the Python 3 CSV module provides this example:

with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    reader = csv.reader(csvfile, dialect)
    # ... process CSV file contents here ...

The Sniffer will try to auto-detect many things about the CSV file. You need to explicitly call its has_header() method to determine whether the file has a header line. If it does, then skip the first row when iterating the CSV rows. You can do it like this:

if sniffer.has_header():
    for header_row in reader:
        break
for data_row in reader:
    # do something with the row

Convert a number to 2 decimal places in Java

Try

DecimalFormat df = new DecimalFormat("#,##0.00");

Select rows from a data frame based on values in a vector

Similar to above, using filter from dplyr:

filter(df, fct %in% vc)

Spring @Transactional - isolation, propagation

You almost never want to use Read Uncommited since it's not really ACID compliant. Read Commmited is a good default starting place. Repeatable Read is probably only needed in reporting, rollup or aggregation scenarios. Note that many DBs, postgres included don't actually support Repeatable Read, you have to use Serializable instead. Serializable is useful for things that you know have to happen completely independently of anything else; think of it like synchronized in Java. Serializable goes hand in hand with REQUIRES_NEW propagation.

I use REQUIRES for all functions that run UPDATE or DELETE queries as well as "service" level functions. For DAO level functions that only run SELECTs, I use SUPPORTS which will participate in a TX if one is already started (i.e. being called from a service function).

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

For me, on centOS 7 I had to remove the old pip link from /bin by

rm /bin/pip2.7 
rm /bin/pip

then relink it with

sudo ln -s  /usr/local/bin/pip2.7 /bin/pip2.7

Then if

/usr/local/bin/pip2.7

Works, this should work

Sample database for exercise

This is what I am using for learning sql: employees-db

this is a sample database with an integrated test suite, used to test your applications and database servers

3rd party edit

According to launchpad.net the database has moved to github.

The database contains about 300,000 employee records with 2.8 million salary entries. The export data is 167 MB, which is not huge, but heavy enough to be non-trivial for testing.

The data was generated, and as such there are inconsistencies and subtle problems. Rather than removing them, we decided to leave the contents untouched, and use these issues as data cleaning exercises.

Convert float to string with precision & number of decimal digits specified?

Here I am providing a negative example where your want to avoid when converting floating number to strings.

float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;

You get

99463 99.463 99.462997

Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.

I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.

string ftos(float f, int nd) {
   ostringstream ostr;
   int tens = stoi("1" + string(nd, '0'));
   ostr << round(f*tens)/tens;
   return ostr.str();
}

Adding dictionaries together, Python

Please search the site before asking questions next time: how to concatenate two dictionaries to create a new one in Python?

The easiest way to do it is to simply use your example code, but using the items() member of each dictionary. So, the code would be:

dic0 = {'dic0': 0}
dic1 = {'dic1': 1}
dic2 = dict(dic0.items() + dic1.items())

I tested this in IDLE and it works fine. However, the previous question on this topic states that this method is slow and chews up memory. There are several other ways recommended there, so please see that if memory usage is important.

Split list into smaller lists (split in half)

#for python 3
    A = [0,1,2,3,4,5]
    l = len(A)/2
    B = A[:int(l)]
    C = A[int(l):]       

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

linking problem: fatal error LNK1112: module machine type 'x64' conflicts with target machine type 'X86'

I bumped into this too and found a solution.

First on how I got into this problem. I have a project which builds in x86. Then I used the Configuration Manager to add x64, and I hit this problem.

By looking at BuildLog.htm carefully, I saw both of these listed as linker options:

/MACHINE:X64  
/machine:X86 

I could not find anywhere in the Property Pages dialog where I could change this, so I opened up the .vcproj file and looked for the appropriate line and changed it to:

AdditionalOptions=" /STACK:10000000 /machine:x64 /debug"

and problem solved.

How to style the parent element when hovering a child element?

A simple jquery solution for those who don't need a pure css solution:

_x000D_
_x000D_
    $(".letter").hover(function() {_x000D_
      $(this).closest("#word").toggleClass("hovered")_x000D_
    });
_x000D_
.hovered {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
_x000D_
.letter {_x000D_
  margin: 20px;_x000D_
  background: lightgray;_x000D_
}_x000D_
_x000D_
.letter:hover {_x000D_
  background: grey;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="word">_x000D_
  <div class="letter">T</div>_x000D_
  <div class="letter">E</div>_x000D_
  <div class="letter">S</div>_x000D_
  <div class="letter">T</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use SortedMap interface in Java?

tl;dr

Use either of the Map implementations bundled with Java 6 and later that implement NavigableMap (the successor to SortedMap):

  • Use TreeMap if running single-threaded, or if the map is to be read-only across threads after first being populated.
  • Use ConcurrentSkipListMap if manipulating the map across threads.

NavigableMap

FYI, the SortedMap interface was succeeded by the NavigableMap interface.

You would only need to use SortedMap if using 3rd-party implementations that have not yet declared their support of NavigableMap. Of the maps bundled with Java, both of the implementations that implement SortedMap also implement NavigableMap.

Interface versus concrete class

s SortedMap the best answer? TreeMap?

As others mentioned, SortedMap is an interface while TreeMap is one of multiple implementations of that interface (and of the more recent NavigableMap.

Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.

NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ; 
currentAssignments.put( bob , setUpNewVendorsProject ) ; 

This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:

NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;

…and the rest of your code using that map continues to work.

Choosing implementation

There are ten implementations of Map bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.

Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap remembers original insertion order.

Table of map implementations in Java 11, comparing their features

jQuery - What are differences between $(document).ready and $(window).load?

The ready event is always execute at the only html page is loaded to the browser and the functions are executed.... But the load event is executed at the time of all the page contents are loaded to the browser for the page..... we can use $ or jQuery when we use the noconflict() method in jquery scripts...

endsWith in JavaScript

7 years old post, but I was not able to understand top few posts, because they are complex. So, I wrote my own solution:

function strEndsWith(str, endwith)
{
    var lastIndex = url.lastIndexOf(endsWith);
    var result = false;
    if (lastIndex > 0 && (lastIndex + "registerc".length) == url.length)
    {
        result = true;
    }
    return result;
}

How to count duplicate value in an array in javascript

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

var newArr = [];
testArray.forEach((item) => {
    newArr[item] = testArray.filter((el) => {
            return el === item;
    }).length;
})
console.log(newArr);

awk - concatenate two string variable and assign to a third

Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:

echo    CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT

I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.

It looks that in awk, string can be concatenated by printing variable next to each other:

echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal

How do I get length of list of lists in Java?

Just use

int listCount = data.size();

That tells you how many lists there are (assuming none are null). If you want to find out how many strings there are, you'll need to iterate:

int total = 0;
for (List<String> sublist : data) {
    // TODO: Null checking
    total += sublist.size();
}
// total is now the total number of strings

How to get the index of an element in an IEnumerable?

Stumbled across this today in a search for answers and I thought I'd add my version to the list (No pun intended). It utlises the null conditional operator of c#6.0

IEnumerable<Item> collection = GetTheCollection();

var index = collection
.Select((item,idx) => new { Item = item, Index = idx })
//or .FirstOrDefault(_ =>  _.Item.Prop == something)
.FirstOrDefault(_ => _.Item == itemToFind)?.Index ?? -1;

I've done some 'racing of the old horses' (testing) and for large collections (~100,000), worst case scenario that item you want is at the end, this is 2x faster than doing ToList().FindIndex(). If the Item you want is in the middle its ~4x faster.

For smaller collections (~10,000) it seems to be only marginally faster

Heres how I tested it https://gist.github.com/insulind/16310945247fcf13ba186a45734f254e

CSS transition fade on hover

I recommend you to use an unordered list for your image gallery.

You should use my code unless you want the image to gain instantly 50% opacity after you hover out. You will have a smoother transition.

#photos li {
    opacity: .5;
    transition: opacity .5s ease-out;
    -moz-transition: opacity .5s ease-out;
    -webkit-transition: opacity .5s ease-out;
    -o-transition: opacity .5s ease-out;
}

#photos li:hover {
    opacity: 1;
}

How to programmatically click a button in WPF?

if you want to call click event:

SomeButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

And if you want the button looks like it is pressed:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { true });

and unpressed after that:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { false });

or use the ToggleButton

get parent's view from a layout

This also works:

this.getCurrentFocus()

It gets the view so I can use it.

How do you force a CIFS connection to unmount

This works for me (Ubuntu 13.10 Desktop to an Ubuntu 14.04 Server) :-

 sudo umount -f /mnt/my_share

Mounted with

 sudo mount -t cifs -o username=me,password=mine //192.168.0.111/serv_share /mnt/my_share

where serv_share is that set up and pointed to in the smb.conf file.

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Differences between unique_ptr and shared_ptr

Both of these classes are smart pointers, which means that they automatically (in most cases) will deallocate the object that they point at when that object can no longer be referenced. The difference between the two is how many different pointers of each type can refer to a resource.

When using unique_ptr, there can be at most one unique_ptr pointing at any one resource. When that unique_ptr is destroyed, the resource is automatically reclaimed. Because there can only be one unique_ptr to any resource, any attempt to make a copy of a unique_ptr will cause a compile-time error. For example, this code is illegal:

unique_ptr<T> myPtr(new T);       // Okay
unique_ptr<T> myOtherPtr = myPtr; // Error: Can't copy unique_ptr

However, unique_ptr can be moved using the new move semantics:

unique_ptr<T> myPtr(new T);                  // Okay
unique_ptr<T> myOtherPtr = std::move(myPtr); // Okay, resource now stored in myOtherPtr

Similarly, you can do something like this:

unique_ptr<T> MyFunction() {
    unique_ptr<T> myPtr(/* ... */);

    /* ... */

    return myPtr;
}

This idiom means "I'm returning a managed resource to you. If you don't explicitly capture the return value, then the resource will be cleaned up. If you do, then you now have exclusive ownership of that resource." In this way, you can think of unique_ptr as a safer, better replacement for auto_ptr.

shared_ptr, on the other hand, allows for multiple pointers to point at a given resource. When the very last shared_ptr to a resource is destroyed, the resource will be deallocated. For example, this code is perfectly legal:

shared_ptr<T> myPtr(new T);       // Okay
shared_ptr<T> myOtherPtr = myPtr; // Sure!  Now have two pointers to the resource.

Internally, shared_ptr uses reference counting to track how many pointers refer to a resource, so you need to be careful not to introduce any reference cycles.

In short:

  1. Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed.
  2. Use shared_ptr when you want multiple pointers to the same resource.

Hope this helps!

Unable to set variables in bash script

Five problems:

  1. Don't put a space before or after the equal sign.
  2. Use "$(...)" to get the output of a command as text.
  3. [ is a command. Put a space between it and the arguments.
  4. Commands are case-sensitive. You want echo.
  5. Use double quotes around variables. rm "$folderToBeMoved"

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

Why number 9 in kill -9 command in unix?

Type the kill -l command on your shell

you will found that at 9th number [ 9) SIGKILL ], so one can use either kill -9 or kill -SIGKILL

SIGKILL is sure kill signal, It can not be dis-positioned, ignore or handle. It always work with its default behaviour, which is to kill the process.

Converting Java objects to JSON with Jackson

This might be useful:

objectMapper.writeValue(new File("c:\\employee.json"), employee);

// display to console
Object json = objectMapper.readValue(
     objectMapper.writeValueAsString(employee), Object.class);

System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
     .writeValueAsString(json));

jQuery How to Get Element's Margin and Padding?

var bordT = $('img').outerWidth() - $('img').innerWidth();
var paddT = $('img').innerWidth() - $('img').width();
var margT = $('img').outerWidth(true) - $('img').outerWidth();

var formattedBord = bordT + 'px';
var formattedPadd = paddT + 'px';
var formattedMarg = margT + 'px';

Check the jQuery API docs for information on each:

Here's the edited jsFiddle showing the result.

You can perform the same type of operations for the Height to get its margin, border, and padding.

jQuery: how to trigger anchor link's click event

 window.open($('#myanchor').attr('href'));

               $('#myanchor')[0].click();

Scala: what is the best way to append an element to an Array?

The easiest might be:

Array(1, 2, 3) :+ 4

Actually, Array can be implcitly transformed in a WrappedArray

Define static method in source-file with declaration in header-file in C++

You don't need to have static in function definition

Removing html5 required attribute with jQuery

If you want to set required to true

$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',true);
});

if you want to set required to false

$(document).ready(function(){
$('#edit-submitted-first-name').prop('required',false);
});

PHP error: Notice: Undefined index:

I think there could be no form elements by name 'month' or 'op'. Can you verify if the HTML source (of the page which results in error when submitted) indeed has html elements by he above names

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had the same issue but in this case microsoft-ace-oledb-12-0-provider was already installed on my machine and working fine for other application developed.

The difference between those application and the one with I had the problem was the Old Applications were running on "Local IIS" whereas the one with error was on "IIS Express(running from Visual Studio"). So what I did was-

  1. Right Click on Project Name.
  2. Go to Properties
  3. Go to Web Tab on the right.
  4. Under Servers select Local IIS and click on Create Virtual Directory button.
  5. Run the application again and it worked.

jQuery Get Selected Option From Dropdown

For anyone who found out that best answer don't work.

Try to use:

  $( "#aioConceptName option:selected" ).attr("value");

Works for me in recent projects so it is worth to look on it.

System.Data.OracleClient requires Oracle client software version 8.1.7

When we first moved over to Vista with Oracle 10g, we experienced this issue when we installed the Oracle client on our Vista boxes, even when we were running with admin privileges during install.

Oracle brought out a new version of the 10g client (10.2.0.3) that was Vista compatible.

I do believe that this was after 11g was released, so it is possible that there is a 'Vista compatible' version for 11g also.

Has an event handler already been added?

i agree with alf's answer,but little modification to it is,, to use,

           try
            {
                control_name.Click -= event_Click;
                main_browser.Document.Click += Document_Click;
            }
            catch(Exception exce)
            {
                main_browser.Document.Click += Document_Click;
            }

How to link an input button to a file select window?

If you want to allow the user to browse for a file, you need to have an input type="file" The closest you could get to your requirement would be to place the input type="file" on the page and hide it. Then, trigger the click event of the input when the button is clicked:

#myFileInput {
    display:none;
}

<input type="file" id="myFileInput" />
<input type="button"
       onclick="document.getElementById('myFileInput').click()" 
       value="Select a File" />

Here's a working fiddle.

Note: I would not recommend this approach. The input type="file" is the mechanism that users are accustomed to using for uploading a file.

"Port 4200 is already in use" when running the ng serve command

It says already we are running the services with port no 4200 please use another port instead of 4200. Below command is to solve the problem

ng serve --port 4300

How do I use LINQ Contains(string[]) instead of Contains(string)

This is an example of one way of writing an extension method (note: I wouldn't use this for very large arrays; another data structure would be more appropriate...):

namespace StringExtensionMethods
{
    public static class StringExtension
    {
        public static bool Contains(this string[] stringarray, string pat)
        {
            bool result = false;

            foreach (string s in stringarray)
            {
                if (s == pat)
                {
                    result = true;
                    break;
                }
            }

            return result;
        }
    }
}

C++ correct way to return pointer to array from function

Your code is OK. Note though that if you return a pointer to an array, and that array goes out of scope, you should not use that pointer anymore. Example:

int* test (void)
{
    int out[5];
    return out;
}

The above will never work, because out does not exist anymore when test() returns. The returned pointer must not be used anymore. If you do use it, you will be reading/writing to memory you shouldn't.

In your original code, the arr array goes out of scope when main() returns. Obviously that's no problem, since returning from main() also means that your program is terminating.

If you want something that will stick around and cannot go out of scope, you should allocate it with new:

int* test (void)
{
    int* out = new int[5];
    return out;
}

The returned pointer will always be valid. Remember do delete it again when you're done with it though, using delete[]:

int* array = test();
// ...
// Done with the array.
delete[] array;

Deleting it is the only way to reclaim the memory it uses.

Add Text on Image using PIL

First, you have to download a font type...for example: https://www.wfonts.com/font/microsoft-sans-serif.

After that, use this code to draw the text:

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw 
img = Image.open("filename.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(r'filepath\..\sans-serif.ttf', 16)
draw.text((0, 0),"Draw This Text",(0,0,0),font=font) # this will draw text with Blackcolor and 16 size

img.save('sample-out.jpg')

Is there a way to iterate over a dictionary?

This is iteration using block approach:

    NSDictionary *dict = @{@"key1":@1, @"key2":@2, @"key3":@3};

    [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        NSLog(@"%@->%@",key,obj);
        // Set stop to YES when you wanted to break the iteration.
    }];

With autocompletion is very fast to set, and you do not have to worry about writing iteration envelope.

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Never construct BigDecimals from floats or doubles. Construct them from ints or strings. floats and doubles loose precision.

This code works as expected (I just changed the type from double to String):

public static void main(String[] args) {
  String doubleVal = "1.745";
  String doubleVal1 = "0.745";
  BigDecimal bdTest = new BigDecimal(  doubleVal);
  BigDecimal bdTest1 = new BigDecimal(  doubleVal1 );
  bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
  bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
  System.out.println("bdTest:"+bdTest); //1.75
  System.out.println("bdTest1:"+bdTest1);//0.75, no problem
}

Why can't Python find shared objects that are in directories in sys.path?

For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.

I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev (the version I use).

Resolve conflicts using remote changes when pulling from Git remote

If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:

# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master

I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.

If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours merge strategy:

# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master

Difference between float and decimal data type

MySQL recently changed they way they store the DECIMAL type. In the past they stored the characters (or nybbles) for each digit comprising an ASCII (or nybble) representation of a number - vs - a two's complement integer, or some derivative thereof.

The current storage format for DECIMAL is a series of 1,2,3,or 4-byte integers whose bits are concatenated to create a two's complement number with an implied decimal point, defined by you, and stored in the DB schema when you declare the column and specify it's DECIMAL size and decimal point position.

By way of example, if you take a 32-bit int you can store any number from 0 - 4,294,967,295. That will only reliably cover 999,999,999, so if you threw out 2 bits and used (1<<30 -1) you'd give up nothing. Covering all 9-digit numbers with only 4 bytes is more efficient than covering 4 digits in 32 bits using 4 ASCII characters, or 8 nybble digits. (a nybble is 4-bits, allowing values 0-15, more than is needed for 0-9, but you can't eliminate that waste by going to 3 bits, because that only covers values 0-7)

The example used on the MySQL online docs uses DECIMAL(18,9) as an example. This is 9 digits ahead of and 9 digits behind the implied decimal point, which as explained above requires the following storage.

As 18 8-bit chars: 144 bits

As 18 4-bit nybbles: 72 bits

As 2 32-bit integers: 64 bits

Currently DECIMAL supports a max of 65 digits, as DECIMAL(M,D) where the largest value for M allowed is 65, and the largest value of D allowed is 30.

So as not to require chunks of 9 digits at a time, integers smaller than 32-bits are used to add digits using 1,2 and 3 byte integers. For some reason that defies logic, signed, instead of unsigned ints were used, and in so doing, 1 bit gets thrown out, resulting in the following storage capabilities. For 1,2 and 4 byte ints the lost bit doesn't matter, but for the 3-byte int it's a disaster because an entire digit is lost due to the loss of that single bit.

With an 7-bit int: 0 - 99

With a 15-bit int: 0 - 9,999

With a 23-bit int: 0 - 999,999 (0 - 9,999,999 with a 24-bit int)

1,2,3 and 4-byte integers are concatenated together to form a "bit pool" DECIMAL uses to represent the number precisely as a two's complement integer. The decimal point is NOT stored, it is implied.

This means that no ASCII to int conversions are required of the DB engine to convert the "number" into something the CPU recognizes as a number. No rounding, no conversion errors, it's a real number the CPU can manipulate.

Calculations on this arbitrarily large integer must be done in software, as there is no hardware support for this kind of number, but these libraries are very old and highly optimized, having been written 50 years ago to support IBM 370 Fortran arbitrary precision floating point data. They're still a lot slower than fixed-sized integer algebra done with CPU integer hardware, or floating point calculations done on the FPU.

In terms of storage efficiency, because the exponent of a float is attached to each and every float, specifying implicitly where the decimal point is, it is massively redundant, and therefore inefficient for DB work. In a DB you already know where the decimal point is to go up front, and every row in the table that has a value for a DECIMAL column need only look at the 1 & only specification of where that decimal point is to be placed, stored in the schema as the arguments to a DECIMAL(M,D) as the implication of the M and the D values.

The many remarks found here about which format is to be used for various kinds of applications are correct, so I won't belabor the point. I took the time to write this here because whoever is maintaining the linked MySQL online documentation doesn't understand any of the above and after rounds of increasingly frustrating attempts to explain it to them I gave up. A good indication of how poorly they understood what they were writing is the very muddled and almost indecipherable presentation of the subject matter.

As a final thought, if you have need of high-precision floating point computation, there've been tremendous advances in floating point code in the last 20 years, and hardware support for 96-bit and Quadruple Precision float are right around the corner, but there are good arbitrary precision libraries out there if manipulation of the stored value is important.

How can I convert NSDictionary to NSData and vice versa?

In Swift 2 you can do it in this way:

var dictionary: NSDictionary = ...

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary

In Swift 3:

/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)

/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)

How to open a web page automatically in full screen mode

It's better to try to simulate a webbrowser by yourself.You don't have to stick with Chrome or IE or else thing.

If you're using Python,you can try package pyQt4 which helps you to simulate a webbrowser. By doing this,there will not be any security reasons and you can set the webbrowser to show in full screen mode automatically.

Get the length of a String

In Xcode 6.1.1

extension String {    
    var length : Int { return self.utf16Count  }
}

I think that brainiacs will change this on every minor version.

How to allow user to pick the image with Swift?

I know this is question is a year old, but here's some pretty simple code (mostly from this tutorial) that's working well for me:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var imagePicker = UIImagePickerController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.imagePicker.delegate = self
}

@IBAction func loadImageButtonTapped(sender: AnyObject) {
    print("hey!")
    self.imagePicker.allowsEditing = false
    self.imagePicker.sourceType = .SavedPhotosAlbum

    self.presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imageView.contentMode = .ScaleAspectFit
        self.imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    self.imagePicker = UIImagePickerController()
    dismissViewControllerAnimated(true, completion: nil)
}

How do I block comment in Jupyter notebook?

TL;DR:

Using MacBook Pro with Spanish - ISO Keyboard.

Solution: Ctrl + -

Full story

This is an old post but reading it got me thinking about possible shortcuts.

My keyboard is a Latin Apple MacBook Pro, which is called Spanish - ISO. I tried the changing keyboard distribution to U.S. solution... this works but with this solution I have to switch keyboards every time I want to comment which... sucks.

So I tried ctrl + - and it works. The - is where the / is located in an english keyboard but doing Cmd + - only changes the Chrome's zoom so I tried Ctrl which isn't as used as Cmd in macOS.

My takeaway with this would be: if I have more shortcut problems I might try the original shortcut but using the key where the U.S. keyboard would have it.

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

Redirect Windows cmd stdout and stderr to a single file

You want:

dir > a.txt 2>&1

The syntax 2>&1 will redirect 2 (stderr) to 1 (stdout). You can also hide messages by redirecting to NUL, more explanation and examples on MSDN.

Dialog with transparent background in Android

You can use the:

setBackgroundDrawable(null);

method.And following is the doc:

  /**
    * Set the background to a given Drawable, or remove the background. If the
    * background has padding, this View's padding is set to the background's
    * padding. However, when a background is removed, this View's padding isn't
    * touched. If setting the padding is desired, please use
    * {@link #setPadding(int, int, int, int)}.
    *
    * @param d The Drawable to use as the background, or null to remove the
    *        background
    */

Create iOS Home Screen Shortcuts on Chrome for iOS

Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.

javascript:location.href=%22googlechrome%22+location.href.substring(4);

Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.

Source

Works for me.

How to select a node of treeview programmatically in c#?

treeViewMain.SelectedNode = treeViewMain.Nodes.Find(searchNode, true)[0];

where searchNode is the name of the node. I'm personally using a combo "Node + Panel" where Node name is Node + and the same tag is also set on panel of choice. With this command + scan of panels by tag i'm usually able to work a treeview+panel full menu set.

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

com.android.build.transform.api.TransformException

I changed a couple of pngs and the build number in the gradle and now I get this. No amount of cleaning and restarting helped. Disabling Instant Run fixed it for me. YMMV

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

I struggled for days. I tried all the different configurations suggested in this thread. None of them works. Finally, I find only the important configuration is the prepare-agent goal. But you have to put it in the right phase. I saw so many examples put it in the "pre-integration-test", that's a misleading, as it will only be executed after unit test. So the unit test won't be instrumented.

The right config should just use the default phase, (don't specify the phase explicitly). And usually, you don't need to mass around maven-surefire-plugin.

  <plugin>
    <groupId>org.jacoco</groupId>
    <artifactId>jacoco-maven-plugin</artifactId>
    <version>0.8.4</version>
    <executions>
      <execution>
        <id>default-prepare-agent</id>
        <goals>
          <goal>prepare-agent</goal>
        </goals>
      </execution>
      <execution>
        <id>jacoco-site</id>
        <phase>post-integration-test</phase>
        <goals>
          <goal>report</goal>
        </goals>
      </execution>
    </executions>
  </plugin>

Calculating the difference between two Java date instances

public static String getDifferenceBtwTime(Date dateTime) {

    long timeDifferenceMilliseconds = new Date().getTime() - dateTime.getTime();
    long diffSeconds = timeDifferenceMilliseconds / 1000;
    long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
    long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
    long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
    long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
    long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
    long diffYears = (long)(timeDifferenceMilliseconds / (1000 * 60 * 60 * 24 * 365));

    if (diffSeconds < 1) {
        return "one sec ago";
    } else if (diffMinutes < 1) {
        return diffSeconds + " seconds ago";
    } else if (diffHours < 1) {
        return diffMinutes + " minutes ago";
    } else if (diffDays < 1) {
        return diffHours + " hours ago";
    } else if (diffWeeks < 1) {
        return diffDays + " days ago";
    } else if (diffMonths < 1) {
        return diffWeeks + " weeks ago";
    } else if (diffYears < 12) {
        return diffMonths + " months ago";
    } else {
        return diffYears + " years ago";
    }
}   

How do I parse a HTML page with Node.js

Htmlparser2 by FB55 seems to be a good alternative.

Parsing JSON objects for HTML table

another nice recursive way to generate HTML from a nested JSON object (currently not supporting arrays):

// generate HTML code for an object
var make_table = function(json, css_class='tbl_calss', tabs=1){
    // helper to tabulate the HTML tags. will return '\t\t\t' for num_of_tabs=3
    var tab = function(num_of_tabs){
        var s = '';
        for (var i=0; i<num_of_tabs; i++){
            s += '\t';
        }
        //console.log('tabbing done. tabs=' + tabs)
        return s;
    }
    // recursive function that returns a fixed block of <td>......</td>.
    var generate_td = function(json){ 
        if (!(typeof(json) == 'object')){
            // for primitive data - direct wrap in <td>...</td>
            return tab(tabs) + '<td>'+json+'</td>\n';
        }else{
            // recursive call for objects to open a new sub-table inside the <td>...</td>
            // (object[key] may be also an object)
            var s = tab(++tabs)+'<td>\n';
            s +=        tab(++tabs)+'<table class="'+css_class+'">\n';
            for (var k in json){
                s +=        tab(++tabs)+'<tr>\n';
                s +=          tab(++tabs)+'<td>' + k + '</td>\n';
                s +=                      generate_td(json[k]);
                s +=        tab(--tabs)+'</tr>' + tab(--tabs) + '\n';


            }
            // close the <td>...</td> external block
            s +=        tab(tabs--)+'</table>\n';
            s +=    tab(tabs--)+'</td>\n';
            return s;
        }
    }
    // construct the complete HTML code
    var html_code = '' ;
    html_code += tab(++tabs)+'<table class="'+css_class+'">\n';
    html_code +=   tab(++tabs)+'<tr>\n';
    html_code +=     generate_td(json);
    html_code +=   tab(tabs--)+'</tr>\n';
    html_code += tab(tabs--)+'</table>\n';
    return html_code;
}

Difference between <context:annotation-config> and <context:component-scan>

The <context:annotation-config> tag tells Spring to scan the codebase for automatically resolving dependency requirements of the classes containing @Autowired annotation.

Spring 2.5 also adds support for JSR-250 annotations such as @Resource, @PostConstruct, and @PreDestroy.Use of these annotations also requires that certain BeanPostProcessors be registered within the Spring container. As always, these can be registered as individual bean definitions, but they can also be implicitly registered by including <context:annotation-config> tag in spring configuration.

Taken from Spring documentation of Annotation Based Configuration


Spring provides the capability of automatically detecting 'stereotyped' classes and registering corresponding BeanDefinitions with the ApplicationContext.

According to javadoc of org.springframework.stereotype:

Stereotypes are Annotations denoting the roles of types or methods in the overall architecture (at a conceptual, rather than implementation, level). Example: @Controller @Service @Repository etc. These are intended for use by tools and aspects (making an ideal target for pointcuts).

To autodetect such 'stereotype' classes, <context:component-scan> tag is required.

The <context:component-scan> tag also tells Spring to scan the code for injectable beans under the package (and all its subpackages) specified.

How can I show the table structure in SQL Server query?

To print a schema, I use jade and do an export to a file of the database then bring it into word to format and print

Pandas dataframe groupby plot

Similar to Julien's answer above, I had success with the following:

fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
    ax.plot(grp['Date'], grp['adj_close'], label=key)

ax.legend()
plt.show()

This solution might be more relevant if you want more control in matlab.

Solution inspired by: https://stackoverflow.com/a/52526454/10521959

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

To summarise solutions from a couple of questions/answers:

If you want to get the current scroll offset use:

$(document).scrollTop()

To set the scroll offset use:

$('html,body').scrollTop(x)

To animate the scroll use use:

$('html,body').animate({scrollTop: x});

Iterate through every file in one directory

Dir.foreach("/home/mydir") do |fname|
  puts fname
end

Can't bind to 'ngModel' since it isn't a known property of 'input'

If someone is still getting errors after applying the accepted solution, it could be possibly because you have a separate module file for the component in which you want to use the ngModel property in input tag. In that case, apply the accepted solution in the component's module.ts file as well.

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

I've simply added

jQuery.browser = {
    msie: false,
    version: 0
};

after jquery script, because I don't care about IE anymore.