Programs & Examples On #Chirpy

Chirpy is a Visual Studio plug-in that can mash, minify, and validate JavaScript code, CSS, LESS files, and more. Chirpy can also auto-update T4MVC and other T4 templates.

Override console.log(); for production

This will override console.log function when the url does not contain localhost. You can replace the localhost with your own development settings.

// overriding console.log in production
if(window.location.host.indexOf('localhost:9000') < 0) {
    console.log = function(){};
}

Background position, margin-top?

 background-image: url(/images/poster.png);
 background-position: center;
 background-position-y: 50px;
 background-repeat: no-repeat;

Detect HTTP or HTTPS then force HTTPS in JavaScript

Try this

if (location.protocol !== 'https:') {
    location.replace(`https:${location.href.substring(location.protocol.length)}`);
}

location.href = blah adds this redirect to the browser history. If the user hits the back button, they will be redirected back to the the same page. It is better to use location.replace as it doesn't add this redirect to the browser history.

How to get cumulative sum

Above (Pre-SQL12) we see examples like this:-

SELECT
    T1.id, SUM(T2.id) AS CumSum
FROM 
    #TMP T1
    JOIN #TMP T2 ON T2.id < = T1.id
GROUP BY
    T1.id

More efficient...

SELECT
    T1.id, SUM(T2.id) + T1.id AS CumSum
FROM 
    #TMP T1
    JOIN #TMP T2 ON T2.id < T1.id
GROUP BY
    T1.id

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

The result of a query cannot be enumerated more than once

Try replacing this

var query = context.Search(id, searchText);

with

var query = context.Search(id, searchText).tolist();

and everything will work well.

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

Here is a function I made based on the answer above

def getDateToEpoch(myDateTime):
    res = (datetime.datetime(myDateTime.year,myDateTime.month,myDateTime.day,myDateTime.hour,myDateTime.minute,myDateTime.second) - datetime.datetime(1970,1,1)).total_seconds()
    return res

You can wrap the returned value like this : str(int(res)) To return it without a decimal value to be used as string or just int (without the str)

Add CSS or JavaScript files to layout head from views or partial views

You can define the section by RenderSection method in layout.

Layout

<head>
  <link href="@Url.Content("~/Content/themes/base/Site.css")"
    rel="stylesheet" type="text/css" />
  @RenderSection("heads", required: false)
</head>

Then you can include your css files in section area in your view except partial view.

The section work in view, but not work in partial view by design.

<!--your code -->
@section heads
{
  <link href="@Url.Content("~/Content/themes/base/AnotherPage.css")"
  rel="stylesheet" type="text/css" />
}

If you really want to using section area in partial view, you can follow the article to redefine RenderSection method.

Razor, Nested Layouts and Redefined Sections – Marcin On ASP.NET

How to convert a set to a list in python?

Python is a dynamically typed language, which means that you cannot define the type of the variable as you do in C or C++:

type variable = value

or

type variable(value)

In Python, you use coercing if you change types, or the init functions (constructors) of the types to declare a variable of a type:

my_set = set([1,2,3])
type my_set

will give you <type 'set'> for an answer.

If you have a list, do this:

my_list = [1,2,3]
my_set = set(my_list)

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

How to create a zip archive with PowerShell?

Here is a slightly improved version of sonjz's answer,it adds an overwrite option.

function Zip-Files(
        [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$false)]
        [string] $zipfilename,
        [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$false)]
        [string] $sourcedir,
        [Parameter(Position=2, Mandatory=$false, ValueFromPipeline=$false)]
        [bool] $overwrite)

{
   Add-Type -Assembly System.IO.Compression.FileSystem
   $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal

    if ($overwrite -eq $true )
    {
        if (Test-Path $zipfilename)
        {
            Remove-Item $zipfilename
        }
    }

    [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $false)
}

What are the -Xms and -Xmx parameters when starting JVM?

The question itself has already been addressed above. Just adding part of the default values.

As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

The default value of Xmx will depend on platform and amount of memory available in the system.

Can't connect to MySQL server error 111

It probably means that your MySQL server is only listening the localhost interface.

If you have lines like this :

bind-address = 127.0.0.1

In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

sudo service mysql restart

Of course, to do this, you must be the administrator of the server.

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

How to Handle Button Click Events in jQuery?

 $("#btnSubmit").click(function(){
        alert("button");
    });    

Differences between ConstraintLayout and RelativeLayout

Officially, ConstraintLayout is much faster

In the N release of Android, the ConstraintLayout class provides similar functionality to RelativeLayout, but at a significantly lower cost.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

An alternative solution is to disable the AOT compiler:

ng build --prod --aot false

disable editing default value of text input

Probably due to the fact that I could not explain well you do not really understand my question. In general, I found the solution.

Sorry for my english

How to mark a build unstable in Jenkins when running shell scripts

The TextFinder is good only if the job status hasn't been changed from SUCCESS to FAILED or ABORTED. For such cases, use a groovy script in the PostBuild step:

errpattern = ~/TEXT-TO-LOOK-FOR-IN-JENKINS-BUILD-OUTPUT.*/;
manager.build.logFile.eachLine{ line ->
    errmatcher=errpattern.matcher(line)
    if (errmatcher.find()) {
        manager.build.@result = hudson.model.Result.NEW-STATUS-TO-SET
    }
 }

See more details in a post I've wrote about it: http://www.tikalk.com/devops/JenkinsJobStatusChange/

Python - Move and overwrite files and folders

Have a look at: os.remove to remove existing files.

CakePHP select default value in SELECT input

In CakePHP 1.3, use 'default'=>value to select the default value in a select input:

$this->Form->input('Leaf.id', array('type'=>'select', 'label'=>'Leaf', 'options'=>$leafs, 'default'=>'3'));

java.util.zip.ZipException: error in opening zip file

In my case SL4j-api.jar with multiple versions are conflicting in the maven repo. Than I deleted the entire SL4j-api folder in m2 maven repo and updated maven project, build maven project than ran the project in JBOSS server. issue got resolved.

Javascript regular expression password validation having special characters

I use the following script for min 8 letter password, with at least a symbol, upper and lower case letters and a number

function checkPassword(str)
{
    var re = /^(?=.*\d)(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z]).{8,}$/;
    return re.test(str);
}

JQuery: Change value of hidden input field

It's simple as:

$('#action').val("1");

#action is hidden input field id.

How to highlight cell if value duplicate in same column for google spreadsheet?

Try this:

  1. Select the whole column
  2. Click Format
  3. Click Conditional formatting
  4. Click Add another rule (or edit the existing/default one)
  5. Set Format cells if to: Custom formula is
  6. Set value to: =countif(A:A,A1)>1 (or change A to your chosen column)
  7. Set the formatting style.
  8. Ensure the range applies to your column (e.g., A1:A100).
  9. Click Done

Anything written in the A1:A100 cells will be checked, and if there is a duplicate (occurs more than once) then it'll be coloured.

For locales using comma (,) as a decimal separator, the argument separator is most likely a semi-colon (;). That is, try: =countif(A:A;A1)>1, instead.

For multiple columns, use countifs.

How to automatically generate a stacktrace when my program crashes

Forget about changing your sources and do some hacks with backtrace() function or macroses - these are just poor solutions.

As a properly working solution, I would advice:

  1. Compile your program with "-g" flag for embedding debug symbols to binary (don't worry this will not impact your performance).
  2. On linux run next command: "ulimit -c unlimited" - to allow system make big crash dumps.
  3. When your program crashed, in the working directory you will see file "core".
  4. Run next command to print backtrace to stdout: gdb -batch -ex "backtrace" ./your_program_exe ./core

This will print proper readable backtrace of your program in human readable way (with source file names and line numbers). Moreover this approach will give you freedom to automatize your system: have a short script that checks if process created a core dump, and then send backtraces by email to developers, or log this into some logging system.

inject bean reference into a Quartz job in Spring?

You're right in your assumption about Spring vs. Quartz instantiating the class. However, Spring provides some classes that let you do some primitive dependency injection in Quartz. Check out SchedulerFactoryBean.setJobFactory() along with the SpringBeanJobFactory. Essentially, by using the SpringBeanJobFactory, you enable dependency injection on all Job properties, but only for values that are in the Quartz scheduler context or the job data map. I don't know what all DI styles it supports (constructor, annotation, setter...) but I do know it supports setter injection.

Javascript code for showing yesterday's date and todays date

Yesterday's date can be calculated as,

var prev_date = new Date();
prev_date.setDate(prev_date.getDate() - 1);

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

If you have a standard code signing certificate, some time will be needed for your application to build trust. Microsoft affirms that an Extended Validation (EV) Code Signing Certificate allows us to skip this period of trust-building. According to Microsoft, extended validation certificates allow the developer to immediately establish a reputation with SmartScreen. Otherwise, the users will see a warning like "Windows Defender SmartScreen prevented an unrecognized app from starting. Running this app might put your PC at risk.", with the two buttons: "Run anyway" and "Don't run".

Another Microsoft resource states the following (quote): "Although not required, programs signed by an EV code signing certificate can immediately establish a reputation with SmartScreen reputation services even if no prior reputation exists for that file or publisher. EV code signing certificates also have a unique identifier which makes it easier to maintain reputation across certificate renewals."

My experience is as follows. Since 2005, we have been using regular (non-EV) code signing certificates to sign .MSI, .EXE and .DLL files with time stamps, and there has never been a problem with SmartScreen until 2018, when there was just one case when it took 3 days for a beta version of our application to build trust since we have released it to beta testers, and it was in the middle of certificate validity period. I don't know what SmartScreen might not like in that specific version of our application, but there have been no SmartScreen complaints since then. Therefore, if your certificate is a non-EV, it is a signed application (such as an .MSI file) that will build trust over time, not a certificate. For example, a certificate can be issued a few months ago and used to sign many files, but for each signed file you publish, it may take a few days for SmartScreen to stop complaining about the file after publishing, as was in our case in 2018.

As a conclusion, to avoid the warning completely, i.e. prevent it from happening even suddenly, you need an Extended Validation (EV) code signing certificate.

Scrolling to an Anchor using Transition/CSS3

If anybody is just like me willing to use jQuery, but still found himself looking to this question then this may help you guys:

https://html-online.com/articles/animated-scroll-anchorid-function-jquery/

_x000D_
_x000D_
$(document).ready(function () {_x000D_
            $("a.scrollLink").click(function (event) {_x000D_
                event.preventDefault();_x000D_
                $("html, body").animate({ scrollTop: $($(this).attr("href")).offset().top }, 500);_x000D_
            });_x000D_
        });
_x000D_
<a href="#anchor1" class="scrollLink">Scroll to anchor 1</a>_x000D_
<a href="#anchor2" class="scrollLink">Scroll to anchor 2</a>_x000D_
<p id="anchor1"><strong>Anchor 1</strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea.</p>_x000D_
<p id="anchor2"><strong>Anchor 2</strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas.</p>
_x000D_
_x000D_
_x000D_

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • HTML CSS How to stop a table cell from expanding

    Simply set the max-width attribute to 280px like this:

    <td align="left" valign="top" style="overflow:hidden;" nowrap="nowrap" max-width="280px" width="280px">
    

    This will solve your problem.

    find first sequence item that matches a criterion

    If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

    next(obj for obj in objs if obj.val == 5)
    

    This is however faster than a complete list comprehension. Compare these two:

    [i for i in xrange(100000) if i == 1000][0]
    
    next(i for i in xrange(100000) if i == 1000)
    

    The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

    Hiding an Excel worksheet with VBA

    Just wanted to add a little more detail to the answers given. You can also use

    sheet.Visible = False
    

    to hide and

    sheet.Visible = True
    

    to unhide.

    Source

    Watch multiple $scope attributes

    Starting from AngularJS 1.3 there's a new method called $watchGroup for observing a set of expressions.

    $scope.foo = 'foo';
    $scope.bar = 'bar';
    
    $scope.$watchGroup(['foo', 'bar'], function(newValues, oldValues, scope) {
      // newValues array contains the current values of the watch expressions
      // with the indexes matching those of the watchExpression array
      // i.e.
      // newValues[0] -> $scope.foo 
      // and 
      // newValues[1] -> $scope.bar 
    });
    

    Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

    In build.gradle change minSdkVersion 17 or later.

    Extract the first word of a string in a SQL Server query

    DECLARE @string NVARCHAR(50)
    
    SET @string = 'CUT STRING'
    
    SELECT LEFT(@string,(PATINDEX('% %',@string)))
    

    Django: Get list of model fields?

    In sometimes we need the db columns as well:

    def get_db_field_names(instance):
       your_fields = instance._meta.local_fields
       db_field_names=[f.name+'_id' if f.related_model is not None else f.name  for f in your_fields]
       model_field_names = [f.name for f in your_fields]
       return db_field_names,model_field_names
    

    Call the method to get the fields:

    db_field_names,model_field_names=get_db_field_names(Mymodel)
    

    Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

    In my case, I just had to make sure I have my urls both with and without www for Application Domain and Redirect URLs:

    enter image description here

    In my case, I had to use: signin-facebook after my site url, for redirect url.

    Convert nested Python dict to object?

    Old Q&A, but I get something more to talk. Seems no one talk about recursive dict. This is my code:

    #!/usr/bin/env python
    
    class Object( dict ):
        def __init__( self, data = None ):
            super( Object, self ).__init__()
            if data:
                self.__update( data, {} )
    
        def __update( self, data, did ):
            dataid = id(data)
            did[ dataid ] = self
    
            for k in data:
                dkid = id(data[k])
                if did.has_key(dkid):
                    self[k] = did[dkid]
                elif isinstance( data[k], Object ):
                    self[k] = data[k]
                elif isinstance( data[k], dict ):
                    obj = Object()
                    obj.__update( data[k], did )
                    self[k] = obj
                    obj = None
                else:
                    self[k] = data[k]
    
        def __getattr__( self, key ):
            return self.get( key, None )
    
        def __setattr__( self, key, value ):
            if isinstance(value,dict):
                self[key] = Object( value )
            else:
                self[key] = value
    
        def update( self, *args ):
            for obj in args:
                for k in obj:
                    if isinstance(obj[k],dict):
                        self[k] = Object( obj[k] )
                    else:
                        self[k] = obj[k]
            return self
    
        def merge( self, *args ):
            for obj in args:
                for k in obj:
                    if self.has_key(k):
                        if isinstance(self[k],list) and isinstance(obj[k],list):
                            self[k] += obj[k]
                        elif isinstance(self[k],list):
                            self[k].append( obj[k] )
                        elif isinstance(obj[k],list):
                            self[k] = [self[k]] + obj[k]
                        elif isinstance(self[k],Object) and isinstance(obj[k],Object):
                            self[k].merge( obj[k] )
                        elif isinstance(self[k],Object) and isinstance(obj[k],dict):
                            self[k].merge( obj[k] )
                        else:
                            self[k] = [ self[k], obj[k] ]
                    else:
                        if isinstance(obj[k],dict):
                            self[k] = Object( obj[k] )
                        else:
                            self[k] = obj[k]
            return self
    
    def test01():
        class UObject( Object ):
            pass
        obj = Object({1:2})
        d = {}
        d.update({
            "a": 1,
            "b": {
                "c": 2,
                "d": [ 3, 4, 5 ],
                "e": [ [6,7], (8,9) ],
                "self": d,
            },
            1: 10,
            "1": 11,
            "obj": obj,
        })
        x = UObject(d)
    
    
        assert x.a == x["a"] == 1
        assert x.b.c == x["b"]["c"] == 2
        assert x.b.d[0] == 3
        assert x.b.d[1] == 4
        assert x.b.e[0][0] == 6
        assert x.b.e[1][0] == 8
        assert x[1] == 10
        assert x["1"] == 11
        assert x[1] != x["1"]
        assert id(x) == id(x.b.self.b.self) == id(x.b.self)
        assert x.b.self.a == x.b.self.b.self.a == 1
    
        x.x = 12
        assert x.x == x["x"] == 12
        x.y = {"a":13,"b":[14,15]}
        assert x.y.a == 13
        assert x.y.b[0] == 14
    
    def test02():
        x = Object({
            "a": {
                "b": 1,
                "c": [ 2, 3 ]
            },
            1: 6,
            2: [ 8, 9 ],
            3: 11,
        })
        y = Object({
            "a": {
                "b": 4,
                "c": [ 5 ]
            },
            1: 7,
            2: 10,
            3: [ 12 , 13 ],
        })
        z = {
            3: 14,
            2: 15,
            "a": {
                "b": 16,
                "c": 17,
            }
        }
        x.merge( y, z )
        assert 2 in x.a.c
        assert 3 in x.a.c
        assert 5 in x.a.c
        assert 1 in x.a.b
        assert 4 in x.a.b
        assert 8 in x[2]
        assert 9 in x[2]
        assert 10 in x[2]
        assert 11 in x[3]
        assert 12 in x[3]
        assert 13 in x[3]
        assert 14 in x[3]
        assert 15 in x[2]
        assert 16 in x.a.b
        assert 17 in x.a.c
    
    if __name__ == '__main__':
        test01()
        test02()
    

    Rails: How to list database tables/objects using the Rails console?

    Run this:

    Rails.application.eager_load! 
    

    Then

    ActiveRecord::Base.descendants
    

    To return a list of models/tables

    Symbol for any number of any characters in regex?

    Do you mean

    .*
    

    . any character, except newline character, with dotall mode it includes also the newline characters

    * any amount of the preceding expression, including 0 times

    Android Material: Status bar color won't change

    I know this doesn't answer the question, but with Material Design (API 21+) we can change the color of the status bar by adding this line in the theme declaration in styles.xml:

    <!-- MAIN THEME -->
    <style name="AppTheme" parent="@android:style/Theme.Material.Light">
        <item name="android:actionBarStyle">@style/actionBarCustomization</item>
        <item name="android:spinnerDropDownItemStyle">@style/mySpinnerDropDownItemStyle</item>
        <item name="android:spinnerItemStyle">@style/mySpinnerItemStyle</item>
        <item name="android:colorButtonNormal">@color/myDarkBlue</item>
        <item name="android:statusBarColor">@color/black</item>
    </style>
    

    Notice the android:statusBarColor, where we can define the color, otherwise the default is used.

    Using Java 8 to convert a list of objects into a string obtained from the toString() method

    There is a collector joining in the API. It's a static method in Collectors.

    list.stream().map(Object::toString).collect(Collectors.joining(","))
    

    Not perfect because of the necessary call of toString, but works. Different delimiters are possible.

    Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

    For swift

    var dateString:String = "2014-05-20";
    var dateFmt = NSDateFormatter()
    // the format you want
    dateFmt.dateFormat = "yyyy-MM-dd"
    var date1:NSDate = dateFmt.dateFromString(dateString)!;
    

    What does it mean by select 1 from table?

    If you don't know there exist any data in your table or not, you can use following query:

    SELECT cons_value FROM table_name;
    

    For an Example:

    SELECT 1 FROM employee;
    
    1. It will return a column which contains the total number of rows & all rows have the same constant value 1 (for this time it returns 1 for all rows);
    2. If there is no row in your table it will return nothing.

    So, we use this SQL query to know if there is any data in the table & the number of rows indicates how many rows exist in this table.

    React: how to update state.item[1] in state using setState?

    If you need to change only part of the Array, You've a react component with state set to.

    state = {items: [{name: 'red-one', value: 100}, {name: 'green-one', value: 999}]}
    

    It's best to update the red-one in the Array as follows:

    const itemIndex = this.state.items.findIndex(i=> i.name === 'red-one');
    const newItems = [
       this.state.items.slice(0, itemIndex),
       {name: 'red-one', value: 666},
       this.state.items.slice(itemIndex)
    ]
    
    this.setState(newItems)
    

    Convert hours:minutes:seconds into total minutes in excel

    The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:

    =HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60
    

    enter image description here

    SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

    Below Solution worked for me :

    Type About:Config in the Address Bar and press Enter.

    “This Might void your warranty!” warning will be displayed, click on I’ll be careful, I Promise button.

    Type security.ssl.enable_ocsp_stapling in search box.

    The value field is true, double click on it to make it false.

    Now try to connect your website again.

    Create auto-numbering on images/figures in MS Word

    Office 2007

    Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.

    Adding a custom header to HTTP request using angular.js

    If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…

    app.config(['$httpProvider', function ($httpProvider) {
        $httpProvider.defaults.headers.common = { 
            'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
            'Accept': 'application/json;odata=verbose'
          };
    }]);
    

    Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

    If embed no longer works for you, try with /v instead:

    <iframe width="420" height="315" src="https://www.youtube.com/v/A6XUVjK9W4o" frameborder="0" allowfullscreen></iframe>
    

    Application.WorksheetFunction.Match method

    You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

    I used CountIf below, but there is lots of different ways to check existence of a value in a range.

    Public Sub test()
    
    Dim rng As Range
    Dim aNumber As Long
    
    aNumber = 666
    
    Set rng = Sheet5.Range("B16:B615")
    
        If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then
    
            rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)
    
        Else
            MsgBox aNumber & " does not exist in range " & rng.Address
        End If
    
    End Sub
    

    ALTERNATIVE WAY

    Public Sub test()
        Dim rng As Range
        Dim aNumber As Variant
        Dim rowNum As Long
    
        aNumber = "2gg"
    
        Set rng = Sheet5.Range("B1:B20")
    
        If Not IsError(Application.Match(aNumber, rng, 0)) Then
            rowNum = Application.Match(aNumber, rng, 0)
            MsgBox rowNum
        Else
            MsgBox "error"
        End If
    End Sub
    

    OR

    Public Sub test()
        Dim rng As Range
        Dim aNumber As Variant
        Dim rowNum As Variant
    
        aNumber = "2gg"
    
        Set rng = Sheet5.Range("B1:B20")
    
        rowNum = Application.Match(aNumber, rng, 0)
    
        If Not IsError(rowNum) Then
            MsgBox rowNum
        Else
            MsgBox "error"
        End If
    End Sub
    

    Adding a SVN repository in Eclipse

    Try to connect to the repository using command line SVN to see if you get a similar error.

    $ svn checkout http://svn.python.org/projects/peps/trunk
    

    If you keep getting the error, it is probably an issue with your proxy server. I have found that I can't check out internet based SVN projects at work because the firewall blocks most HTTP commands. It only allows GET, POST and others necessary for browsing.

    Perform a Shapiro-Wilk Normality Test

    You failed to specify the exact columns (data) to test for normality. Use this instead

    shapiro.test(heisenberg$HWWIchg)
    

    Reading local text file into a JavaScript array

    Using Node.js

    sync mode:

    var fs = require("fs");
    var text = fs.readFileSync("./mytext.txt");
    var textByLine = text.split("\n")
    

    async mode:

    var fs = require("fs");
    fs.readFile("./mytext.txt", function(text){
        var textByLine = text.split("\n")
    });
    

    UPDATE

    As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

    var text = fs.readFileSync("./mytext.txt").toString('utf-8');
    

    Or

    var text = fs.readFileSync("./mytext.txt", "utf-8");
    

    Use xml.etree.ElementTree to print nicely formatted xml files

    You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

    >>> print(etree.tostring(root, pretty_print=True))
    <root>
      <child1/>
      <child2/>
      <child3/>
    </root>
    

    How to programmatically set style attribute in a view

    I made a helper interface for this using the holder pattern.

    public interface StyleHolder<V extends View> {
        void applyStyle(V view);
    }
    

    Now for every style you want to use pragmatically just implement the interface, for example:

    public class ButtonStyleHolder implements StyleHolder<Button> {
    
        private final Drawable background;
        private final ColorStateList textColor;
        private final int textSize;
    
        public ButtonStyleHolder(Context context) {
            TypedArray ta = context.obtainStyledAttributes(R.style.button, R.styleable.ButtonStyleHolder);
    
            Resources resources = context.getResources();
    
            background = ta.getDrawable(ta.getIndex(R.styleable.ButtonStyleHolder_android_background));
    
            textColor = ta.getColorStateList(ta.getIndex(R.styleable.ButtonStyleHolder_android_textColor));
    
            textSize = ta.getDimensionPixelSize(
                    ta.getIndex(R.styleable.ButtonStyleHolder_android_textSize),
                    resources.getDimensionPixelSize(R.dimen.standard_text_size)
            );
    
            // Don't forget to recycle!
            ta.recycle();
        }
    
        @Override
        public void applyStyle(Button btn) {
            btn.setBackground(background);
            btn.setTextColor(textColor);
            btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        }
    }
    

    Declare a stylable in your attrs.xml, the styleable for this example is:

    <declare-styleable name="ButtonStyleHolder">
        <attr name="android:background" />
        <attr name="android:textSize" />
        <attr name="android:textColor" />
    </declare-styleable>
    

    Here is the style declared in styles.xml:

    <style name="button">
        <item name="android:background">@drawable/button</item>
        <item name="android:textColor">@color/light_text_color</item>
        <item name="android:textSize">@dimen/standard_text_size</item>
    </style>
    

    And finally the implementation of the style holder:

    Button btn = new Button(context);    
    StyleHolder<Button> styleHolder = new ButtonStyleHolder(context);
    styleHolder.applyStyle(btn);
    

    I found this very helpful as it can be easily reused and keeps the code clean and verbose, i would recommend using this only as a local variable so we can allow the garbage collector to do its job once we're done with setting all the styles.

    How to use the onClick event for Hyperlink using C# code?

    Wow, you have a huge misunderstanding how asp.net works.

    This line of code

    System.Diagnostics.Process.Start("help/AdminTutorial.html");
    

    Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.

    A very easy solution would be to change the href attribute of the link in you page_load method.

    Your aspx code:

    <a href="#" runat="server" id="myLink">Tutorial</a>
    

    Your codebehind / cs code of page_load:

    ...
    if (userinfo.user == "Admin")
    {
      myLink.Attributes["href"] = "help/AdminTutorial.html";
    }
    else 
    {
      myLink.Attributes["href"] = "help/otherSite.html";
    }
    ...
    

    Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.

    Unix tail equivalent command in Windows Powershell

    For completeness I'll mention that Powershell 3.0 now has a -Tail flag on Get-Content

    Get-Content ./log.log -Tail 10
    

    gets the last 10 lines of the file

    Get-Content ./log.log -Wait -Tail 10
    

    gets the last 10 lines of the file and waits for more

    Also, for those *nix users, note that most systems alias cat to Get-Content, so this usually works

    cat ./log.log -Tail 10
    

    Android difference between Two Dates

    When you use Date() to calculate the difference in hours is necessary configure the SimpleDateFormat() in UTC otherwise you get one hour error due to Daylight SavingTime.

    How to reverse an std::string?

    I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse(). std::reverse() operates in place, so you may want to make a copy of the string first:

    #include <algorithm>
    #include <iostream>
    #include <string>
    
    int main()
    {
        std::string foo("foo");
        std::string copy(foo);
        std::cout << foo << '\n' << copy << '\n';
    
        std::reverse(copy.begin(), copy.end());
        std::cout << foo << '\n' << copy << '\n';
    }
    

    How to send email from Terminal?

    in the terminal on your mac os or linux os type this code

    mail -s (subject) (receiversEmailAddress)  <<< "how are you?"
    

    for an example try this

    mail -s "hi" [email protected] <<< "how are you?"<br>
    

    Jackson with JSON: Unrecognized field, not marked as ignorable

    If for some reason you cannot add the @JsonIgnoreProperties annotations to your class and you are inside a web server/container such as Jetty. You can create and customize the ObjectMapper inside a custom provider

    import javax.ws.rs.ext.ContextResolver;
    import javax.ws.rs.ext.Provider;
    
    import com.fasterxml.jackson.annotation.JsonInclude.Include;
    import com.fasterxml.jackson.databind.DeserializationFeature;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    @Provider
    public class CustomObjectMapperProvider implements ContextResolver<ObjectMapper> {
    
        private ObjectMapper objectMapper;
    
        @Override
        public ObjectMapper getContext(final Class<?> cls) {
            return getObjectMapper();
        }
    
        private synchronized ObjectMapper getObjectMapper() {
            if(objectMapper == null) {
                objectMapper = new ObjectMapper();
                objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            }
            return objectMapper;
        }
    }
    

    Where does System.Diagnostics.Debug.Write output appear?

    While debugging System.Diagnostics.Debug.WriteLine will display in the output window (Ctrl+Alt+O), you can also add a TraceListener to the Debug.Listeners collection to specify Debug.WriteLine calls to output in other locations.

    Note: Debug.WriteLine calls may not display in the output window if you have the Visual Studio option "Redirect all Output Window text to the Immediate Window" checked under the menu Tools ? Options ? Debugging ? General. To display "Tools ? Options ? Debugging", check the box next to "Tools ? Options ? Show All Settings".

    UITapGestureRecognizer - single tap and double tap

    Solution for Swift 2:

    let singleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap))
    singleTapGesture.numberOfTapsRequired = 1 // Optional for single tap
    view.addGestureRecognizer(singleTapGesture)
    
    let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap))
    doubleTapGesture.numberOfTapsRequired = 2
    view.addGestureRecognizer(doubleTapGesture)
    
    singleTapGesture.requireGestureRecognizerToFail(doubleTapGesture)
    

    Nginx: stat() failed (13: permission denied)

    In my case, the folder which served the files was a symbolic link to another folder, made with

    ln -sf /origin /var/www/destination
    

    Even though the permissions (user and group) where correct on the destination folder (the symbolic link), I still had the error because Nginx needed to have permissions to the origin folder whole's hierarchy as well.

    Add rows to CSV File in powershell

    To simply append to a file in powershell,you can use add-content.

    So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.

    $NewLine = "{0},{1}" -f $YourNewDate,$YourDescription
    $NewLine | add-content -path $file
    

    Or,

    "{0},{1}" -f $YourNewDate,$YourDescription | add-content -path $file
    

    This will just tag the new line to the end of the .csv, and will not work for creating new .csv files where you will need to add the header.

    Java: String - add character n-times

    Use this:

    String input = "original";
    String newStr = "new"; //new string to be added
    int n = 10 // no of times we want to add
    input = input + new String(new char[n]).replace("\0", newStr);
    

    What does $1 [QSA,L] mean in my .htaccess file?

    Not the place to give a complete tutorial, but here it is in short;

    RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

    The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

    QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

    L means if the rule matches, don't process any more RewriteRules below this one.

    For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

    Passing JavaScript array to PHP through jQuery $.ajax

    I know it may be too late to answer this, but this worked for me in a great way:

    1. Stringify your javascript object (json) with var st = JSON.stringify(your_object);

    2. Pass your POST data as "string" (maybe using jQuery: $.post('foo.php',{data:st},function(data){... });

    3. Decode your data on the server-side processing: $data = json_decode($_POST['data']);

    That's it... you can freely use your data.

    Multi-dimensional arrays and single arrays are handled as normal arrays. To access them just do the normal $foo[4].

    Associative arrays (javsacript objects) are handled as php objects (classes). To access them just do it like classes: $foo->bar.

    string to string array conversion in java

    Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).

    import org.apache.commons.lang3.StringUtils;
    
    StringUtils.split(null)       => null
    StringUtils.split("")         => []
    StringUtils.split("abc def")  => ["abc", "def"]
    StringUtils.split("abc  def") => ["abc", "def"]
    StringUtils.split(" abc ")    => ["abc"]
    

    Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:

    import com.google.common.base.Splitter;
    
    Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
    
    SPLITTER.split("a,b,   c , , ,, ")     =>  [a, b, c]
    SPLITTER.split("")                     =>  []
    SPLITTER.split("  ")                   =>  []
    SPLITTER.split(null)                   =>  NullPointerException
    

    If you want a list rather than an iterator then use Splitter.splitToList().

    How to remove focus from single editText

    check this question and the selected answer: Stop EditText from gaining focus at Activity startup It's ugly but it works, and as far as I know there's no better solution.

    Maven build debug in Eclipse

    The Run/Debug configuration you're using is meant to let you run Maven on your workspace as if from the command line without leaving Eclipse.

    Assuming your tests are JUnit based you should be able to debug them by choosing a source folder containing tests with the right button and choose Debug as... -> JUnit tests.

    Failed to load the JNI shared Library (JDK)

    Working pairings of OS, JDK and Eclipse:


    • 32-bit OS | 32-bit JDK | 32-bit Eclipse (32-bit only)
    • 64-bit OS | 32-bit JDK | 32-bit Eclipse
    • 64-bit OS | 64-bit JDK | 64bit Eclipse (64-bit only)

    I had several JDKs and JREs installed.

    Each of them had their own entry in the PATH variable, all was working more or less.

    Judging from the PATH variables, some installations were completely useless, since they were never used. Of course, the "inactive" Javas could be referenced manually from within Eclipse if I needed, but I never did that, so I really did not need them. (At least I thought so at that time...)

    I cleaned up the mess, deinstalled all current Java's, installed only JDK + JRE 1.7 64-bit.

    One of the Eclipse 'installations' failed afterwards with the Failed to Load the JNI shared Library and a given path relative to the fresh installed JDK where it thought the jvm.dll to be.

    The failing Eclipse was the only one of all my IDEs that was still a 32-bit version on my otherwise all-64-bit setup.

    Adding VM arguments, like so often mentioned, in the eclipse.ini was no use in my case (because I had only the wrong JDK/JRE to relate to.)

    I was also unable to find out how to check if this Eclipse was a 32-bit or 64-bit version (I could not look it up in the Task Manager, since this Eclipse 'installation' would not start up. And since it had been a while since I had set it up, I could not remember its version either.)

    In case you use a newer JDK and a older JRE you might be in for trouble, too, but then it is more likely a java.lang.UnsupportedClassVersionError appears, IIRC.

    How to select records from last 24 hours using SQL?

    Hello i now it past a lot of time from the original post but i got a similar problem and i want to share.

    I got a datetime field with this format YYYY-MM-DD hh:mm:ss, and i want to access a whole day, so here is my solution.

    The function DATE(), in MySQL: Extract the date part of a date or datetime expression.

    SELECT * FROM `your_table` WHERE DATE(`your_datatime_field`)='2017-10-09'
    

    with this i get all the row register in this day.

    I hope its help anyone.

    What is N-Tier architecture?

    If I understand the question, then it seems to me that the questioner is really asking "OK, so 3-tier is well understood, but it seems that there's a mix of hype, confusion, and uncertainty around what 4-tier, or to generalize, N-tier architectures mean. So...what's a definition of N-tier that is widely understood and agreed upon?"

    It's actually a fairly deep question, and to explain why, I need to go a little deeper. Bear with me.

    The classic 3-tier architecture: database, "business logic" and presentation, is a good way to clarify how to honor the principle of separation of concerns. Which is to say, if I want to change how "the business" wants to service customers, I should not have to look through the entire system to figure out how to do this, and in particular, decisions business issues shouldn't be scattered willy-nilly through the code.

    Now, this model served well for decades, and it is the classic 'client-server' model. Fast forward to cloud offerings, where web browsers are the user interface for a broad and physically distributed set of users, and one typically ends up having to add content distribution services, which aren't a part of the classic 3-tier architecture (and which need to be managed in their own right).

    The concept generalizes when it comes to services, micro-services, how data and computation are distributed and so on. Whether or not something is a 'tier' largely comes down to whether or not the tier provides an interface and deployment model to services that are behind (or beneath) the tier. So a content distribution network would be a tier, but an authentication service would not be.

    Now, go and read other descriptions of examples of N-tier architectures with this concept in mind, and you will begin to understand the issue. Other perspectives include vendor-based approaches (e.g. NGINX), content-aware load balancers, data isolation and security services (e.g. IBM Datapower), all of which may or may not add value to a given architecture, deployment, and use cases.

    How to create a delay in Swift?

    If your code is already running in a background thread, pause the thread using this method in Foundation: Thread.sleep(forTimeInterval:)

    For example:

    DispatchQueue.global(qos: .userInitiated).async {
    
        // Code is running in a background thread already so it is safe to sleep
        Thread.sleep(forTimeInterval: 4.0)
    }
    

    (See other answers for suggestions when your code is running on the main thread.)

    Find the directory part (minus the filename) of a full path in access 97

    If you're just needing the path of the MDB currently open in the Access UI, I'd suggest writing a function that parses CurrentDB.Name and then stores the result in a Static variable inside the function. Something like this:

    Public Function CurrentPath() As String
      Dim strCurrentDBName As String
      Static strPath As String
      Dim i As Integer
    
      If Len(strPath) = 0 Then
         strCurrentDBName = CurrentDb.Name
         For i = Len(strCurrentDBName) To 1 Step -1
           If Mid(strCurrentDBName, i, 1) = "\" Then
              strPath = Left(strCurrentDBName, i)
              Exit For
           End If
        Next
      End If
      CurrentPath = strPath
    End Function
    

    This has the advantage that it only loops through the name one time.

    Of course, it only works with the file that's open in the user interface.

    Another way to write this would be to use the functions provided at the link inside the function above, thus:

    Public Function CurrentPath() As String
      Static strPath As String
    
      If Len(strPath) = 0 Then
         strPath = FolderFromPath(CurrentDB.Name)
      End If
      CurrentPath = strPath
    End Function
    

    This makes retrieving the current path very efficient while utilizing code that can be used for finding the path for any filename/path.

    Determine which MySQL configuration file is being used

    Just did a quick test on ubuntu:

    • installed mysql-server, which created /etc/mysql/my.cnf

    • mysqld --verbose --help | grep -A 1 "Default options"

    110112 13:35:26 [Note] Plugin 'FEDERATED' is disabled.
    Default options are read from the following files in the given order: /etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf

    • created /etc/my.cnf and /usr/etc/my.cnf, each with a different port number

    • restarted mysql - it was using the port number set in /usr/etc/my.cnf

    Also meanwhile found the --defaults-file option to the mysqld. If you specify a config file there, only that one will be used, regardless of what is returned by /usr/sbin/mysqld --verbose --help | grep -A 1 "Default options"

    How can I make a button redirect my page to another page?

    This is here:

     <button onClick="window.location='page_name.php';" value="click here" />
    

    Node Version Manager install - nvm command not found

    After trying multiple steps, not sure what was the problem in my case but running this helped:

    touch ~/.bash_profile
    curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.1/install.sh | bash
    

    Verified by nvm --version

    nvm -v output

    SQL Server: Is it possible to insert into two tables at the same time?

    Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?

    casting Object array to Integer array error

    You can't cast an Object array to an Integer array. You have to loop through all elements of a and cast each one individually.

    Object[] a = new Object[1];
    Integer b=1;
    a[0]=b;
    Integer[] c = new Integer[a.length];
    for(int i = 0; i < a.length; i++)
    {
        c[i] = (Integer) a[i];
    }
    

    Edit: I believe the rationale behind this restriction is that when casting, the JVM wants to ensure type-safety at runtime. Since an array of Objects can be anything besides Integers, the JVM would have to do what the above code is doing anyway (look at each element individually). The language designers decided they didn't want the JVM to do that (I'm not sure why, but I'm sure it's a good reason).

    However, you can cast a subtype array to a supertype array (e.g. Integer[] to Object[])!

    Bash script - variable content as a command to run

    line=$((${RANDOM} % $(wc -l < /etc/passwd)))
    sed -n "${line}p" /etc/passwd
    

    just with your file instead.

    In this example I used the file /etc/password, using the special variable ${RANDOM} (about which I learned here), and the sed expression you had, only difference is that I am using double quotes instead of single to allow the variable expansion.

    count number of lines in terminal output

    "abcd4yyyy" | grep 4 -c gives the count as 1

    Use a list of values to select rows from a pandas dataframe

    You can use isin method:

    In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
    
    In [2]: df
    Out[2]:
       A  B
    0  5  1
    1  6  2
    2  3  3
    3  4  5
    
    In [3]: df[df['A'].isin([3, 6])]
    Out[3]:
       A  B
    1  6  2
    2  3  3
    

    And to get the opposite use ~:

    In [4]: df[~df['A'].isin([3, 6])]
    Out[4]:
       A  B
    0  5  1
    3  4  5
    

    css with background image without repeating the image

    This is all you need:

    background-repeat: no-repeat;
    

    JQuery: dynamic height() with window resize()

    To see the window height while (or after) it is resized, try it:

    $(window).resize(function() {
    $('body').prepend('<div>' + $(window).height() - 46 + '</div>');
    });
    

    How to get the latest file in a folder?

    I would suggest using glob.iglob() instead of the glob.glob(), as it is more efficient.

    glob.iglob() Return an iterator which yields the same values as glob() without actually storing them all simultaneously.

    Which means glob.iglob() will be more efficient.

    I mostly use below code to find the latest file matching to my pattern:

    LatestFile = max(glob.iglob(fileNamePattern),key=os.path.getctime)


    NOTE: There are variants of max function, In case of finding the latest file we will be using below variant: max(iterable, *[, key, default])

    which needs iterable so your first parameter should be iterable. In case of finding max of nums we can use beow variant : max (num1, num2, num3, *args[, key])

    How do I delete an item or object from an array using ng-click?

    Using $index works perfectly well in basic cases, and @charlietfl's answer is great. But sometimes, $index isn't enough.

    Imagine you have a single array, which you're presenting in two different ng-repeat's. One of those ng-repeat's is filtered for objects that have a truthy property, and the other is filtered for a falsy property. Two different filtered arrays are being presented, which derive from a single original array. (Or, if it helps to visualize: perhaps you have a single array of people, and you want one ng-repeat for the women in that array, and another for the men in that same array.) Your goal: delete reliably from the original array, using information from the members of the filtered arrays.

    In each of those filtered arrays, $index won't be the index of the item within the original array. It'll be the index in the filtered sub-array. So, you won't be able to tell the person's index in the original people array, you'll only know the $index from the women or men sub-array. Try to delete using that, and you'll have items disappearing from everywhere except where you wanted. What to do?

    If you're lucky enough be using a data model includes a unique identifier for each object, then use that instead of $index, to find the object and splice it out of the main array. (Use my example below, but with that unique identifier.) But if you're not so lucky?

    Angular actually augments each item in an ng-repeated array (in the main, original array) with a unique property called $$hashKey. You can search the original array for a match on the $$hashKey of the item you want to delete, and get rid of it that way.

    Note that $$hashKey is an implementation detail, not included in the published API for ng-repeat. They could remove support for that property at any time. But probably not. :-)

    $scope.deleteFilteredItem = function(hashKey, sourceArray){
      angular.forEach(sourceArray, function(obj, index){
        // sourceArray is a reference to the original array passed to ng-repeat, 
        // rather than the filtered version. 
        // 1. compare the target object's hashKey to the current member of the iterable:
        if (obj.$$hashKey === hashKey) {
          // remove the matching item from the array
          sourceArray.splice(index, 1);
          // and exit the loop right away
          return;
        };
      });
    }
    

    Invoke with:

    ng-click="deleteFilteredItem(item.$$hashKey, refToSourceArray)"
    

    EDIT: Using a function like this, which keys on the $$hashKey instead of a model-specific property name, also has the significant added advantage of making this function reusable across different models and contexts. Provide it with your array reference, and your item reference, and it should just work.

    Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

    Change to another USB port works for me. I tried reset ADB, but problem still there.

    How can I issue a single command from the command line through sql plus?

    For UNIX (AIX):

    export ORACLE_HOME=/oracleClient/app/oracle/product/version
    export DBUSER=fooUser
    export DBPASSWD=fooPW
    export DBNAME=fooSchema 
    
    echo "select * from someTable;" | $ORACLE_HOME/bin/sqlplus $DBUSER/$DBPASSWD@$DBNAME
    

    UPDATE multiple tables in MySQL using LEFT JOIN

    UPDATE `Table A` a
    SET a.`text`=(
            SELECT group_concat(b.`B-num`,' from ',b.`date` SEPARATOR ' / ') 
            FROM `Table B` b WHERE (a.`A-num`=b.`A-num`)
    )
    

    Cursor adapter and sqlite example

    Really simple example.

    Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.

    There are two main parts to using a Cursor Adapter with SQLite:

    1. Create a proper Cursor from the Database.

    2. Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.

    1. Create a proper Cursor from the Database.

    In your Activity:

    SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper( 
            context, DATABASE_NAME, null, DATABASE_VERSION);
    
    SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();
    
    String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'
    
    Cursor cursor = sqLiteDatabase.rawQuery(query, null); 
    
    ClientCursorAdapter adapter = new ClientCursorAdapter(
            this, R.layout.clients_listview_row, cursor, 0 );
    
    this.setListAdapter(adapter);
    

    2. Create a Custom Cursor Adapter.

    Note: Extending from ResourceCursorAdapter assumes you use XML to create your views.

    public class ClientCursorAdapter extends ResourceCursorAdapter {
    
        public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
            super(context, layout, cursor, flags);
        }
    
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            TextView name = (TextView) view.findViewById(R.id.name);
            name.setText(cursor.getString(cursor.getColumnIndex("name")));
    
            TextView phone = (TextView) view.findViewById(R.id.phone);
            phone.setText(cursor.getString(cursor.getColumnIndex("phone")));
        }
    }
    

    git rebase merge conflict

    If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".

    First, checkout temp branch and start standard merge

    git checkout -b temp
    git merge origin/master
    

    You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.

    git commit -m "Merge branch 'origin/master' into 'temp'"
    

    Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.

    git checkout alpha
    git rebase origin/master -X theirs
    

    Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.

    git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)
    

    And delete temporary branch

    git branch -D temp
    

    That's all. We did a rebase via hidden merge.

    Also I wrote a script, so that can be done in a dialog manner, you can find it here.

    Optimal way to concatenate/aggregate strings

    For those of us who found this and are not using Azure SQL Database:

    STRING_AGG() in PostgreSQL, SQL Server 2017 and Azure SQL
    https://www.postgresql.org/docs/current/static/functions-aggregate.html
    https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

    GROUP_CONCAT() in MySQL
    http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat

    (Thanks to @Brianjorden and @milanio for Azure update)

    Example Code:

    select Id
    , STRING_AGG(Name, ', ') Names 
    from Demo
    group by Id
    

    SQL Fiddle: http://sqlfiddle.com/#!18/89251/1

    PHP preg_replace special characters

    $newstr = preg_replace('/[^a-zA-Z0-9\']/', '_', "There wouldn't be any");
    $newstr = str_replace("'", '', $newstr);
    

    I put them on two separate lines to make the code a little more clear.

    Note: If you're looking for Unicode support, see Filip's answer below. It will match all characters that register as letters in addition to A-z.

    How do I append text to a file?

    How about:

    echo "hello" >> <filename>
    

    Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

    You could also use printf in the same way:

    printf "hello" >> <filename>
    

    Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

    set -o noclobber
    

    Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

    To force writing to the file you must now use the special syntax:

    echo "hello" >| <filename>
    

    You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

    echo -n "hello" >> <filename>
    

    References

    Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

    Check your TLS version:

    python2 -c "import urllib2,json; print(json.loads(urllib2.urlopen('https://www.howsmyssl.com/a/check').read())['tls_version'])"
    

    If your TLS version is less than 1.2 you have to upgrade it since the PyPI repository is on a brownout period of deprecating early TLS.

    Source - Time To Upgrade Your Python: TLS v1.2 Will Soon Be Mandatory

    You can upgrade the TLS version using the following command:

    sudo apt-get update && sudo apt-get install openssl libssl-dev
    

    This should fix your problem. Good luck!

    EDIT: You can download packages using your own private python package repository regardless of TLS version. Private Python Package Repository

    Programmatically find the number of cores on a machine

    One more Windows recipe: use system-wide environment variable NUMBER_OF_PROCESSORS:

    printf("%d\n", atoi(getenv("NUMBER_OF_PROCESSORS")));
    

    What are the differences between the different saving methods in Hibernate?

    Actually the difference between hibernate save() and persist() methods is depends on generator class we are using.

    If our generator class is assigned, then there is no difference between save() and persist() methods. Because generator ‘assigned’ means, as a programmer we need to give the primary key value to save in the database right [ Hope you know this generators concept ] In case of other than assigned generator class, suppose if our generator class name is Increment means hibernate it self will assign the primary key id value into the database right [ other than assigned generator, hibernate only used to take care the primary key id value remember ], so in this case if we call save() or persist() method then it will insert the record into the database normally But hear thing is, save() method can return that primary key id value which is generated by hibernate and we can see it by

    long s = session.save(k);
    

    In this same case, persist() will never give any value back to the client.

    How to clamp an integer to some range?

    Chaining max() and min() together is the normal idiom I've seen. If you find it hard to read, write a helper function to encapsulate the operation:

    def clamp(minimum, x, maximum):
        return max(minimum, min(x, maximum))
    

    What is the best way to update the entity in JPA

    That depends on what you want to do, but as you said, getting an entity reference using find() and then just updating that entity is the easiest way to do that.

    I'd not bother about performance differences of the various methods unless you have strong indications that this really matters.

    How to discover number of *logical* cores on Mac OS X?

    You can do this using the sysctl utility:

    sysctl -n hw.ncpu
    

    Execute a PHP script from another PHP script

    Possible and easiest one-line solution is to use:

    file_get_contents("YOUR_REQUESTED_FILE");
    

    Or equivavelt for example CURL.

    How to code a BAT file to always run as admin mode?

    1. My experimenting indicates that the runas command must include the admin user's domain (at least it does in my organization's environmental setup):

      runas /user:AdminDomain\AdminUserName ExampleScript.bat
      

      If you don’t already know the admin user's domain, run an instance of Command Prompt as the admin user, and enter the following command:

      echo %userdomain%
      
    2. The answers provided by both Kerrek SB and Ed Greaves will execute the target file under the admin user but, if the file is a Command script (.bat file) or VB script (.vbs file) which attempts to operate on the normal-login user’s environment (such as changing registry entries), you may not get the desired results because the environment under which the script actually runs will be that of the admin user, not the normal-login user! For example, if the file is a script that operates on the registry’s HKEY_CURRENT_USER hive, the affected “current-user” will be the admin user, not the normal-login user.

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

    DATEDIFF(minute,startdate,enddate)/60.0)
    

    Or use this for 2 decimal places:

    CAST(DATEDIFF(minute,startdate,enddate)/60.0 as decimal(18,2))
    

    Get original URL referer with PHP?

    Store it in a cookie that only lasts for the current browsing session

    Redirect all to index.php using htaccess

    You can use something like this:

    RewriteEngine on
    RewriteRule ^.+$ /index.php [L]
    

    This will redirect every query to the root directory's index.php. Note that it will also redirect queries for files that exist, such as images, javascript files or style sheets.

    What does 'corrupted double-linked list' mean

    I ran into this error in some code where someone was calling exit() in one thread about the same time as main() returned, so all the global/static constructors were being kicked off in two separate threads simultaneously.

    This error also manifests as double free or corruption, or a segfault/sig11 inside exit() or inside malloc_consolidate, and likely others. The call stack for the malloc_consolidate crash may resemble:

    #0  0xabcdabcd in malloc_consolidate () from /lib/libc.so.6
    #1  0xabcdabcd in _int_free () from /lib/libc.so.6
    #2  0xabcdabcd in operator delete (...)
    #3  0xabcdabcd in operator delete[] (...)
    (...)
    

    I couldn't get it to exhibit this problem while running under valgrind.

    How can I scroll a div to be visible in ReactJS?

    In you keyup/down handler you just need to set the scrollTop property of the div you want to scroll to make it scroll down (or up).

    For example:

    JSX:

    <div ref="foo">{content}</div>

    keyup/down handler:

    this.refs.foo.getDOMNode().scrollTop += 10

    If you do something similar to above, your div will scroll down 10 pixels (assuming the div is set to overflow auto or scroll in css, and your content is overflowing of course).

    You will need to expand on this to find the offset of the element inside your scrolling div that you want to scroll the div down to, and then modify the scrollTop to scroll far enough to show the element based on it's height.

    Have a look at MDN's definitions of scrollTop, and offsetTop here:

    https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop

    https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

    how do I give a div a responsive height

    I know this is a little late to the party but you could use viewport units

    From caniuse.com:

    Viewport units: vw, vh, vmin, vmax - CR Length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).

    Support: http://caniuse.com/#feat=viewport-units

    _x000D_
    _x000D_
    div {_x000D_
    /* 25% of viewport */_x000D_
      height: 25vh;_x000D_
      width: 15rem;_x000D_
      background-color: #222;_x000D_
      color: #eee;_x000D_
      font-family: monospace;_x000D_
      padding: 2rem;_x000D_
    }
    _x000D_
    <div>responsive height</div>
    _x000D_
    _x000D_
    _x000D_

    On linux SUSE or RedHat, how do I load Python 2.7

    Execute the below commands to make yum work as well as python2.7

    yum groupinstall -y development
    yum groupinstall -y 'development tools'
    yum install -y zlib-dev openssl-devel wget sqlite-devel bzip2-devel
    yum -y install gcc gcc-c++ numpy python-devel scipy git boost*
    yum install -y *lapack*
    yum install -y gcc gcc-c++ make bison flex autoconf libtool memcached libevent libevent-devel uuidd libuuid-devel  boost boost-devel libcurl-dev libcurl curl gperf mysql-devel
    
    cd
    mkdir srk
    cd srk 
    wget http://www.python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz
    yum install xz-libs
    xz -d Python-2.7.6.tar.xz
    tar -xvf Python-2.7.6.tar
    cd Python-2.7.6
    ./configure --prefix=/usr/local
    make
    make altinstall
    
    
    
    echo "export PATH="/usr/local/bin:$PATH"" >> /etc/profile
    source /etc/profile
    mv /usr/bin/python /usr/bin/python.bak
    update-alternatives --install /usr/bin/python python /usr/bin/python2.6 1
    update-alternatives --install /usr/bin/python python /usr/local/bin/python2.7 2
    update-alternatives --config python
    sed -i "s/python/python2.6/g" /usr/bin/yum
    

    Is there a better way to refresh WebView?

    Why not to try this?

    Swift code to call inside class:

    self.mainFrame.reload()
    

    or external call

    myWebV.mainFrame.reload()
    

    SQLAlchemy: print the actual query

    This code is based on brilliant existing answer from @bukzor. I just added custom render for datetime.datetime type into Oracle's TO_DATE().

    Feel free to update code to suit your database:

    import decimal
    import datetime
    
    def printquery(statement, bind=None):
        """
        print a query, with values filled in
        for debugging purposes *only*
        for security, you should always separate queries from their values
        please also note that this function is quite slow
        """
        import sqlalchemy.orm
        if isinstance(statement, sqlalchemy.orm.Query):
            if bind is None:
                bind = statement.session.get_bind(
                        statement._mapper_zero_or_none()
                )
            statement = statement.statement
        elif bind is None:
            bind = statement.bind 
    
        dialect = bind.dialect
        compiler = statement._compiler(dialect)
        class LiteralCompiler(compiler.__class__):
            def visit_bindparam(
                    self, bindparam, within_columns_clause=False, 
                    literal_binds=False, **kwargs
            ):
                return super(LiteralCompiler, self).render_literal_bindparam(
                        bindparam, within_columns_clause=within_columns_clause,
                        literal_binds=literal_binds, **kwargs
                )
            def render_literal_value(self, value, type_):
                """Render the value of a bind parameter as a quoted literal.
    
                This is used for statement sections that do not accept bind paramters
                on the target driver/database.
    
                This should be implemented by subclasses using the quoting services
                of the DBAPI.
    
                """
                if isinstance(value, basestring):
                    value = value.replace("'", "''")
                    return "'%s'" % value
                elif value is None:
                    return "NULL"
                elif isinstance(value, (float, int, long)):
                    return repr(value)
                elif isinstance(value, decimal.Decimal):
                    return str(value)
                elif isinstance(value, datetime.datetime):
                    return "TO_DATE('%s','YYYY-MM-DD HH24:MI:SS')" % value.strftime("%Y-%m-%d %H:%M:%S")
    
                else:
                    raise NotImplementedError(
                                "Don't know how to literal-quote value %r" % value)            
    
        compiler = LiteralCompiler(dialect, statement)
        print compiler.process(statement)
    

    How to get the type of a variable in MATLAB?

    Be careful when using the isa function. This will be true if your object is of the specified type or one of its subclasses. You have to use strcmp with the class function to test if the object is specifically that type and not a subclass.

    How to install easy_install in Python 2.7.1 on Windows 7

    That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.

    http://pypi.python.org/pypi/distribute#installation-instructions

    Global keyboard capture in C# application

    Stephen Toub wrote a great article on implementing global keyboard hooks in C#:

    using System;
    using System.Diagnostics;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    class InterceptKeys
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private static LowLevelKeyboardProc _proc = HookCallback;
        private static IntPtr _hookID = IntPtr.Zero;
    
        public static void Main()
        {
            _hookID = SetHook(_proc);
            Application.Run();
            UnhookWindowsHookEx(_hookID);
        }
    
        private static IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                    GetModuleHandle(curModule.ModuleName), 0);
            }
        }
    
        private delegate IntPtr LowLevelKeyboardProc(
            int nCode, IntPtr wParam, IntPtr lParam);
    
        private static IntPtr HookCallback(
            int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                Console.WriteLine((Keys)vkCode);
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }
    
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook,
            LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
    
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);
    
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
            IntPtr wParam, IntPtr lParam);
    
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    }
    

    fail to change placeholder color with Bootstrap 3

    The others did not work in my case (Bootstrap 4). Here is the solution I used.

    html .form-control::-webkit-input-placeholder { color:white; }
    html .form-control:-moz-placeholder { color:white; }
    html .form-control::-moz-placeholder { color:white; }
    html .form-control:-ms-input-placeholder { color:white; }
    

    If we use a stronger selector (html first), we don't need to use the hacky value !important.

    This overrides bootstraps CSS as we use a higher level of specificity to target .form-control elements (html first instead of .form-control first).

    What is HEAD in Git?

    It feels like that HEAD is just a tag for the last commit that you checked out.

    This can be the tip of a specific branch (such as "master") or some in-between commit of a branch ("detached head")

    How to split a string in two and store it in a field

    I would suggest the following:

    String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

    Generating CSV file for Excel, how to have a newline inside a value

    UTF files that contain a BOM will cause Excel to treat new lines literally even in that field is surrounded by quotes. (Tested Excel 2008 Mac)

    The solution is to make any new lines a carriage return (CHR 13) rather than a line feed.

    Check if a class `active` exist on element with jquery

    i wrote a helper method to help me go through all my selected elements and remove the active class.

        function removeClassFromElem(classSelect, classToRemove){
          $(classSelect).each(function(){
            var currElem=$(this);
            if(currElem.hasClass(classToRemove)){
              currElem.removeClass(classToRemove);
            }
          });
        }
    
        //usage
        removeClassFromElem('.someclass', 'active');
    

    How to enable Ad Hoc Distributed Queries

    sp_configure 'show advanced options', 1;
    GO
    RECONFIGURE;
    GO
    sp_configure 'Ad Hoc Distributed Queries', 1;
    GO
    RECONFIGURE;
    GO
    

    Codeigniter - multiple database connections

    Use this.

    $dsn1 = 'mysql://user:password@localhost/db1';
    $this->db1 = $this->load->database($dsn1, true);     
    
    $dsn2 = 'mysql://user:password@localhost/db2';
    $this->db2= $this->load->database($dsn2, true);     
    
    $dsn3 = 'mysql://user:password@localhost/db3';
    $this->db3= $this->load->database($dsn3, true);   
    

    Usage

    $this->db1 ->insert('tablename', $insert_array);
    $this->db2->insert('tablename', $insert_array);
    $this->db3->insert('tablename', $insert_array);
    

    Binding a list in @RequestParam

    One way you could accomplish this (in a hackish way) is to create a wrapper class for the List. Like this:

    class ListWrapper {
         List<String> myList; 
         // getters and setters
    }
    

    Then your controller method signature would look like this:

    public String controllerMethod(ListWrapper wrapper) {
        ....
    }
    

    No need to use the @RequestParam or @ModelAttribute annotation if the collection name you pass in the request matches the collection field name of the wrapper class, in my example your request parameters should look like this:

    myList[0]     : 'myValue1'
    myList[1]     : 'myValue2'
    myList[2]     : 'myValue3'
    otherParam    : 'otherValue'
    anotherParam  : 'anotherValue'
    

    phpMyAdmin Error: The mbstring extension is missing. Please check your PHP configuration

    Change extension_dir = "ext" to extension_dir = "C:/php/ext" in php.ini.

    Using if elif fi in shell scripts

    Josh Lee's answer works, but you can use the "&&" operator for better readability like this:

    echo "You have provided the following arguments $arg1 $arg2 $arg3"
    if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
    then 
        echo "Two of the provided args are equal."
        exit 3
    elif [ $arg1 = $arg2 ] && [ $arg1 = $arg3 ]
    then
        echo "All of the specified args are equal"
        exit 0
    else
        echo "All of the specified args are different"
        exit 4 
    fi
    

    How to replace existing value of ArrayList element in Java

    If you are unaware of the position to replace, use list iterator to find and replace element ListIterator.set(E e)

    ListIterator<String> iterator = list.listIterator();
    while (iterator.hasNext()) {
         String next = iterator.next();
         if (next.equals("Two")) {
             //Replace element
             iterator.set("New");
         }
     }
    

    Preprocessor check if multiple defines are not defined

    #if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL)
    

    Validating IPv4 addresses with regexp

    I think many people reading this post will be looking for simpler regular expressions, even if they match some technically invalid IP addresses. (And, as noted elsewhere, regex probably isn't the right tool for properly validating an IP address anyway.)

    Remove ^ and, where applicable, replace $ with \b, if you don't want to match the beginning/end of the line.

    Basic Regular Expression (BRE) (tested on GNU grep, GNU sed, and vim):

    /^[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+$/
    

    Extended Regular Expression (ERE):

    /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/
    

    or:

    /^([0-9]+(\.|$)){4}/
    

    Perl-compatible Regular Expression (PCRE) (tested on Perl 5.18):

    /^\d+\.\d+\.\d+\.\d+$/
    

    or:

    /^(\d+(\.|$)){4}/
    

    Ruby (tested on Ruby 2.1):

    Although supposed to be PCRE, Ruby for whatever reason allowed this regex not allowed by Perl 5.18:

    /^(\d+[\.$]){4}/
    

    My tests for all these are online here.

    Parsing PDF files (especially with tables) with PDFBox

    For reading content of the table from pdf file,you have to do only just convert the pdf file into a text file by using any API(I have use PdfTextExtracter.getTextFromPage() of iText) and then read that txt file by your java program..now after reading it the major task is done.. you have to filter the data of your need. you can do it by continuously using split method of String class until you find record of your intrest.. here is my code by which I have extract part of record by an PDF file and write it into a .CSV file.. Url of PDF file is..http://www.cea.nic.in/reports/monthly/generation_rep/actual/jan13/opm_02.pdf

    Code:-

    public static void genrateCsvMonth_Region(String pdfpath, String csvpath) {
            try {
                String line = null;
                // Appending Header in CSV file...
                BufferedWriter writer1 = new BufferedWriter(new FileWriter(csvpath,
                        true));
                writer1.close();
                // Checking whether file is empty or not..
                BufferedReader br = new BufferedReader(new FileReader(csvpath));
    
                if ((line = br.readLine()) == null) {
                    BufferedWriter writer = new BufferedWriter(new FileWriter(
                            csvpath, true));
                    writer.append("REGION,");
                    writer.append("YEAR,");
                    writer.append("MONTH,");
                    writer.append("THERMAL,");
                    writer.append("NUCLEAR,");
                    writer.append("HYDRO,");
                    writer.append("TOTAL\n");
                    writer.close();
                }
                // Reading the pdf file..
                PdfReader reader = new PdfReader(pdfpath);
                BufferedWriter writer = new BufferedWriter(new FileWriter(csvpath,
                        true));
    
                // Extracting records from page into String..
                String page = PdfTextExtractor.getTextFromPage(reader, 1);
                // Extracting month and Year from String..
                String period1[] = page.split("PEROID");
                String period2[] = period1[0].split(":");
                String month[] = period2[1].split("-");
                String period3[] = month[1].split("ENERGY");
                String year[] = period3[0].split("VIS");
    
                // Extracting Northen region
                String northen[] = page.split("NORTHEN REGION");
                String nthermal1[] = northen[0].split("THERMAL");
                String nthermal2[] = nthermal1[1].split(" ");
    
                String nnuclear1[] = northen[0].split("NUCLEAR");
                String nnuclear2[] = nnuclear1[1].split(" ");
    
                String nhydro1[] = northen[0].split("HYDRO");
                String nhydro2[] = nhydro1[1].split(" ");
    
                String ntotal1[] = northen[0].split("TOTAL");
                String ntotal2[] = ntotal1[1].split(" ");
    
                // Appending filtered data into CSV file..
                writer.append("NORTHEN" + ",");
                writer.append(year[0] + ",");
                writer.append(month[0] + ",");
                writer.append(nthermal2[4] + ",");
                writer.append(nnuclear2[4] + ",");
                writer.append(nhydro2[4] + ",");
                writer.append(ntotal2[4] + "\n");
    
                // Extracting Western region
                String western[] = page.split("WESTERN");
    
                String wthermal1[] = western[1].split("THERMAL");
                String wthermal2[] = wthermal1[1].split(" ");
    
                String wnuclear1[] = western[1].split("NUCLEAR");
                String wnuclear2[] = wnuclear1[1].split(" ");
    
                String whydro1[] = western[1].split("HYDRO");
                String whydro2[] = whydro1[1].split(" ");
    
                String wtotal1[] = western[1].split("TOTAL");
                String wtotal2[] = wtotal1[1].split(" ");
    
                // Appending filtered data into CSV file..
                writer.append("WESTERN" + ",");
                writer.append(year[0] + ",");
                writer.append(month[0] + ",");
                writer.append(wthermal2[4] + ",");
                writer.append(wnuclear2[4] + ",");
                writer.append(whydro2[4] + ",");
                writer.append(wtotal2[4] + "\n");
    
                // Extracting Southern Region
                String southern[] = page.split("SOUTHERN");
    
                String sthermal1[] = southern[1].split("THERMAL");
                String sthermal2[] = sthermal1[1].split(" ");
    
                String snuclear1[] = southern[1].split("NUCLEAR");
                String snuclear2[] = snuclear1[1].split(" ");
    
                String shydro1[] = southern[1].split("HYDRO");
                String shydro2[] = shydro1[1].split(" ");
    
                String stotal1[] = southern[1].split("TOTAL");
                String stotal2[] = stotal1[1].split(" ");
    
                // Appending filtered data into CSV file..
                writer.append("SOUTHERN" + ",");
                writer.append(year[0] + ",");
                writer.append(month[0] + ",");
                writer.append(sthermal2[4] + ",");
                writer.append(snuclear2[4] + ",");
                writer.append(shydro2[4] + ",");
                writer.append(stotal2[4] + "\n");
    
                // Extracting eastern region
                String eastern[] = page.split("EASTERN");
    
                String ethermal1[] = eastern[1].split("THERMAL");
                String ethermal2[] = ethermal1[1].split(" ");
    
                String ehydro1[] = eastern[1].split("HYDRO");
                String ehydro2[] = ehydro1[1].split(" ");
    
                String etotal1[] = eastern[1].split("TOTAL");
                String etotal2[] = etotal1[1].split(" ");
                // Appending filtered data into CSV file..
                writer.append("EASTERN" + ",");
                writer.append(year[0] + ",");
                writer.append(month[0] + ",");
                writer.append(ethermal2[4] + ",");
                writer.append(" " + ",");
                writer.append(ehydro2[4] + ",");
                writer.append(etotal2[4] + "\n");
    
                // Extracting northernEastern region
                String neestern[] = page.split("NORTH");
    
                String nethermal1[] = neestern[2].split("THERMAL");
                String nethermal2[] = nethermal1[1].split(" ");
    
                String nehydro1[] = neestern[2].split("HYDRO");
                String nehydro2[] = nehydro1[1].split(" ");
    
                String netotal1[] = neestern[2].split("TOTAL");
                String netotal2[] = netotal1[1].split(" ");
    
                writer.append("NORTH EASTERN" + ",");
                writer.append(year[0] + ",");
                writer.append(month[0] + ",");
                writer.append(nethermal2[4] + ",");
                writer.append(" " + ",");
                writer.append(nehydro2[4] + ",");
                writer.append(netotal2[4] + "\n");
                writer.close();
    
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
    
        }
    

    ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

    As the error says your router link should match the existing routes configured

    It should be just routerLink="/about"

    Is the practice of returning a C++ reference variable evil?

    You should return a reference to an existing object that isn't going away immediately, and where you don't intend any transfer of ownership.

    Never return a reference to a local variable or some such, because it won't be there to be referenced.

    You can return a reference to something independent of the function, which you don't expect the calling function to take the responsibility for deleting. This is the case for the typical operator[] function.

    If you are creating something, you should return either a value or a pointer (regular or smart). You can return a value freely, since it's going into a variable or expression in the calling function. Never return a pointer to a local variable, since it will go away.

    jQuery - find child with a specific class

    $(this).find(".bgHeaderH2").html();
    

    or

    $(this).find(".bgHeaderH2").text();
    

    Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

    Just go to https://www.lfd.uci.edu/~gohlke/pythonlibs/ find your suitable package (whl file). Download it. Go to the download folder in cmd or typing 'cmd' on the address bar of the folder. Run the command :

    pip install mysqlclient-1.4.6-cp38-cp38-win32.whl
    

    (Type the file name correctly. I have given an example only). Your problem will be solved without installing build toll cpp of 6GB size.

    Understanding lambda in python and using it to pass multiple arguments

    Why do you need to state both 'x' and 'y' before the ':'?

    Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to

    def f(x, y) : return x + y
    

    just without binding it to a name like f.

    Also how do you make it return multiple arguments?

    The same way like with a function. Preferably, you return a tuple:

    lambda x, y: (x+y, x-y)
    

    Or a list, or a class, or whatever.

    The thing with self.entry_1.bind should be answered by Demosthenex.

    Render Partial View Using jQuery in ASP.NET MVC

    You'll need to create an Action on your Controller that returns the rendered result of the "UserDetails" partial view or control. Then just use an Http Get or Post from jQuery to call the Action to get the rendered html to be displayed.

    JavaScript: Object Rename Key

    Your way is optimized, in my opinion. But you will end up with reordered keys. Newly created key will be appended at the end. I know you should never rely on key order, but if you need to preserve it, you will need to go through all keys and construct new object one by one, replacing the key in question during that process.

    Like this:

    var new_o={};
    for (var i in o)
    {
       if (i==old_key) new_o[new_key]=o[old_key];
       else new_o[i]=o[i];
    }
    o=new_o;
    

    Set the text in a span

    You need to fix your selector. Although CSS syntax requires multiple classes to be space separated, selector syntax would require them to be directly concatenated, and dot prefixed:

    $(".ui-icon.ui-icon-circle-triangle-w").text(...);
    

    or better:

    $(".ui-datepicker-prev > span").text(...);
    

    What is the difference between HTTP_HOST and SERVER_NAME in PHP?

    The HTTP_HOST is obtained from the HTTP request header and this is what the client actually used as "target host" of the request. The SERVER_NAME is defined in server config. Which one to use depends on what you need it for. You should now however realize that the one is a client-controlled value which may thus not be reliable for use in business logic and the other is a server-controlled value which is more reliable. You however need to ensure that the webserver in question has the SERVER_NAME correctly configured. Taking Apache HTTPD as an example, here's an extract from its documentation:

    If no ServerName is specified, then the server attempts to deduce the hostname by performing a reverse lookup on the IP address. If no port is specified in the ServerName, then the server will use the port from the incoming request. For optimal reliability and predictability, you should specify an explicit hostname and port using the ServerName directive.


    Update: after checking the answer of Pekka on your question which contains a link to bobince's answer that PHP would always return HTTP_HOST's value for SERVER_NAME, which goes against my own PHP 4.x + Apache HTTPD 1.2.x experiences from a couple of years ago, I blew some dust from my current XAMPP environment on Windows XP (Apache HTTPD 2.2.1 with PHP 5.2.8), started it, created a PHP page which prints the both values, created a Java test application using URLConnection to modify the Host header and tests taught me that this is indeed (incorrectly) the case.

    After first suspecting PHP and digging in some PHP bug reports regarding the subject, I learned that the root of the problem is in web server used, that it incorrectly returned HTTP Host header when SERVER_NAME was requested. So I dug into Apache HTTPD bug reports using various keywords regarding the subject and I finally found a related bug. This behaviour was introduced since around Apache HTTPD 1.3. You need to set UseCanonicalName directive to on in the <VirtualHost> entry of the ServerName in httpd.conf (also check the warning at the bottom of the document!).

    <VirtualHost *>
        ServerName example.com
        UseCanonicalName on
    </VirtualHost> 
    

    This worked for me.

    Summarized, SERVER_NAME is more reliable, but you're dependent on the server config!

    How to generate List<String> from SQL query?

    Or a nested List (okay, the OP was for a single column and this is for multiple columns..):

            //Base list is a list of fields, ie a data record
            //Enclosing list is then a list of those records, ie the Result set
            List<List<String>> ResultSet = new List<List<String>>();
    
            using (SqlConnection connection =
                new SqlConnection(connectionString))
            {
                // Create the Command and Parameter objects.
                SqlCommand command = new SqlCommand(qString, connection);
    
                // Create and execute the DataReader..
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    var rec = new List<string>();
                    for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
                    {                      
                        rec.Add(reader.GetString(i));
                    }
                    ResultSet.Add(rec);
    
                }
            }
    

    Mongoose: Find, modify, save

    Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:

    User.update({username: oldUsername}, {
        username: newUser.username, 
        password: newUser.password, 
        rights: newUser.rights
    }, function(err, numberAffected, rawResponse) {
       //handle it
    })
    

    jQuery multiple conditions within if statement

    Try

    if (!(i == 'InvKey' || i == 'PostDate')) {
    

    or

    if (i != 'InvKey' || i != 'PostDate') {
    

    that says if i does not equals InvKey OR PostDate

    How to generate a HTML page dynamically using PHP?

    It looks funny but it works.

    <?php 
    $file = 'newpage.html';
    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new person to the file
    $current .= "<!doctype html><html>
    <head><meta charset='utf-8'>
    <title>new file</title>
    </head><body><h3>New HTML file</h3>
    </body></html>
    ";
    // Write the contents back to the file
    file_put_contents($file, $current);
    ?>
    

    json_decode returns NULL after webservice call

    Yesterday I spent 2 hours on checking and fixing that error finally I found that in JSON string that I wanted to decode were '\' slashes. So the logical thing to do is to use stripslashes function or something similiar to different PL.

    Of course the best way is sill to print this var out and see what it becomes after json_decode, if it is null you can also use json_last_error() function to determine the error it will return integer but here are those int described:

    0 = JSON_ERROR_NONE

    1 = JSON_ERROR_DEPTH

    2 = JSON_ERROR_STATE_MISMATCH

    3 = JSON_ERROR_CTRL_CHAR

    4 = JSON_ERROR_SYNTAX

    5 = JSON_ERROR_UTF8

    In my case I got output of json_last_error() as number 4 so it is JSON_ERROR_SYNTAX. Then I went and take a look into the string it self which I wanted to convert and it had in last line:

    '\'title\' error ...'
    

    After that is really just an easy fix.

    $json = json_decode(stripslashes($response));
    if (json_last_error() == 0) { // you've got an object in $json}
    

    How to open child forms positioned within MDI parent in VB.NET?

    See this page for the solution! https://msdn.microsoft.com/en-us/library/7aw8zc76(v=vs.110).aspx

    I was able to implement the Child form inside the parent.

    In the Example below Form2 should change to the name of your child form. NewMDIChild.MdiParent=me is the main form since the control that opens (shows) the child form is the parent or Me.

    NewMDIChild.Show() is your child form since you associated your child form with Dim NewMDIChild As New Form2()

    Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click
       Dim NewMDIChild As New Form2()
       'Set the Parent Form of the Child window.
       NewMDIChild.MdiParent = Me
       'Display the new form.
       NewMDIChild.Show()
    End Sub
    

    Simple and it works.

    How to use cookies in Python Requests

    Summary (@Freek Wiekmeijer, @gtalarico) other's answer:

    Logic of Login

    • Many resource(pages, api) need authentication, then can access, otherwise 405 Not Allowed
    • Common authentication=grant access method are:
      • cookie
      • auth header
        • Basic xxx
        • Authorization xxx

    How use cookie in requests to auth

    1. first get/generate cookie
    2. send cookie for following request
    • manual set cookie in headers
    • auto process cookie by requests's
      • session to auto manage cookies
      • response.cookies to manually set cookies

    use requests's session auto manage cookies

    curSession = requests.Session() 
    # all cookies received will be stored in the session object
    
    payload={'username': "yourName",'password': "yourPassword"}
    curSession.post(firstUrl, data=payload)
    # internally return your expected cookies, can use for following auth
    
    # internally use previously generated cookies, can access the resources
    curSession.get(secondUrl)
    
    curSession.get(thirdUrl)
    

    manually control requests's response.cookies

    payload={'username': "yourName",'password': "yourPassword"}
    resp1 = requests.post(firstUrl, data=payload)
    
    # manually pass previously returned cookies into following request
    resp2 = requests.get(secondUrl, cookies= resp1.cookies)
    
    resp3 = requests.get(thirdUrl, cookies= resp2.cookies)
    

    How to set the allowed url length for a nginx request (error code: 414, uri too large)

    For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;

    You will need the sudo password.

    sudo nano /etc/nginx/conf.d/uploads.conf
    

    Replace contents with the following;

    fastcgi_buffers 8 16k;
    fastcgi_buffer_size 32k;
    
    client_max_body_size 24M;
    client_body_buffer_size 128k;
    
    client_header_buffer_size 5120k;
    large_client_header_buffers 16 5120k;
    

    Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

    Html.Partial: returns MvcHtmlString and slow

    Html.RenderPartial: directly render/write on output stream and returns void and it's very fast in comparison to Html.Partial

    Apply formula to the entire column

    Let's say you want to substitute something in an array of string and you don't want to perform the copy-paste on your entire sheet.

    Let's take this as an example:

    • String array in column "A": {apple, banana, orange, ..., avocado}
    • You want to substitute the char of "a" to "x" to have: {xpple, bxnxnx, orxnge, ..., xvocado}

    To apply this formula on the entire column (array) in a clean an elegant way, you can do:

    =ARRAYFORMULA(SUBSTITUE(A:A, "a", "x"))
    

    It works for 2D-arrays as well, let's say:

    =ARRAYFORMULA(SUBSTITUE(A2:D83, "a", "x"))
    

    How do I copy a version of a single file from one git branch to another?

    Following madlep's answer you can also just copy one directory from another branch with the directory blob.

    git checkout other-branch app/**
    

    As to the op's question if you've only changed one file in there this will work fine ^_^

    PHP passing $_GET in linux command prompt

    Try using WGET:

    WGET 'http://localhost/index.php?a=1&b=2&c=3'
    

    Java heap terminology: young, old and permanent generations?

    The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

    Uncaught SyntaxError: Unexpected token with JSON.parse

    If there are leading or trailing spaces, it'll be invalid. Trailing/Leading spaces can be removed as

    mystring = mystring.replace(/^\s+|\s+$/g, "");
    

    Source: http://www.toptip.ca/2010/02/javascript-trim-leading-or-trailing.html

    How to create a .gitignore file

    I realize this question is focused on how to "create" the gitignore file, but in case someone is interested in a quick way to add contents to the file once it is created, here is my answer for those trying to "ignore" files that appear in their changes list.

    1. Make the changes to your code which generate unwanted changes in your repository.
    2. Go to GitHub Desktop and to your repository.
    3. Select all the changes and right click them.
    4. Add your changes to the gitignore file.

    enter image description here

    What does it mean when a PostgreSQL process is "idle in transaction"?

    The PostgreSQL manual indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.

    If you're using Slony for replication, however, the Slony-I FAQ suggests idle in transaction may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details.

    How to read a file line-by-line into a list?

    with open(filename) as f:
        content = f.readlines()
    # you may also want to remove whitespace characters like `\n` at the end of each line
    content = [x.strip() for x in content] 
    

    write a shell script to ssh to a remote machine and execute commands

    There are a number of ways to handle this.

    My favorite way is to install http://pamsshagentauth.sourceforge.net/ on the remote systems and also your own public key. (Figure out a way to get these installed on the VM, somehow you got an entire Unix system installed, what's a couple more files?)

    With your ssh agent forwarded, you can now log in to every system without a password.

    And even better, that pam module will authenticate for sudo with your ssh key pair so you can run with root (or any other user's) rights as needed.

    You don't need to worry about the host key interaction. If the input is not a terminal then ssh will just limit your ability to forward agents and authenticate with passwords.

    You should also look into packages like Capistrano. Definitely look around that site; it has an introduction to remote scripting.

    Individual script lines might look something like this:

    ssh remote-system-name command arguments ... # so, for exmaple,
    ssh target.mycorp.net sudo puppet apply
    

    How to declare a structure in a header that is to be used by multiple files in c?

    if this structure is to be used by some other file func.c how to do it?

    When a type is used in a file (i.e. func.c file), it must be visible. The very worst way to do it is copy paste it in each source file needed it.

    The right way is putting it in an header file, and include this header file whenever needed.

    shall we open a new header file and declare the structure there and include that header in the func.c?

    This is the solution I like more, because it makes the code highly modular. I would code your struct as:

    #ifndef SOME_HEADER_GUARD_WITH_UNIQUE_NAME
    #define SOME_HEADER_GUARD_WITH_UNIQUE_NAME
    
    struct a
    { 
        int i;
        struct b
        {
            int j;
        }
    };
    
    #endif
    

    I would put functions using this structure in the same header (the function that are "semantically" part of its "interface").

    And usually, I could name the file after the structure name, and use that name again to choose the header guards defines.

    If you need to declare a function using a pointer to the struct, you won't need the full struct definition. A simple forward declaration like:

    struct a ;
    

    Will be enough, and it decreases coupling.

    or can we define the total structure in header file and include that in both source.c and func.c?

    This is another way, easier somewhat, but less modular: Some code needing only your structure to work would still have to include all types.

    In C++, this could lead to interesting complication, but this is out of topic (no C++ tag), so I won't elaborate.

    then how to declare that structure as extern in both the files. ?

    I fail to see the point, perhaps, but Greg Hewgill has a very good answer in his post How to declare a structure in a header that is to be used by multiple files in c?.

    shall we typedef it then how?

    • If you are using C++, don't.
    • If you are using C, you should.

    The reason being that C struct managing can be a pain: You have to declare the struct keyword everywhere it is used:

    struct MyStruct ; /* Forward declaration */
    
    struct MyStruct
    {
       /* etc. */
    } ;
    
    void doSomething(struct MyStruct * p) /* parameter */
    {
       struct MyStruct a ; /* variable */
       /* etc */
    }
    

    While a typedef will enable you to write it without the struct keyword.

    struct MyStructTag ; /* Forward declaration */
    
    typedef struct MyStructTag
    {
       /* etc. */
    } MyStruct ;
    
    void doSomething(MyStruct * p) /* parameter */
    {
       MyStruct a ; /* variable */
       /* etc */
    }
    

    It is important you still keep a name for the struct. Writing:

    typedef struct
    {
       /* etc. */
    } MyStruct ;
    

    will just create an anonymous struct with a typedef-ed name, and you won't be able to forward-declare it. So keep to the following format:

    typedef struct MyStructTag
    {
       /* etc. */
    } MyStruct ;
    

    Thus, you'll be able to use MyStruct everywhere you want to avoid adding the struct keyword, and still use MyStructTag when a typedef won't work (i.e. forward declaration)

    Edit:

    Corrected wrong assumption about C99 struct declaration, as rightfully remarked by Jonathan Leffler.

    Edit 2018-06-01:

    Craig Barnes reminds us in his comment that you don't need to keep separate names for the struct "tag" name and its "typedef" name, like I did above for the sake of clarity.

    Indeed, the code above could well be written as:

    typedef struct MyStruct
    {
       /* etc. */
    } MyStruct ;
    

    IIRC, this is actually what C++ does with its simpler struct declaration, behind the scenes, to keep it compatible with C:

    // C++ explicit declaration by the user
    struct MyStruct
    {
       /* etc. */
    } ;
    // C++ standard then implicitly adds the following line
    typedef MyStruct MyStruct;
    

    Back to C, I've seen both usages (separate names and same names), and none has drawbacks I know of, so using the same name makes reading simpler if you don't use C separate "namespaces" for structs and other symbols.

    Best way to make a shell script daemon?

    Just backgrounding your script (./myscript &) will not daemonize it. See http://www.faqs.org/faqs/unix-faq/programmer/faq/, section 1.7, which describes what's necessary to become a daemon. You must disconnect it from the terminal so that SIGHUP does not kill it. You can take a shortcut to make a script appear to act like a daemon;

    nohup ./myscript 0<&- &>/dev/null &
    

    will do the job. Or, to capture both stderr and stdout to a file:

    nohup ./myscript 0<&- &> my.admin.log.file &
    

    However, there may be further important aspects that you need to consider. For example:

    • You will still have a file descriptor open to the script, which means that the directory it's mounted in would be unmountable. To be a true daemon you should chdir("/") (or cd / inside your script), and fork so that the parent exits, and thus the original descriptor is closed.
    • Perhaps run umask 0. You may not want to depend on the umask of the caller of the daemon.

    For an example of a script that takes all of these aspects into account, see Mike S' answer.

    Hello World in Python

    print("Hello, World!")
    

    You are probably using Python 3.0, where print is now a function (hence the parenthesis) instead of a statement.

    Perl regular expression (using a variable as a search string with Perl operator characters included)

    Use \Q to autoescape any potentially problematic characters in your variable.

    if($text_to_search =~ m/\Q$search_string/) print "wee";
    

    how to POST/Submit an Input Checkbox that is disabled?

    <html>
        <head>
        <script type="text/javascript">
        function some_name() {if (document.getElementById('first').checked)      document.getElementById('second').checked=false; else document.getElementById('second').checked=true;} 
        </script>
        </head>
        <body onload="some_name();">
        <form>
        <input type="checkbox" id="first" value="first" onclick="some_name();"/>first<br/>
        <input type="checkbox" id="second" value="second" onclick="some_name();" />second
        </form>
        </body>
    </html>
    

    Function some_name is an example of a previous clause to manage the second checkbox which is checked (posts its value) or unchecked (does not post its value) according to the clause and the user cannot modify its status; there is no need to manage any disabling of second checkbox

    Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

    You can do this simply by using pandas drop duplicates function

    df.drop_duplicates(['A','B'],keep= 'last')
    

    How to delete a column from a table in MySQL

    To delete column use this,

    ALTER TABLE `tbl_Country` DROP `your_col`
    

    PHP ini file_get_contents external url

    Complementing Aillyn's answer, you could use a function like the one below to mimic the behavior of file_get_contents:

    function get_content($URL){
          $ch = curl_init();
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_URL, $URL);
          $data = curl_exec($ch);
          curl_close($ch);
          return $data;
    }
    
    echo get_content('http://example.com');
    

    Unescape HTML entities in Javascript?

    There is an variant that 80% as productive as the answers at the very top.

    See the benchmark: https://jsperf.com/decode-html12345678/1

    performance test

    _x000D_
    _x000D_
    console.log(decodeEntities('test: &gt'));_x000D_
    _x000D_
    function decodeEntities(str) {_x000D_
      // this prevents any overhead from creating the object each time_x000D_
      const el = decodeEntities.element || document.createElement('textarea')_x000D_
    _x000D_
      // strip script/html tags_x000D_
      el.innerHTML = str_x000D_
        .replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')_x000D_
        .replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');_x000D_
    _x000D_
      return el.value;_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    If you need to leave tags, then remove the two .replace(...) calls (you can leave the first one if you do not need scripts).

    Simple If/Else Razor Syntax

    Just use this for the closing tag:

      @:</tr>
    

    And leave your if/else as is.

    Seems like the if statement doesn't wanna' work.

    It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.

    How to extract text from a PDF file?

    PyPDF2 in some cases ignores the white spaces and makes the result text a mess, but I use PyMuPDF and I'm really satisfied you can use this link for more info

    Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

    I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.

    @GetMapping(value="/person/{id}/", 
                params="format=json",
                produces=MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Person> getPerson(@PathVariable Integer id){
        Person person = personMapRepository.findPerson(id);
        return ResponseEntity.ok(person);
    } 
    @GetMapping(value="/person/{id}/", 
                params="format=xml",
                produces=MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
        return GetPerson(id); // delegate
    }
    

    Getting a directory name from a filename

     auto p = boost::filesystem::path("test/folder/file.txt");
     std::cout << p.parent_path() << '\n';             // test/folder
     std::cout << p.parent_path().filename() << '\n';  // folder
     std::cout << p.filename() << '\n';                // file.txt
    

    You may need p.parent_path().filename() to get name of parent folder.

    Remove rows with all or some NAs (missing values) in data.frame

    I am a synthesizer:). Here I combined the answers into one function:

    #' keep rows that have a certain number (range) of NAs anywhere/somewhere and delete others
    #' @param df a data frame
    #' @param col restrict to the columns where you would like to search for NA; eg, 3, c(3), 2:5, "place", c("place","age")
    #' \cr default is NULL, search for all columns
    #' @param n integer or vector, 0, c(3,5), number/range of NAs allowed.
    #' \cr If a number, the exact number of NAs kept
    #' \cr Range includes both ends 3<=n<=5
    #' \cr Range could be -Inf, Inf
    #' @return returns a new df with rows that have NA(s) removed
    #' @export
    ez.na.keep = function(df, col=NULL, n=0){
        if (!is.null(col)) {
            # R converts a single row/col to a vector if the parameter col has only one col
            # see https://radfordneal.wordpress.com/2008/08/20/design-flaws-in-r-2-%E2%80%94-dropped-dimensions/#comments
            df.temp = df[,col,drop=FALSE]
        } else {
            df.temp = df
        }
    
        if (length(n)==1){
            if (n==0) {
                # simply call complete.cases which might be faster
                result = df[complete.cases(df.temp),]
            } else {
                # credit: http://stackoverflow.com/a/30461945/2292993
                log <- apply(df.temp, 2, is.na)
                logindex <- apply(log, 1, function(x) sum(x) == n)
                result = df[logindex, ]
            }
        }
    
        if (length(n)==2){
            min = n[1]; max = n[2]
            log <- apply(df.temp, 2, is.na)
            logindex <- apply(log, 1, function(x) {sum(x) >= min && sum(x) <= max})
            result = df[logindex, ]
        }
    
        return(result)
    }
    

    Anchor links in Angularjs?

    I had the same problem, but this worked for me:

    <a ng-href="javascript:void(0);#tagId"></a>
    

    Best way to unselect a <select> in jQuery?

    There are lots of answers here but unfortunately all of them are quite old and therefore rely on attr/removeAttr which is really not the way to go.

    @coffeeyesplease correctly mentions that a good, cross-browser solution is to use

    $("select").val([]);
    

    Another good cross-browser solution is

    // Note the use of .prop instead of .attr
    $("select option").prop("selected", false);
    

    You can see it run a self-test here. Tested on IE 7/8/9, FF 11, Chrome 19.

    Found shared references to a collection org.hibernate.HibernateException

    I faced similar exception in my application. After looking into the stacktrace it was clear that exception was thrown within a FlushEntityEventListener class.

    In Hibernate 4.3.7 the MSLocalSessionFactory bean no longer supports the eventListeners property. Hence, one has to explicitly fetch the service registry from individual Hibernate session beans and then set the required custom event listeners.

    In the process of adding custom event listeners we need to make sure the corresponding default event listeners are removed from the respective Hibernate session.

    If the default event listener is not removed then the case arises of two event listeners registered against same event. In this case while iterating over these listeners, against first listeners any collections in the session will be flagged as reached and while processing the same collection against second listener would throw this Hibernate exception.

    So, make sure that when registering custom listeners corresponding default listeners are removed from registry.

    Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

    btoa() only support characters from String.fromCodePoint(0) up to String.fromCodePoint(255). For Base64 characters with a code point 256 or higher you need to encode/decode these before and after.

    And in this point it becomes tricky...

    Every possible sign are arranged in a Unicode-Table. The Unicode-Table is divided in different planes (languages, math symbols, and so on...). Every sign in a plane has a unique code point number. Theoretically, the number can become arbitrarily large.

    A computer stores the data in bytes (8 bit, hexadecimal 0x00 - 0xff, binary 00000000 - 11111111, decimal 0 - 255). This range normally use to save basic characters (Latin1 range).

    For characters with higher codepoint then 255 exist different encodings. JavaScript use 16 bits per sign (UTF-16), the string called DOMString. Unicode can handle code points up to 0x10fffff. That means, that a method must be exist to store several bits over several cells away.

    String.fromCodePoint(0x10000).length == 2

    UTF-16 use surrogate pairs to store 20bits in two 16bit cells. The first higher surrogate begins with 110110xxxxxxxxxx, the lower second one with 110111xxxxxxxxxx. Unicode reserved own planes for this: https://unicode-table.com/de/#high-surrogates

    To store characters in bytes (Latin1 range) standardized procedures use UTF-8.

    Sorry to say that, but I think there is no other way to implement this function self.

    function stringToUTF8(str)
    {
        let bytes = [];
    
        for(let character of str)
        {
            let code = character.codePointAt(0);
    
            if(code <= 127)
            {
                let byte1 = code;
    
                bytes.push(byte1);
            }
            else if(code <= 2047)
            {
                let byte1 = 0xC0 | (code >> 6);
                let byte2 = 0x80 | (code & 0x3F);
    
                bytes.push(byte1, byte2);
            }
            else if(code <= 65535)
            {
                let byte1 = 0xE0 | (code >> 12);
                let byte2 = 0x80 | ((code >> 6) & 0x3F);
                let byte3 = 0x80 | (code & 0x3F);
    
                bytes.push(byte1, byte2, byte3);
            }
            else if(code <= 2097151)
            {
                let byte1 = 0xF0 | (code >> 18);
                let byte2 = 0x80 | ((code >> 12) & 0x3F);
                let byte3 = 0x80 | ((code >> 6) & 0x3F);
                let byte4 = 0x80 | (code & 0x3F);
    
                bytes.push(byte1, byte2, byte3, byte4);
            }
        }
    
        return bytes;
    }
    
    function utf8ToString(bytes, fallback)
    {
        let valid = undefined;
        let codePoint = undefined;
        let codeBlocks = [0, 0, 0, 0];
    
        let result = "";
    
        for(let offset = 0; offset < bytes.length; offset++)
        {
            let byte = bytes[offset];
    
            if((byte & 0x80) == 0x00)
            {
                codeBlocks[0] = byte & 0x7F;
    
                codePoint = codeBlocks[0];
            }
            else if((byte & 0xE0) == 0xC0)
            {
                codeBlocks[0] = byte & 0x1F;
    
                byte = bytes[++offset];
                if(offset >= bytes.length || (byte & 0xC0) != 0x80) { valid = false; break; }
    
                codeBlocks[1] = byte & 0x3F;
    
                codePoint = (codeBlocks[0] << 6) + codeBlocks[1];
            }
            else if((byte & 0xF0) == 0xE0)
            {
                codeBlocks[0] = byte & 0xF;
    
                for(let blockIndex = 1; blockIndex <= 2; blockIndex++)
                {
                    byte = bytes[++offset];
                    if(offset >= bytes.length || (byte & 0xC0) != 0x80) { valid = false; break; }
    
                    codeBlocks[blockIndex] = byte & 0x3F;
                }
                if(valid === false) { break; }
    
                codePoint = (codeBlocks[0] << 12) + (codeBlocks[1] << 6) + codeBlocks[2];
            }
            else if((byte & 0xF8) == 0xF0)
            {
                codeBlocks[0] = byte & 0x7;
    
                for(let blockIndex = 1; blockIndex <= 3; blockIndex++)
                {
                    byte = bytes[++offset];
                    if(offset >= bytes.length || (byte & 0xC0) != 0x80) { valid = false; break; }
    
                    codeBlocks[blockIndex] = byte & 0x3F;
                }
                if(valid === false) { break; }
    
                codePoint = (codeBlocks[0] << 18) + (codeBlocks[1] << 12) + (codeBlocks[2] << 6) + (codeBlocks[3]);
            }
            else
            {
                valid = false; break;
            }
    
            result += String.fromCodePoint(codePoint);
        }
    
        if(valid === false)
        {
            if(!fallback)
            {
                throw new TypeError("Malformed utf-8 encoding.");
            }
    
            result = "";
    
            for(let offset = 0; offset != bytes.length; offset++)
            {
                result += String.fromCharCode(bytes[offset] & 0xFF);
            }
        }
    
        return result;
    }
    
    function decodeBase64(text, binary)
    {
        if(/[^0-9a-zA-Z\+\/\=]/.test(text)) { throw new TypeError("The string to be decoded contains characters outside of the valid base64 range."); }
    
        let codePointA = 'A'.codePointAt(0);
        let codePointZ = 'Z'.codePointAt(0);
        let codePointa = 'a'.codePointAt(0);
        let codePointz = 'z'.codePointAt(0);
        let codePointZero = '0'.codePointAt(0);
        let codePointNine = '9'.codePointAt(0);
        let codePointPlus = '+'.codePointAt(0);
        let codePointSlash = '/'.codePointAt(0);
    
        function getCodeFromKey(key)
        {
            let keyCode = key.codePointAt(0);
    
            if(keyCode >= codePointA && keyCode <= codePointZ)
            {
                return keyCode - codePointA;
            }
            else if(keyCode >= codePointa && keyCode <= codePointz)
            {
                return keyCode + 26 - codePointa;
            }
            else if(keyCode >= codePointZero && keyCode <= codePointNine)
            {
                return keyCode + 52 - codePointZero;
            }
            else if(keyCode == codePointPlus)
            {
                return 62;
            }
            else if(keyCode == codePointSlash)
            {
                return 63;
            }
    
            return undefined;
        }
    
        let codes = Array.from(text).map(character => getCodeFromKey(character));
    
        let bytesLength = Math.ceil(codes.length / 4) * 3;
    
        if(codes[codes.length - 2] == undefined) { bytesLength = bytesLength - 2; } else if(codes[codes.length - 1] == undefined) { bytesLength--; }
    
        let bytes = new Uint8Array(bytesLength);
    
        for(let offset = 0, index = 0; offset < bytes.length;)
        {
            let code1 = codes[index++];
            let code2 = codes[index++];
            let code3 = codes[index++];
            let code4 = codes[index++];
    
            let byte1 = (code1 << 2) | (code2 >> 4);
            let byte2 = ((code2 & 0xf) << 4) | (code3 >> 2);
            let byte3 = ((code3 & 0x3) << 6) | code4;
    
            bytes[offset++] = byte1;
            bytes[offset++] = byte2;
            bytes[offset++] = byte3;
        }
    
        if(binary) { return bytes; }
    
        return utf8ToString(bytes, true);
    }
    
    function encodeBase64(bytes) {
        if (bytes === undefined || bytes === null) {
            return '';
        }
        if (bytes instanceof Array) {
            bytes = bytes.filter(item => {
                return Number.isFinite(item) && item >= 0 && item <= 255;
            });
        }
    
        if (
            !(
                bytes instanceof Uint8Array ||
                bytes instanceof Uint8ClampedArray ||
                bytes instanceof Array
            )
        ) {
            if (typeof bytes === 'string') {
                const str = bytes;
                bytes = Array.from(unescape(encodeURIComponent(str))).map(ch =>
                    ch.codePointAt(0)
                );
            } else {
                throw new TypeError('bytes must be of type Uint8Array or String.');
            }
        }
    
        const keys = [
            'A',
            'B',
            'C',
            'D',
            'E',
            'F',
            'G',
            'H',
            'I',
            'J',
            'K',
            'L',
            'M',
            'N',
            'O',
            'P',
            'Q',
            'R',
            'S',
            'T',
            'U',
            'V',
            'W',
            'X',
            'Y',
            'Z',
            'a',
            'b',
            'c',
            'd',
            'e',
            'f',
            'g',
            'h',
            'i',
            'j',
            'k',
            'l',
            'm',
            'n',
            'o',
            'p',
            'q',
            'r',
            's',
            't',
            'u',
            'v',
            'w',
            'x',
            'y',
            'z',
            '0',
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            '+',
            '/'
        ];
        const fillKey = '=';
    
        let byte1;
        let byte2;
        let byte3;
        let sign1 = ' ';
        let sign2 = ' ';
        let sign3 = ' ';
        let sign4 = ' ';
    
        let result = '';
    
        for (let index = 0; index < bytes.length; ) {
            let fillUpAt = 0;
    
            // tslint:disable:no-increment-decrement
            byte1 = bytes[index++];
            byte2 = bytes[index++];
            byte3 = bytes[index++];
    
            if (byte2 === undefined) {
                byte2 = 0;
                fillUpAt = 2;
            }
    
            if (byte3 === undefined) {
                byte3 = 0;
                if (!fillUpAt) {
                    fillUpAt = 3;
                }
            }
    
            // tslint:disable:no-bitwise
            sign1 = keys[byte1 >> 2];
            sign2 = keys[((byte1 & 0x3) << 4) + (byte2 >> 4)];
            sign3 = keys[((byte2 & 0xf) << 2) + (byte3 >> 6)];
            sign4 = keys[byte3 & 0x3f];
    
            if (fillUpAt > 0) {
                if (fillUpAt <= 2) {
                    sign3 = fillKey;
                }
                if (fillUpAt <= 3) {
                    sign4 = fillKey;
                }
            }
    
            result += sign1 + sign2 + sign3 + sign4;
    
            if (fillUpAt) {
                break;
            }
        }
    
        return result;
    }
    
    let base64 = encodeBase64("\u{1F604}"); // unicode code point escapes for smiley
    let str = decodeBase64(base64);
    
    console.log("base64", base64);
    console.log("str", str);
    
    document.body.innerText = str;
    

    how to use it: decodeBase64(encodeBase64("\u{1F604}"))

    demo: https://jsfiddle.net/qrLadeb8/

    check if variable is dataframe

    Use isinstance, nothing else:

    if isinstance(x, pd.DataFrame):
        ... # do something
    

    PEP8 says explicitly that isinstance is the preferred way to check types

    No:  type(x) is pd.DataFrame
    No:  type(x) == pd.DataFrame
    Yes: isinstance(x, pd.DataFrame)
    

    And don't even think about

    if obj.__class__.__name__ = 'DataFrame':
        expect_problems_some_day()
    

    isinstance handles inheritance (see What are the differences between type() and isinstance()?). For example, it will tell you if a variable is a string (either str or unicode), because they derive from basestring)

    if isinstance(obj, basestring):
        i_am_string(obj)
    

    Specifically for pandas DataFrame objects:

    import pandas as pd
    isinstance(var, pd.DataFrame)
    

    Password must have at least one non-alpha character

    An expression like this:

    [a-zA-Z]*[0-9\+\*][a-zA-Z0-9\+\*]*
    

    should work just fine (obviously insert any additional special characters you want to allow or use ^ operator to match anything except letters/numbers); no need to use complicated lookarounds. This approach makes sense if you only want to allow a certain subset of special characters that you know are "safe", and disallow all others.

    If you want to include all special characters except certain ones which you know are "unsafe", then it makes sense to use something like:

    \w[^\\]*[^a-zA-Z\\][^\\]*
    

    In this case, you are explicitly disallowing backslashes in your password and allowing any combination with at least one non-alphabetic character otherwise.

    The expression above will match any string containing letters and at least one number or +,*. As for the "length of 8" requirement, theres really no reason to check that using regex.

    Microsoft.ReportViewer.Common Version=12.0.0.0

    Version 12 of the ReportViewer bits is referred to as Microsoft Report Viewer 2015 Runtime and can downloaded for installation from the following link:

    https://www.microsoft.com/en-us/download/details.aspx?id=45496

    UPDATE:

    The ReportViewer bits are also available as a NUGET package: https://www.nuget.org/packages/Microsoft.ReportViewer.Runtime.Common/12.0.2402.15

    Install-Package Microsoft.ReportViewer.Runtime.Common

    int to unsigned int conversion

    Since we know that i is an int, you can just go ahead and unsigneding it!

    This would do the trick:

    int i = -62;
    unsigned int j = unsigned(i);
    

    pointer to array c++

    j[0]; dereferences a pointer to int, so its type is int.

    (*j)[0] has no type. *j dereferences a pointer to an int, so it returns an int, and (*j)[0] attempts to dereference an int. It's like attempting int x = 8; x[0];.

    How to add RSA key to authorized_keys file?

    I know I am replying too late but for anyone else who needs this, run following command from your local machine

    cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"
    

    this has worked perfectly fine. All you need to do is just to replace

    [email protected]

    with your own user for that particular host

    Access Control Request Headers, is added to header in AJAX request with jQuery

    Try to use the rack-cors gem. And add the header field in your Ajax call.

    Use of Custom Data Types in VBA

    It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

    This can be defined in a CLASS MODULE (here named clsTrucks)

    Option Explicit
    
    Private tID As String
    Private tNumberOfAxles As Double
    Private tAxleSpacings As Double
    
    
    Public Property Get truckID() As String
        truckID = tID
    End Property
    
    Public Property Let truckID(value As String)
        tID = value
    End Property
    
    Public Property Get truckNumberOfAxles() As Double
        truckNumberOfAxles = tNumberOfAxles
    End Property
    
    Public Property Let truckNumberOfAxles(value As Double)
        tNumberOfAxles = value
    End Property
    
    Public Property Get truckAxleSpacings() As Double
        truckAxleSpacings = tAxleSpacings
    End Property
    
    Public Property Let truckAxleSpacings(value As Double)
        tAxleSpacings = value
    End Property
    

    then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

    Option Explicit
    
    Public TruckCollection As New Collection
    
    Sub DefineNewTruck()
    Dim tempTruck As clsTrucks
    Dim i As Long
    
        'Add 5 trucks
        For i = 1 To 5
            Set tempTruck = New clsTrucks
            'Random data
            tempTruck.truckID = "Truck" & i
            tempTruck.truckAxleSpacings = 13.5 + i
            tempTruck.truckNumberOfAxles = 20.5 + i
    
            'tempTruck.truckID is the collection key
            TruckCollection.Add tempTruck, tempTruck.truckID
        Next i
    
        'retrieve 5 trucks
        For i = 1 To 5
            'retrieve by collection index
            Debug.Print TruckCollection(i).truckAxleSpacings
            'retrieve by key
            Debug.Print TruckCollection("Truck" & i).truckAxleSpacings
    
        Next i
    
    End Sub
    

    There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

    git - remote add origin vs remote set-url origin

    git remote add => ADDS a new remote.

    git remote set-url => UPDATES existing remote.


    1. The remote name that comes after add is a new remote name that did not exist prior to that command.
    2. The remote name that comes after set-url should already exist as a remote name to your repository.

    git remote add myupstream someurl => myupstream remote name did not exist now creating it with this command.

    git remote set-url upstream someurl => upstream remote name already exist i'm just changing it's url.


    git remote add myupstream https://github.com/nodejs/node => **ADD** If you don't already have upstream
    git remote set-url upstream https://github.com/nodejs/node # => **UPDATE** url for upstream
    

    How to set image name in Dockerfile?

    Here is another version if you have to reference a specific docker file:

    version: "3"
    services:
      nginx:
        container_name: nginx
        build:
          context: ../..
          dockerfile: ./docker/nginx/Dockerfile
        image: my_nginx:latest
    

    Then you just run

    docker-compose build
    

    Pandas groupby: How to get a union of strings

    Following @Erfan's good answer, most of the times in an analysis of aggregate values you want the unique possible combinations of these existing character values:

    unique_chars = lambda x: ', '.join(x.unique())
    (df
     .groupby(['A'])
     .agg({'C': unique_chars}))
    

    generate model using user:references vs user_id:integer

    Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:

    :001 > Micropost
    => Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)
    

    The second command adds a belongs_to :user relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id column and it will use a model named User to instantiate the specific user.

    The second command also adds an index on the new user_id column.

    MySQL GROUP BY two columns

    Using Concat on the group by will work

    SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
    FROM clients, portfolios
    WHERE clients.id = portfolios.client_id
    GROUP BY CONCAT(portfolios.id, "-", clients.id)
    ORDER BY total DESC
    LIMIT 30
    

    Trying to get property of non-object - Laravel 5

    I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:

    First, as suggested by Jimmy Zoto, my code in blade from

    $article->poster->name 
    

    to

    $article->poster['name']
    

    Next is to add a second parameter in my belongsTo, from

    return $this->belongsTo('App\User');
    

    to

    return $this->belongsTo('App\User', 'user_id');
    

    in which user_id is my foreign key in the news table.

    Uploading into folder in FTP?

    The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

    You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

    Docker command can't connect to Docker daemon

    For OSX:

    After opening docker and starting the 'default' machine via the Quickstart Terminal (https://docs.docker.com/engine/installation/mac/), you try docker commands and get this "can't connect to docker daemon" message, it turns out you need some env variables set:

    eval "$(docker-machine env default)"

    Then try it out with docker run hello-world to see if everything is peachy.

    C string append

    You could use asprintf to concatenate both into a new string:

    char *new_str;
    asprintf(&new_str,"%s%s",str1,str2);
    

    Grunt watch error - Waiting...Fatal error: watch ENOSPC

    In my case I found that I have an aggressive plugin for Vim, just restarted it.

    What is the reason for a red exclamation mark next to my project in Eclipse?

    Solutin 1:

    step:1

    Right click on your project -> Close Project. it will Close your project and all opened file(s) of the project

    step:2

    Right click on your project -> Open Project. it will Open your project and rebuild your project, Hope fully it will fix red exclamation mark

    Solution 2:

    Step:1

    Right click on your Project -> Properties -> Java Build Path. Can you see missing in front of your library file(s) as per following screen-shot

    Step:2 Click on Add Jar to select your Jar file if it is the placed in WEB-INF/lib of your project or Add External Jar if jar file placed somewhere on your computer

    Step:3 Select the old missing file(s) and click on Remove click here for image

    Solutioin 3: Right click on your Project -> Properties -> Java Build Path -> JRE System Library and reconfigure the JRE

    and go to your project and remove .properties and .classpath in your project directories.

    backup your project data and create a new one and follow the solutions 1 & 2