Programs & Examples On #Ncommon

How does one set up the Visual Studio Code compiler/debugger to GCC?

Caution

A friendly reminder: The following tutorial is for Linux user instead of Windows

Tutorial

If you want to debug your c++ code with GDB

You can read this ( Debugging your code ) article from Visual Studio Code official website.

Step 1: Compilation

You need to set up task.json for compilation of your cpp file

or simply type in the following command in the command window

g++ -g file.cpp -o file.exe

to generate a debuggable .exe file

Step 2: Set up the launch.json file

To enable debugging, you will need to generate a launch.json file

follow the launch.json example or google others

Step 3: Press (Ctrl+F5) to start compiling

this launch.json file will launch the configuration when you press the shortcut (Ctrl+F5)

Enjoy it!

ps. For those who want to set up tasks.json, you can read this from vscode official (-> TypeScript Hello World)

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

I had this issue with JetBrains Rider, specifically for port 80 and 90 bit it was working with other ports as well as visual studio.

after running as admin this resolved the issue.

Invalidating JSON Web Tokens

If you are using axios or a similar promise-based http request lib you can simply destroy token on the front-end inside the .then() part. It will be launched in the response .then() part after user executes this function (result code from the server endpoint must be ok, 200). After user clicks this route while searching for data, if database field user_enabled is false it will trigger destroying token and user will immediately be logged-off and stopped from accessing protected routes/pages. We don't have to await for token to expire while user is permanently logged on.

function searchForData() {   // front-end js function, user searches for the data
    // protected route, token that is sent along http request for verification
    var validToken = 'Bearer ' + whereYouStoredToken; // token stored in the browser 

    // route will trigger destroying token when user clicks and executes this func
    axios.post('/my-data', {headers: {'Authorization': validToken}})
     .then((response) => {
   // If Admin set user_enabled in the db as false, we destroy token in the browser localStorage
       if (response.data.user_enabled === false) {  // user_enabled is field in the db
           window.localStorage.clear();  // we destroy token and other credentials
       }  
    });
     .catch((e) => {
       console.log(e);
    });
}

Hibernate Error: a different object with the same identifier value was already associated with the session

I agree with @Hemant Kumar, thank you very much. According his solution, I solved my problem.

For example:

@Test
public void testSavePerson() {
    try (Session session = sessionFactory.openSession()) {
        Transaction tx = session.beginTransaction();
        Person person1 = new Person();
        Person person2 = new Person();
        person1.setName("222");
        person2.setName("111");
        session.save(person1);
        session.save(person2);
        tx.commit();
    }
}

Person.java

public class Person {
    private int id;
    private String name;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

This code always make mistake in my application: A different object with the same identifier value was already associated with the session, later I found out that I forgot to autoincrease my primary key!

My solution is to add this code on your primary key:

@GeneratedValue(strategy = GenerationType.AUTO)

Convert this string to datetime

Use DateTime::createFromFormat

$date = date_create_from_format('d/m/Y:H:i:s', $s);
$date->getTimestamp();

Comparing two arrays & get the values which are not common

Collection

$a = 1..5
$b = 4..8

$Yellow = $a | Where {$b -NotContains $_}

$Yellow contains all the items in $a except the ones that are in $b:

PS C:\> $Yellow
1
2
3

$Blue = $b | Where {$a -NotContains $_}

$Blue contains all the items in $b except the ones that are in $a:

PS C:\> $Blue
6
7
8

$Green = $a | Where {$b -Contains $_}

Not in question, but anyways; Green contains the items that are in both $a and $b.

PS C:\> $Green
4
5

Note: Where is an alias of Where-Object. Alias can introduce possible problems and make scripts hard to maintain.


Addendum 12 October 2019

As commented by @xtreampb and @mklement0: although not shown from the example in the question, the task that the question implies (values "not in common") is the symmetric difference between the two input sets (the union of yellow and blue).

Union

The symmetric difference between the $a and $b can be literally defined as the union of $Yellow and $Blue:

$NotGreen = $Yellow + $Blue

Which is written out:

$NotGreen = ($a | Where {$b -NotContains $_}) + ($b | Where {$a -NotContains $_})

Performance

As you might notice, there are quite some (redundant) loops in this syntax: all items in list $a iterate (using Where) through items in list $b (using -NotContains) and visa versa. Unfortunately the redundancy is difficult to avoid as it is difficult to predict the result of each side. A Hash Table is usually a good solution to improve the performance of redundant loops. For this, I like to redefine the question: Get the values that appear once in the sum of the collections ($a + $b):

$Count = @{}
$a + $b | ForEach-Object {$Count[$_] += 1}
$Count.Keys | Where-Object {$Count[$_] -eq 1}

By using the ForEach statement instead of the ForEach-Object cmdlet and the Where method instead of the Where-Object you might increase the performance by a factor 2.5:

$Count = @{}
ForEach ($Item in $a + $b) {$Count[$Item] += 1}
$Count.Keys.Where({$Count[$_] -eq 1})

LINQ

But Language Integrated Query (LINQ) will easily beat any native PowerShell and native .Net methods (see also High Performance PowerShell with LINQ and mklement0's answer for Can the following Nested foreach loop be simplified in PowerShell?:

To use LINQ you need to explicitly define the array types:

[Int[]]$a = 1..5
[Int[]]$b = 4..8

And use the [Linq.Enumerable]:: operator:

$Yellow   = [Int[]][Linq.Enumerable]::Except($a, $b)
$Blue     = [Int[]][Linq.Enumerable]::Except($b, $a)
$Green    = [Int[]][Linq.Enumerable]::Intersect($a, $b)
$NotGreen = [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))

Benchmark

Benchmark results highly depend on the sizes of the collections and how many items there are actually shared, as a "average", I am presuming that half of each collection is shared with the other.

Using             Time
Compare-Object    111,9712
NotContains       197,3792
ForEach-Object    82,8324
ForEach Statement 36,5721
LINQ              22,7091

To get a good performance comparison, caches should be cleared by e.g. starting a fresh PowerShell session.

$a = 1..1000
$b = 500..1500

(Measure-Command {
    Compare-Object -ReferenceObject $a -DifferenceObject $b  -PassThru
}).TotalMilliseconds
(Measure-Command {
    ($a | Where {$b -NotContains $_}), ($b | Where {$a -NotContains $_})
}).TotalMilliseconds
(Measure-Command {
    $Count = @{}
    $a + $b | ForEach-Object {$Count[$_] += 1}
    $Count.Keys | Where-Object {$Count[$_] -eq 1}
}).TotalMilliseconds

(Measure-Command {
    $Count = @{}
    ForEach ($Item in $a + $b) {$Count[$Item] += 1}
    $Count.Keys.Where({$Count[$_] -eq 1})
}).TotalMilliseconds

[Int[]]$a = $a
[Int[]]$b = $b
(Measure-Command {
    [Int[]]([Linq.Enumerable]::Except($a, $b) + [Linq.Enumerable]::Except($b, $a))
}).TotalMilliseconds

Is it a good practice to place C++ definitions in header files?

To add more fun you can add .ipp files which contain the template implementation (that is being included in .hpp), while .hpp contains the interface.

As apart from templatized code (depending on the project this can be majority or minority of files) there is normal code and here it is better to separate the declarations and definitions. Provide also forward-declarations where needed - this may have effect on the compilation time.

RegEx for matching UK Postcodes

First half of postcode Valid formats

  • [A-Z][A-Z][0-9][A-Z]
  • [A-Z][A-Z][0-9][0-9]
  • [A-Z][0-9][0-9]
  • [A-Z][A-Z][0-9]
  • [A-Z][A-Z][A-Z]
  • [A-Z][0-9][A-Z]
  • [A-Z][0-9]

Exceptions
Position 1 - QVX not used
Position 2 - IJZ not used except in GIR 0AA
Position 3 - AEHMNPRTVXY only used
Position 4 - ABEHMNPRVWXY

Second half of postcode

  • [0-9][A-Z][A-Z]

Exceptions
Position 2+3 - CIKMOV not used

Remember not all possible codes are used, so this list is a necessary but not sufficent condition for a valid code. It might be easier to just match against a list of all valid codes?

How to deal with a slow SecureRandom generator?

The problem you referenced about /dev/random is not with the SecureRandom algorithm, but with the source of randomness that it uses. The two are orthogonal. You should figure out which one of the two is slowing you down.

Uncommon Maths page that you linked explicitly mentions that they are not addressing the source of randomness.

You can try different JCE providers, such as BouncyCastle, to see if their implementation of SecureRandom is faster.

A brief search also reveals Linux patches that replace the default implementation with Fortuna. I don't know much more about this, but you're welcome to investigate.

I should also mention that while it's very dangerous to use a badly implemented SecureRandom algorithm and/or randomness source, you can roll your own JCE Provider with a custom implementation of SecureRandomSpi. You will need to go through a process with Sun to get your provider signed, but it's actually pretty straightforward; they just need you to fax them a form stating that you're aware of the US export restrictions on crypto libraries.

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

Cannot find "Package Explorer" view in Eclipse

You might be in debug mode. If this is the problem, you can simply click on the "Java" button (next to the "Debug" button) in the upper-right hand corner, or click on "Open Perspective" and then select "Java (default)" from the "Open Perspective" window.

Execute a terminal command from a Cocoa app

Here's how to do it in Swift

Changes for Swift 3.0:

  • NSPipe has been renamed Pipe

  • NSTask has been renamed Process


This is based on inkit's Objective-C answer above. He wrote it as a category on NSString — For Swift, it becomes an extension of String.

extension  String.runAsCommand()  ->  String

extension String {
    func runAsCommand() -> String {
        let pipe = Pipe()
        let task = Process()
        task.launchPath = "/bin/sh"
        task.arguments = ["-c", String(format:"%@", self)]
        task.standardOutput = pipe
        let file = pipe.fileHandleForReading
        task.launch()
        if let result = NSString(data: file.readDataToEndOfFile(), encoding: String.Encoding.utf8.rawValue) {
            return result as String
        }
        else {
            return "--- Error running command - Unable to initialize string from file data ---"
        }
    }
}

Usage:

let input = "echo hello"
let output = input.runAsCommand()
print(output)                        // prints "hello"

    or just:

print("echo hello".runAsCommand())   // prints "hello" 

Example:

@IBAction func toggleFinderShowAllFiles(_ sender: AnyObject) {

    var newSetting = ""
    let readDefaultsCommand = "defaults read com.apple.finder AppleShowAllFiles"

    let oldSetting = readDefaultsCommand.runAsCommand()

    // Note: the Command results are terminated with a newline character

    if (oldSetting == "0\n") { newSetting = "1" }
    else { newSetting = "0" }

    let writeDefaultsCommand = "defaults write com.apple.finder AppleShowAllFiles \(newSetting) ; killall Finder"

    _ = writeDefaultsCommand.runAsCommand()

}

Note the Process result as read from the Pipe is an NSString object. It might be an error string and it can also be an empty string, but it should always be an NSString.

So, as long as it's not nil, the result can cast as a Swift String and returned.

If for some reason no NSString at all can be initialized from the file data, the function returns an error message. The function could have been written to return an optional String?, but that would be awkward to use and wouldn't serve a useful purpose because it's so unlikely for this to occur.

Is there an easy way to attach source in Eclipse?

Short answer would be yes.

You can attach source using the properties for a project.

Go to Properties (for the Project) -> Java Build Path -> Libraries

Select the Library you want to attach source/javadoc for and then expand it, you'll see a list like so:

Source Attachment: (none)
Javadoc location: (none)
Native library location: (none)
Access rules: (No restrictions)

Select Javadoc location and then click Edit on the right hahnd side. It should be quite straight forward from there.

Good luck :)

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

As mentioned by Dan Abramov

Do it right inside render

We actually use that approach with memoise one for any kind of proxying props to state calculations.

Our code looks this way

// ./decorators/memoized.js  
import memoizeOne from 'memoize-one';

export function memoized(target, key, descriptor) {
  descriptor.value = memoizeOne(descriptor.value);
  return descriptor;
}

// ./components/exampleComponent.js
import React from 'react';
import { memoized } from 'src/decorators';

class ExampleComponent extends React.Component {
  buildValuesFromProps() {
    const {
      watchedProp1,
      watchedProp2,
      watchedProp3,
      watchedProp4,
      watchedProp5,
    } = this.props
    return {
      value1: buildValue1(watchedProp1, watchedProp2),
      value2: buildValue2(watchedProp1, watchedProp3, watchedProp5),
      value3: buildValue3(watchedProp3, watchedProp4, watchedProp5),
    }
  }

  @memoized
  buildValue1(watchedProp1, watchedProp2) {
    return ...;
  }

  @memoized
  buildValue2(watchedProp1, watchedProp3, watchedProp5) {
    return ...;
  }

  @memoized
  buildValue3(watchedProp3, watchedProp4, watchedProp5) {
    return ...;
  }

  render() {
    const {
      value1,
      value2,
      value3
    } = this.buildValuesFromProps();

    return (
      <div>
        <Component1 value={value1}>
        <Component2 value={value2}>
        <Component3 value={value3}>
      </div>
    );
  }
}

The benefits of it are that you don't need to code tons of comparison boilerplate inside getDerivedStateFromProps or componentWillReceiveProps and you can skip copy-paste initialization inside a constructor.

NOTE:

This approach is used only for proxying the props to state, in case you have some inner state logic it still needs to be handled in component lifecycles.

How to stretch in width a WPF user control to its window?

The Canvas in WPF doesn't provide much automatic layout support. I try to steer clear of them for this reason (HorizontalAlignment and VerticalAlignment don't work as expected), but I got your code to work with these minor modifications (binding the Width and Height of the control to the canvas's ActualWidth/ActualHeight).

<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load" 
ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" 
WindowState="Maximized" Focusable="True" x:Name="windowOperacao">

<Canvas x:Name="canv">
    <Grid>
        <tci:Status x:Name="ucStatus" Width="{Binding ElementName=canv
                                                    , Path=ActualWidth}" 
                                      Height="{Binding ElementName=canv
                                                    , Path=ActualHeight}"/> 
        <!-- the control which I want to stretch in width -->
    </Grid>
</Canvas>

The Canvas is the problem here. If you're not actually utilizing the features the canvas offers in terms of layout or Z-Order "squashing" (think of the flatten command in PhotoShop), I would consider using a control like a Grid instead so you don't end up having to learn the quirks of a control that works differently than you have come to expect with WPF.

jQuery rotate/transform

Why not just use, toggleClass on click?

js:

$(this).toggleClass("up");

css:

button.up {
    -webkit-transform: rotate(180deg);
       -moz-transform: rotate(180deg);
        -ms-transform: rotate(180deg);
         -o-transform: rotate(180deg);
            transform: rotate(180deg);
               /* IE6–IE9 */
               filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9914448613738104, M12=-0.13052619222005157,M21=0.13052619222005157, M22=0.9914448613738104, sizingMethod='auto expand');
                 zoom: 1;
    }

you can also add this to the css:

button{
        -webkit-transition: all 500ms ease-in-out;
        -moz-transition: all 500ms ease-in-out;
        -o-transition: all 500ms ease-in-out;
        -ms-transition: all 500ms ease-in-out;
}

which will add the animation.

PS...

to answer your original question:

you said that it rotates but never stops. When using set timeout you need to make sure you have a condition that will not call settimeout or else it will run forever. So for your code:

<script type="text/javascript">
    $(function() {
     var $elie = $("#bkgimg");
     rotate(0);
     function rotate(degree) {

      // For webkit browsers: e.g. Chrome
    $elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
      // For Mozilla browser: e.g. Firefox
    $elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});


    /* add a condition here for the extremity */ 
    if(degree < 180){
      // Animate rotation with a recursive call
      setTimeout(function() { rotate(++degree); },65);
     }
    }
    });
    </script>

jQuery - Get Width of Element when Not Visible (Display: None)

As has been said before, the clone and attach elsewhere method does not guarantee the same results as styling may be different.

Below is my approach. It travels up the parents looking for the parent responsible for the hiding, then temporarily unhides it to calculate the required width, height, etc.

_x000D_
_x000D_
    var width = parseInt($image.width(), 10);_x000D_
    var height = parseInt($image.height(), 10);_x000D_
_x000D_
    if (width === 0) {_x000D_
_x000D_
        if ($image.css("display") === "none") {_x000D_
_x000D_
            $image.css("display", "block");_x000D_
            width = parseInt($image.width(), 10);_x000D_
            height = parseInt($image.height(), 10);_x000D_
            $image.css("display", "none");_x000D_
        }_x000D_
        else {_x000D_
_x000D_
            $image.parents().each(function () {_x000D_
_x000D_
                var $parent = $(this);_x000D_
                if ($parent.css("display") === "none") {_x000D_
_x000D_
                    $parent.css("display", "block");_x000D_
                    width = parseInt($image.width(), 10);_x000D_
                    height = parseInt($image.height(), 10);_x000D_
                    $parent.css("display", "none");_x000D_
                }_x000D_
            });_x000D_
        }_x000D_
    }
_x000D_
_x000D_
_x000D_

JavaScript private methods

In these situations when you have a public API, and you would like private and public methods/properties, I always use the Module Pattern. This pattern was made popular within the YUI library, and the details can be found here:

http://yuiblog.com/blog/2007/06/12/module-pattern/

It is really straightforward, and easy for other developers to comprehend. For a simple example:

var MYLIB = function() {  
    var aPrivateProperty = true;
    var aPrivateMethod = function() {
        // some code here...
    };
    return {
        aPublicMethod : function() {
            aPrivateMethod(); // okay
            // some code here...
        },
        aPublicProperty : true
    };  
}();

MYLIB.aPrivateMethod() // not okay
MYLIB.aPublicMethod() // okay

MySql export schema without data

Yes, you can use mysqldump with the --no-data option:

mysqldump -u user -h localhost --no-data -p database > database.sql

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

This will work:

DECLARE @MS INT = 235216
select cast(dateadd(ms, @MS, '00:00:00') AS TIME(3))

(where ms is just a number of seconds not a timeformat)

How can I increase the size of a bootstrap button?

Default Bootstrap size classes

You can use btn-lg, btn-sm and btn-xs classes for manipulating with its size.

btn-block

Also, there is a class btn-block which will extend your button to the whole block. It is very convenient in combination with Bootstrap grid.
For example, this code will show a button with the width equal to half of screen for medium and large screens; and will show a full-width button for small screens:

<div class="container">
    <div class="col-xs-12 col-xs-offset-0 col-sm-offset-3 col-sm-6">
        <button class="btn btn-group">Click me!</button>
    </div>
</div>

Check this JSFiddle out. Try to resize frame.

If it is not enough, you can easily create your custom class.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

It's security all about. Make sure you have double check your firewall (windows and anti virus) in some cases when you disabled av firewall and restart your computer, automatically windows firewall is active and it's still block your application. Hope this is helpful ..

break/exit script

This is an old question but there is no a clean solution yet. This probably is not answering this specific question, but those looking for answers on 'how to gracefully exit from an R script' will probably land here. It seems that R developers forgot to implement an exit() function. Anyway, the trick I've found is:

continue <- TRUE

tryCatch({
     # You do something here that needs to exit gracefully without error.
     ...

     # We now say bye-bye         
     stop("exit")

}, error = function(e) {
    if (e$message != "exit") {
        # Your error message goes here. E.g.
        stop(e)
    }

    continue <<-FALSE
})

if (continue) {
     # Your code continues here
     ...
}

cat("done.\n")

Basically, you use a flag to indicate the continuation or not of a specified block of code. Then you use the stop() function to pass a customized message to the error handler of a tryCatch() function. If the error handler receives your message to exit gracefully, then it just ignores the error and set the continuation flag to FALSE.

Import data.sql MySQL Docker Container

do docker cp file.sql <CONTAINER NAME>:/file.sql first

then docker exec -i <CONTAINER NAME> mysql -u user -p

then inside mysql container execute source \file.sql

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

If you don't want to change the domain-wide default timeout, your best option is to change the deployment descriptor by setting the trans-timeout-seconds attribute in the weblogic-ejb-jar.xml - see http://docs.oracle.com/cd/E11035_01/wls100/jta/trxejb.html

This overrides the "Timeout Seconds" default, only for this specific EJB, while leaving all other EJB unaffected.

No connection could be made because the target machine actively refused it (PHP / WAMP)

Till yesterday I was able to connect to phpMyAdmin, but today I started getting this error:

2002-no-connection-could-be-made-because-the-target-machine-actively-refused

None of the answers here really helped me fix the problem, what helped me is shared below:

I looked at the mysql logs.[C:\wamp\logs\mysql.log]

It said

2015-09-18 01:16:30 5920 [Note] Plugin 'FEDERATED' is disabled.
2015-09-18 01:16:30 5920 [Note] InnoDB: Using atomics to ref count buffer pool pages
2015-09-18 01:16:30 5920 [Note] InnoDB: The InnoDB memory heap is disabled
2015-09-18 01:16:30 5920 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-09-18 01:16:30 5920 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-09-18 01:16:30 5920 [Note] InnoDB: Not using CPU crc32 instructions
2015-09-18 01:16:30 5920 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2015-09-18 01:16:30 5920 [Note] InnoDB: Completed initialization of buffer pool
2015-09-18 01:16:30 5920 [Note] InnoDB: Highest supported file format is Barracuda.
2015-09-18 01:16:30 5920 [Note] InnoDB: The log sequence numbers 1765410 and 1765410 in ibdata files do not match the log sequence number 2058233 in the ib_logfiles!
2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!
2015-09-18 01:16:30 5920 [Note] InnoDB: Starting crash recovery.
2015-09-18 01:16:30 5920 [Note] InnoDB: Reading tablespace information from the .ibd files...
2015-09-18 01:16:30 5920 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace harley/login_confirm uses space ID: 6 at filepath: .\harley\login_confirm.ibd. Cannot open tablespace testdb/testtable which uses space ID: 6 at filepath: .\testdb\testtable.ibd
InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.

I got the clue that this guy is creating a problem - InnoDB: Error: could not open single-table tablespace file .\testdb\testtable.ibd

and this line 2015-09-18 01:16:30 5920 [Note] InnoDB: Database was not shutdown normally!

hmmm, For me the testdb was just a test-db! hence I decided to delete this file inside C:\wamp\bin\mysql\mysql5.6.17\data\testdb

and restarted all services, and went to phpMyAdmin, and this time no issues, phpMyAdmin opened :)

How to find first element of array matching a boolean condition in JavaScript?

It should be clear by now that JavaScript offers no such solution natively; here are the closest two derivatives, the most useful first:

  1. Array.prototype.some(fn) offers the desired behaviour of stopping when a condition is met, but returns only whether an element is present; it's not hard to apply some trickery, such as the solution offered by Bergi's answer.

  2. Array.prototype.filter(fn)[0] makes for a great one-liner but is the least efficient, because you throw away N - 1 elements just to get what you need.

Traditional search methods in JavaScript are characterized by returning the index of the found element instead of the element itself or -1. This avoids having to choose a return value from the domain of all possible types; an index can only be a number and negative values are invalid.

Both solutions above don't support offset searching either, so I've decided to write this:

(function(ns) {
  ns.search = function(array, callback, offset) {
    var size = array.length;

    offset = offset || 0;
    if (offset >= size || offset <= -size) {
      return -1;
    } else if (offset < 0) {
      offset = size - offset;
    }

    while (offset < size) {
      if (callback(array[offset], offset, array)) {
        return offset;
      }
      ++offset;
    }
    return -1;
  };
}(this));

search([1, 2, NaN, 4], Number.isNaN); // 2
search([1, 2, 3, 4], Number.isNaN); // -1
search([1, NaN, 3, NaN], Number.isNaN, 2); // 3

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Is there an easy way to add a border to the top and bottom of an Android View?

Just to add my solution to the list..

I wanted a semi transparent bottom border that extends past the original shape (So the semi-transparent border was outside the parent rectangle).

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
  <item>
    <shape android:shape="rectangle" >      
      <solid android:color="#33000000" /> <!-- Border colour -->
    </shape>
  </item>
  <item  android:bottom="2dp" >
    <shape android:shape="rectangle" >     
      <solid android:color="#164586" />
    </shape>
  </item>
</layer-list>

Which gives me;

enter image description here

Apache: "AuthType not set!" 500 Error

The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?

Require all granted is only in 2.4, but Allow all ... stops working in 2.4, and we want to be able to rollout a config that works in both.

The only solution I found, which I am not sure is the proper one, is to use:

# backwards compatibility with apache 2.2
Order allow,deny
Allow from all

# forward compatibility with apache 2.4
Require all granted
Satisfy Any

This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...

See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.

Passing a URL with brackets to curl

Globbing uses brackets, hence the need to escape them with a slash \. Alternatively, the following command-line switch will disable globbing:

--globoff (or the short-option version: -g)

Ex:

curl --globoff https://www.google.com?test[]=1

HTTP Basic Authentication credentials passed in URL and encryption

Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs

Yes, yes yes.

The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.

Android Service Stops When App Is Closed

Using the same process for the service and the activity and START_STICKY or START_REDELIVER_INTENT in the service is the only way to be able to restart the service when the application restarts, which happens when the user closes the application for example, but also when the system decides to close it for optimisations reasons. You CAN NOT have a service that will run permanently without any interruption. This is by design, smartphones are not made to run continuous processes for long period of time. This is due to the fact that battery life is the highest priority. You need to design your service so it handles being stopped at any point.

npm behind a proxy fails with status 403

npm config set proxy http://proxy.company.com:8080
npm config set https-proxy http://proxy.company.com:8080

credit goes to http://jjasonclark.com/how-to-setup-node-behind-web-proxy.

Most efficient way to convert an HTMLCollection to an Array

not sure if this is the most efficient, but a concise ES6 syntax might be:

let arry = [...htmlCollection] 

Edit: Another one, from Chris_F comment:

let arry = Array.from(htmlCollection)

How to conditionally take action if FINDSTR fails to find a string

You are not evaluating a condition for the IF. I am guessing you want to not copy if you find stringToCheck in fileToCheck. You need to do something like (code untested but you get the idea):

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat
IF NOT ERRORLEVEL 0 XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y

EDIT by dbenham
The above test is WRONG, it always evaluates to FALSE.
The correct test is IF ERRORLEVEL 1 XCOPY ...

Update: I can't test the code, but I am not sure what return value findstr actually returns if it doesn't find anything. You might have to do something like:

CD C:\MyFolder
findstr /c:"stringToCheck" fileToCheck.bat > tempfindoutput.txt
set /p FINDOUTPUT= < tempfindoutput.txt
IF "%FINDOUTPUT%"=="" XCOPY "C:\OtherFolder\fileToCheck.bat" "C:\MyFolder" /s /y
del tempfindoutput.txt

Android Spinner: Get the selected item change event

The docs for the spinner-widget says

A spinner does not support item click events.

You should use setOnItemSelectedListener to handle your problem.

fatal: git-write-tree: error building trees

This worked for me:

Do

$ git status

And check if you have Unmerged paths

# Unmerged paths:
#   (use "git reset HEAD <file>..." to unstage)
#   (use "git add <file>..." to mark resolution)
#
#   both modified:      app/assets/images/logo.png
#   both modified:      app/models/laundry.rb

Fix them with git add to each of them and try git stash again.

git add app/assets/images/logo.png

TypeError: method() takes 1 positional argument but 2 were given

Newcomer to Python, I had this issue when I was using the Python's ** feature in a wrong way. Trying to call this definition from somewhere:

def create_properties_frame(self, parent, **kwargs):

using a call without a double star was causing the problem:

self.create_properties_frame(frame, kw_gsp)

TypeError: create_properties_frame() takes 2 positional arguments but 3 were given

The solution is to add ** to the argument:

self.create_properties_frame(frame, **kw_gsp)

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

Why is the jquery script not working?

This may not be the answer you are looking for, but may help others whose jquery is not working properly, or working sometimes and not at other times.

This could be because your jquery has not yet loaded and you have started to interact with the page. Either put jquery on top in head (probably not a very great idea) or use a loader or spinner to stop the user from interacting with the page until the entire jquery has loaded.

How to run a single test with Mocha?

run single test –by filename–

Actually, one can also run a single mocha test by filename (not just by „it()-string-grepping“) if you remove the glob pattern (e.g. ./test/**/*.spec.js) from your mocha.opts, respectively create a copy, without:

node_modules/.bin/mocha --opts test/mocha.single.opts test/self-test.spec.js

Here's my mocha.single.opts (it's only different in missing the aforementioned glob line)

--require ./test/common.js
--compilers js:babel-core/register
--reporter list
--recursive

Background: While you can override the various switches from the opts-File (starting with --) you can't override the glob. That link also has some explanations.

Hint: if node_modules/.bin/mocha confuses you, to use the local package mocha. You can also write just mocha, if you have it installed globally.


And if you want the comforts of package.json: Still: remove the **/*-ish glob from your mocha.opts, insert them here, for the all-testing, leave them away for the single testing:

"test": "mocha ./test/**/*.spec.js",
"test-watch": "mocha -R list -w ./test/**/*.spec.js",
"test-single": "mocha $1",
"test-single-watch": "mocha -R list -w $1",

usage:

> npm run test

respectively

> npm run test-single -- test/ES6.self-test.spec.js 

(mind the --!)

socket.shutdown vs socket.close

Here's one explanation:

Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.

How to check for a JSON response using RSpec?

When using Rails 5 (currently still in beta), there's a new method, parsed_body on the test response, which will return the response parsed as what the last request was encoded at.

The commit on GitHub: https://github.com/rails/rails/commit/eee3534b

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

View/edit ID3 data for MP3 files

TagLib Sharp has support for reading ID3 tags.

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

How to check whether a Button is clicked by using JavaScript

Try adding an event listener for clicks:

document.getElementById('button').addEventListener("click", function() {
   alert("You clicked me");
}?);?

Using addEventListener is probably a better idea then setting onclick - onclick can easily be overwritten by another piece of code.

You can use a variable to store whether or not the button has been clicked before:

var clicked = false
document.getElementById('button').addEventListener("click", function() {
   clicked = true
}?);?

addEventListener on MDN

How to redirect to Index from another controller?

try:

public ActionResult Index() {
    return RedirectToAction("actionName");
    // or
    return RedirectToAction("actionName", "controllerName");
    // or
    return RedirectToAction("actionName", "controllerName", new {/* routeValues, for example: */ id = 5 });
}

and in .cshtml view:

@Html.ActionLink("linkText","actionName")

OR:

@Html.ActionLink("linkText","actionName","controllerName")

OR:

@Html.ActionLink("linkText", "actionName", "controllerName", 
    new { /* routeValues forexample: id = 6 or leave blank or use null */ }, 
    new { /* htmlAttributes forexample: @class = "my-class" or leave blank or use null */ })

Notice using null in final expression is not recommended, and is better to use a blank new {} instead of null

Edit seaborn legend

If legend_out is set to True then legend is available thought g._legend property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)

sns.plt.show()

enter image description here

Another situation if legend_out is set to False. You have to define which axes has a legend (in below example this is axis number 0):

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = False)

# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()

enter image description here

Moreover you may combine both situations and use this code:

import seaborn as sns

tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
 data=tips, markers=["o", "x"], legend_out = True)

# check axes and find which is have legend
for ax in g.axes.flat:
    leg = g.axes.flat[0].get_legend()
    if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend

# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)

sns.plt.show()

This code works for any seaborn plot which is based on Grid class.

How to parse/format dates with LocalDateTime? (Java 8)

GET CURRENT UTC TIME IN REQUIRED FORMAT

// Current UTC time
        OffsetDateTime utc = OffsetDateTime.now(ZoneOffset.UTC);

        // GET LocalDateTime 
        LocalDateTime localDateTime = utc.toLocalDateTime();
        System.out.println("*************" + localDateTime);

        // formated UTC time
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF.format(localDateTime));

        //GET UTC time for current date
        Date now= new Date();
        LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
        DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));

How do I create a Python function with optional arguments?

Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" ). After the required positional arguments, you can specify specific optional arguments by name.

Select data from date range between two dates

Try following query to get dates between the range:

SELECT  *
FROM    Product_sales 
WHERE   From_date >= '2013-01-03' AND
        To_date   <= '2013-01-09'

Epoch vs Iteration when training neural networks

To understand the difference between these you must understand the Gradient Descent Algorithm and its Variants.

Before I start with the actual answer, I would like to build some background.

A batch is the complete dataset. Its size is the total number of training examples in the available dataset.

Mini-batch size is the number of examples the learning algorithm processes in a single pass (forward and backward).

A Mini-batch is a small part of the dataset of given mini-batch size.

Iterations is the number of batches of data the algorithm has seen (or simply the number of passes the algorithm has done on the dataset).

Epochs is the number of times a learning algorithm sees the complete dataset. Now, this may not be equal to the number of iterations, as the dataset can also be processed in mini-batches, in essence, a single pass may process only a part of the dataset. In such cases, the number of iterations is not equal to the number of epochs.

In the case of Batch gradient descent, the whole batch is processed on each training pass. Therefore, the gradient descent optimizer results in smoother convergence than Mini-batch gradient descent, but it takes more time. The batch gradient descent is guaranteed to find an optimum if it exists.

Stochastic gradient descent is a special case of mini-batch gradient descent in which the mini-batch size is 1.

Batch gradient descent vs Mini-batch gradient descent

Comparison of batch, stochastic and mini-batch gradient descents.

Rotate camera in Three.js with mouse

OrbitControls and TrackballControls seems to be good for this purpose.

controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;

update in render

controls.update();

How / can I display a console window in Intellij IDEA?

View>Tool Windows>Run

It will show you the console

How to implement a lock in JavaScript

Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:

var functionLock = false;
var functionCallbacks = [];
var lockingFunction = function (callback) {
    if (functionLock) {
        functionCallbacks.push(callback);
    } else {
        $.longRunning(function(response) {
             while(functionCallbacks.length){
                 var thisCallback = functionCallbacks.pop();
                 thisCallback(response);
             }
        });
    }
}

You can also implement this using DOM event listeners or a pubsub solution.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

StreamWriter is available for NET 1.1. and for the Compact framework. Just open the file and apply the ToString to your StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.Append(......);

    StreamWriter sw = new StreamWriter("\\hereIAm.txt", true);
    sw.Write(sb.ToString());
    sw.Close();

Also, note that you say that you want to append debug messages to the file (like a log). In this case, the correct constructor for StreamWriter is the one that accepts an append boolean flag. If true then it tries to append to an existing file or create a new one if it doesn't exists.

Remove HTML Tags from an NSString on the iPhone

#import "RegexKitLite.h"

string text = [html stringByReplacingOccurrencesOfRegex:@"<[^>]+>" withString:@""]

How do I iterate through children elements of a div using jQuery?

If you need to loop through child elements recursively:

function recursiveEach($element){
    $element.children().each(function () {
        var $currentElement = $(this);
        // Show element
        console.info($currentElement);
        // Show events handlers of current element
        console.info($currentElement.data('events'));
        // Loop her children
        recursiveEach($currentElement);
    });
}

// Parent div
recursiveEach($("#div"));   

NOTE: In this example I show the events handlers registered with an object.

How to append a newline to StringBuilder

It should be

r.append("\n");

But I recommend you to do as below,

r.append(System.getProperty("line.separator"));

System.getProperty("line.separator") gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()

Calculate correlation for more than two variables?

See corr.test function in psych package:

> corr.test(mtcars[1:4])
Call:corr.test(x = mtcars[1:4])
Correlation matrix 
       mpg   cyl  disp    hp
mpg   1.00 -0.85 -0.85 -0.78
cyl  -0.85  1.00  0.90  0.83
disp -0.85  0.90  1.00  0.79
hp   -0.78  0.83  0.79  1.00
Sample Size 
     mpg cyl disp hp
mpg   32  32   32 32
cyl   32  32   32 32
disp  32  32   32 32
hp    32  32   32 32
Probability value 
     mpg cyl disp hp
mpg    0   0    0  0
cyl    0   0    0  0
disp   0   0    0  0
hp     0   0    0  0

And yet another shameless self-advert: https://gist.github.com/887249

Exit/save edit to sudoers file? Putty SSH

The tutorial you saw was telling you how to exit nano editor. By typing Ctrl+X nano exits and if your file needs change you will be prompted to save the changes in which case to save you should press Y and then enter to save changes in the same file you open.

If you are not using any gui and you just want to leave the shell the command is Ctrl+D.

Regarding tutorial, The Linux Documentation Project would be a good place to start. If you like books I would recommend by far any book you want from O'Reilly. They have nice cd bookshelfs with good compilation for any linux sysadmin, and without much effort you can find many places where those html bookshelfs are available to read online.

How can I import Swift code to Objective-C?

Be careful with dashes and underscores, they can be mixed up and your Project Name and Target name won't be the same as SWIFT_MODULE_NAME.

Dashes and underscores

Export Postgresql table data using pgAdmin

Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.

pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.

It uses something like this:

pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.

Open a new tab in the background?

THX for this question! Works good for me on all popular browsers:

function openNewBackgroundTab(){
    var a = document.createElement("a");
    a.href = window.location.pathname;
    var evt = document.createEvent("MouseEvents");
    //the tenth parameter of initMouseEvent sets ctrl key
    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
                                true, false, false, false, 0, null);
    a.dispatchEvent(evt);
}

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
    var url = window.location.pathname;
    var win = window.open(url, '_blank');
} else {
    openNewBackgroundTab();
}

Select from one table matching criteria in another?

I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

That WHERE clause I would like to be:

WHERE B.tag = A.<col_name>

or, in my specific case:

WHERE B.val BETWEEN A.val1 AND A.val2

More detailed:

Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.

Convert any object to a byte[]

I'd rather use the expression "serialization" than "casting into bytes". Serializing an object means converting it into a byte array (or XML, or something else) that can be used on the remote box to re-construct the object. In .NET, the Serializable attribute marks types whose objects can be serialized.

How to Add a Dotted Underline Beneath HTML Text

You can try this method:

<h2 style="text-decoration: underline; text-underline-position: under; text-decoration-style: dotted">Hello World!</h2>

Please note that without text-underline-position: under; you still will have a dotted underline but this property will give it more breathing space.

This is assuming you want to embed everything inside an HTML file using inline styling and not to use a separate CSS file or tag.

Can I add an image to an ASP.NET button?

.my_btn{ 
  font-family:Arial; 
  font-size:10pt; 
  font-weight:normal; 
  height:30px; 
  line-height:30px; 
  width:98px; 
  border:0px;
  background-image:url('../Images/menu_image.png'); 
  cursor:pointer;
}

<asp:Button ID="clickme" runat="server" Text="Click" CssClass="my_btn" />

Removing items from a list

You cannot do it because you are already looping on it.

Inorder to avoid this situation use Iterator,which guarentees you to remove the element from list safely ...

List<Object> objs;
Iterator<Object> i = objs.iterator();
while (i.hasNext()) {
   Object o = i.next();
  //some condition
    i.remove();
}

identifier "string" undefined?

#include <string> would be the correct c++ include, also you need to specify the namespace with std::string or more generally with using namespace std;

Change the location of the ~ directory in a Windows install of Git Bash

Instead of modifying the global profile you could create the .bash_profile in your default $HOME directory (e.g. C:\Users\WhateverUser\.bash_profile) with the following contents:

export HOME="C:\my\projects\dir"
cd "$HOME" # if you'd like it to be the starting dir of the git shell

How do I 'foreach' through a two-dimensional array?

Multidimensional arrays aren't enumerable. Just iterate the good old-fashioned way:

for (int i = 0; i < table.GetLength(0); i++)
{
    Console.WriteLine(table[i, 0] + " " + table[i, 1]);
}

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

How to close jQuery Dialog within the dialog?

$(this).parents(".ui-dialog-content").dialog('close')

Simple, I like to make sure I don't:

  1. hardcode dialog #id values.
  2. Close all dialogs.

from jquery $.ajax to angular $http

you can use $.param to assign data :

 $http({
  url: "http://example.appspot.com/rest/app",
  method: "POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $scope.data = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;
 });

look at this : AngularJS + ASP.NET Web API Cross-Domain Issue

jquery variable syntax

self and $self aren't the same. The former is the object pointed to by "this" and the latter a jQuery object whose "scope" is the object pointed to by "this". Similarly, $body isn't the body DOM element but the jQuery object whose scope is the body element.

How can I slice an ArrayList out of an ArrayList in Java?

If there is no existing method then I guess you can iterate from 0 to input.size()/2, taking each consecutive element and appending it to a new ArrayList.

EDIT: Actually, I think you can take that List and use it to instantiate a new ArrayList using one of the ArrayList constructors.

Can you do a partial checkout with Subversion?

Sort of. As Bobby says:

svn co file:///.../trunk/foo file:///.../trunk/bar file:///.../trunk/hum

will get the folders, but you will get separate folders from a subversion perspective. You will have to go separate commits and updates on each subfolder.

I don't believe you can checkout a partial tree and then work with the partial tree as a single entity.

Jquery Ajax, return success/error from mvc.net controller

Use Json class instead of Content as shown following:

    //  When I want to return an error:
    if (!isFileSupported)
    {
        Response.StatusCode = (int) HttpStatusCode.BadRequest;
        return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
    }
    else
    {
        //  When I want to return sucess:
        Response.StatusCode = (int)HttpStatusCode.OK; 
        return Json("Message sent!", MediaTypeNames.Text.Plain);
    }

Also set contentType:

contentType: 'application/json; charset=utf-8',

How to use vagrant in a proxy environment?

Installing proxyconf will solve this, but behind a proxy you can't install a plugin simply using the command vagrant plugin install, Bundler will raise an error.

set your proxy in your environment if you're using a unix like system

export http_proxy=http://user:password@host:port

or get a more detailed answer here: How to use bundler behind a proxy?

after this set up proxyconf

Partition Function COUNT() OVER possible using DISTINCT

I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
) 
+ dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1

An SQL Fiddle with an extended example can be found here.

How to detect when a UIScrollView has finished scrolling

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    scrollingFinished(scrollView: scrollView)
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if decelerate {
        //didEndDecelerating will be called for sure
        return
    }
    scrollingFinished(scrollView: scrollView)        
}

func scrollingFinished(scrollView: UIScrollView) {
   // Your code
}

Placing a textview on top of imageview in android

This should give you the required layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ImageView
        android:id="@+id/flag"
        android:layout_width="fill_parent"
        android:layout_height="250dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

Play with the android:layout_marginTop="20dp" to see which one suits you better. Use the id textview to dynamically set the android:text value.

Since a RelativeLayout stacks its children, defining the TextView after ImageView puts it 'over' the ImageView.

NOTE: Similar results can be obtained using a FrameLayout as the parent, along with the efficiency gain over using any other android container. Thanks to Igor Ganapolsky(see comment below) for pointing out that this answer needs an update.

Java read file and store text in an array

int count = -1;
String[] content = new String[200];
while(inFile1.hasNext()){

    content[++count] = inFile1.nextLine();
}

EDIT

Looks like you want to create a float array, for that create a float array

int count = -1;
Float[] content = new Float[200];
while(inFile1.hasNext()){

    content[++count] = Float.parseFloat(inFile1.nextLine());
}

then your float array would look like

content[0] = 70.3
content[1] = 70.8
content[2] = 73.8
content[3] = 77.0 and so on

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

Important:

For anybody who was brought here by googling the generic bean error message, but who is actually trying to add a feign client to their Spring Boot application via the @FeignClient annotation on your client interface, none of the above solutions will work for you.

To fix the problem, you need to add the @EnableFeignClients annotation to your Application class, like so:

@SpringBootApplication
// ... (other pre-existing annotations) ...
@EnableFeignClients // <------- THE IMPORTANT ONE
public class Application {

Side note: adding a @ComponentScan(...) beneath @SpringBootApplication is redundant, and your IDE should flag it as such (IntelliJ IDEA does, at least).

How do you find out the caller function in JavaScript?

It's safer to use *arguments.callee.caller since arguments.caller is deprecated...

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

Use KeyPressEventArgs,

Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles ComboBox1.KeyPress
    e.Handled = True
End Sub

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

Show a number to two decimal places

Here's another solution with strtok and str_pad:

$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')

How can I connect to MySQL in Python 3 on Windows?

if you want to use MySQLdb first you have to install pymysql on your pc by typing in cmd of windows

    pip install pymysql

then in python shell, type

    import pymysql
    pymysql.install_as_MySQLdb()
    import MySQLdb
    db = MySQLdb.connect("localhost" , "root" , "password")

this will establish the connection.

Java inner class and static nested class

I don't think the real difference became clear in the above answers.

First to get the terms right:

  • A nested class is a class which is contained in another class at the source code level.
  • It is static if you declare it with the static modifier.
  • A non-static nested class is called inner class. (I stay with non-static nested class.)

Martin's answer is right so far. However, the actual question is: What is the purpose of declaring a nested class static or not?

You use static nested classes if you just want to keep your classes together if they belong topically together or if the nested class is exclusively used in the enclosing class. There is no semantic difference between a static nested class and every other class.

Non-static nested classes are a different beast. Similar to anonymous inner classes, such nested classes are actually closures. That means they capture their surrounding scope and their enclosing instance and make that accessible. Perhaps an example will clarify that. See this stub of a Container:

public class Container {
    public class Item{
        Object data;
        public Container getContainer(){
            return Container.this;
        }
        public Item(Object data) {
            super();
            this.data = data;
        }

    }

    public static Item create(Object data){
        // does not compile since no instance of Container is available
        return new Item(data);
    }
    public Item createSubItem(Object data){
        // compiles, since 'this' Container is available
        return new Item(data);
    }
}

In this case you want to have a reference from a child item to the parent container. Using a non-static nested class, this works without some work. You can access the enclosing instance of Container with the syntax Container.this.

More hardcore explanations following:

If you look at the Java bytecodes the compiler generates for an (non-static) nested class it might become even clearer:

// class version 49.0 (49)
// access flags 33
public class Container$Item {

  // compiled from: Container.java
  // access flags 1
  public INNERCLASS Container$Item Container Item

  // access flags 0
  Object data

  // access flags 4112
  final Container this$0

  // access flags 1
  public getContainer() : Container
   L0
    LINENUMBER 7 L0
    ALOAD 0: this
    GETFIELD Container$Item.this$0 : Container
    ARETURN
   L1
    LOCALVARIABLE this Container$Item L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

  // access flags 1
  public <init>(Container,Object) : void
   L0
    LINENUMBER 12 L0
    ALOAD 0: this
    ALOAD 1
    PUTFIELD Container$Item.this$0 : Container
   L1
    LINENUMBER 10 L1
    ALOAD 0: this
    INVOKESPECIAL Object.<init>() : void
   L2
    LINENUMBER 11 L2
    ALOAD 0: this
    ALOAD 2: data
    PUTFIELD Container$Item.data : Object
    RETURN
   L3
    LOCALVARIABLE this Container$Item L0 L3 0
    LOCALVARIABLE data Object L0 L3 2
    MAXSTACK = 2
    MAXLOCALS = 3
}

As you can see the compiler creates a hidden field Container this$0. This is set in the constructor which has an additional parameter of type Container to specify the enclosing instance. You can't see this parameter in the source but the compiler implicitly generates it for a nested class.

Martin's example

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

would so be compiled to a call of something like (in bytecodes)

new InnerClass(outerObject)

For the sake of completeness:

An anonymous class is a perfect example of a non-static nested class which just has no name associated with it and can't be referenced later.

"sed" command in bash

Here sed is replacing all occurrences of % with $ in its standard input.

As an example

$ echo 'foo%bar%' | sed -e 's,%,$,g'

will produce "foo$bar$".

Powershell folder size of folders without listing Subdirectories

Interesting how powerful yet how helpless PS can be in the same time, coming from a Nix learning PS. after install crgwin/gitbash, you can do any combination in one commands:

size of current folder: du -sk .

size of all files and folders under current directory du -sk *

size of all subfolders (including current folders) find ./ -type d -exec du -sk {} \;

How to make a .NET Windows Service start right after the installation?

The easiest solution is found here install-windows-service-without-installutil-exe by @Hoàng Long

@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"

echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause

Android error: Failed to install *.apk on device *: timeout

Reboot the phone.

Seriously! Completely power down and power up. That fixed it for me.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

I was getting the error “gcc: error: x86_64-linux-gnu-gcc: No such file or directory” as I was trying to build a simple c-extension module to run in Python. I tried all the things above to no avail, and finally realized that I had an error in my module.c code! So I thought it would be helpful to add that, if you are getting this error message but you have python-dev and everything correctly installed, you should look for issues in your code.

Material UI and Grid system

Material UI have implemented their own Flexbox layout via the Grid component.

It appears they initially wanted to keep themselves as purely a 'components' library. But one of the core developers decided it was too important not to have their own. It has now been merged into the core code and was released with v1.0.0.

You can install it via:

npm install @material-ui/core

It is now in the official documentation with code examples.

How To Get Selected Value From UIPickerView

You have to use the didSelectRow delegate method, because a UIPickerView can have an arbitrary number of components. There is no "objectValue" or anything like that, because that's entirely up to you.

Failed to execute 'atob' on 'Window'

In my case, I was going nuts since there wasn't any issues with the string to be decoded, since I could successfully decode it on online tools. Until I found out that you first have to decodeURIComponent what you are decoding, like so:

atob(decodeURIComponent(dataToBeDecoded));

How to use `replace` of directive definition?

Replace [True | False (default)]

Effect

1.  Replace the directive element. 

Dependency:

1. When replace: true, the template or templateUrl must be required. 

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

Install numpy on python3.3 - Install pip for python3

My issue was the failure to import numpy into my python files. I was receiving the "ModuleNotFoundError: No module named 'numpy'". I ran into the same issue and I was not referencing python3 on the installation of numpy. I inputted the following into my terminal for OSX and my problems were solved:

python3 -m pip install numpy

no module named zlib

My objective was to create a new Django project from the command line in Ubuntu, like so:

django-admin.py startproject mysite

I have python2.7.5 installed. I got this error:

ImportError: No module named zlib

For hours I could not find a solution, until now!

Here is a link to the solution -

http://doc.biblissima-condorcet.fr/loris-setup-guide-ubuntu-debian

I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.

Check if a Postgres JSON array contains a string

Not smarter but simpler:

select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';

any tool for java object to object mapping?

ModelMapper is another library worth checking out. ModelMapper's design is different from other libraries in that it:

  • Automatically maps object models by intelligently matching source and destination properties
  • Provides a refactoring safe mapping API that uses actual code to map fields and methods rather than using strings
  • Utilizes convention based configuration for simple handling of custom scenarios

Check out the ModelMapper site for more info:

http://modelmapper.org

Change a Nullable column to NOT NULL with Default Value

Try this

ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:

>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'

This will almost certainly be faster than the conversion to and from a date.

How to drop all tables in a SQL Server database?

Short and sweet:

USE YOUR_DATABASE_NAME
-- Disable all referential integrity constraints
EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Drop all PKs and FKs
declare @sql nvarchar(max)
SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name  +'  drop constraint ' + Constraint_Name  from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@sql)
GO

-- Drop all tables
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO

C# cannot convert method to non delegate type

To execute a method you need to add parentheses, even if the method does not take arguments.

So it should be:

string t = obj.getTitle();

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

i think csrf only works with spring forms

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

change to form:form tag and see it that works.

What is the reason behind "non-static method cannot be referenced from a static context"?

The answers so far describe why, but here is a something else you might want to consider:

You can can call a method from an instantiable class by appending a method call to its constructor,

Object instance = new Constuctor().methodCall();

or

primitive name = new Constuctor().methodCall();

This is useful it you only wish to use a method of an instantiable class once within a single scope. If you are calling multiple methods from an instantiable class within a single scope, definitely create a referable instance.

How to force a html5 form validation without submitting it via jQuery

This worked form me to display the native HTML 5 error messages with form validation.

<button id="btnRegister" class="btn btn-success btn btn-lg" type="submit"> Register </button>



$('#RegForm').on('submit', function () 
{

if (this.checkValidity() == false) 
{

 // if form is not valid show native error messages 

return false;

}
else
{

 // if form is valid , show please wait message and disable the button

 $("#btnRegister").html("<i class='fa fa-spinner fa-spin'></i> Please Wait...");

 $(this).find(':submit').attr('disabled', 'disabled');

}


});

Note: RegForm is the form id.

Reference

Hope helps someone.

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

Convert an integer to an array of digits

You can do something like this:

public int[] convertDigitsToArray(int n) {

    int [] temp = new int[String.valueOf(n).length()]; // Calculate the length of digits
    int i = String.valueOf(n).length()-1 ;  // Initialize the value to the last index

    do {
        temp[i] = n % 10;
        n = n / 10;
        i--;
    } while(n>0);

    return temp;
}

This will also maintain the order.

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

NSOperation vs Grand Central Dispatch

GCD is indeed lower-level than NSOperationQueue, its major advantage is that its implementation is very light-weight and focused on lock-free algorithms and performance.

NSOperationQueue does provide facilities that are not available in GCD, but they come at non-trivial cost, the implementation of NSOperationQueue is complex and heavy-weight, involves a lot of locking, and uses GCD internally only in a very minimal fashion.

If you need the facilities provided by NSOperationQueue by all means use it, but if GCD is sufficient for your needs, I would recommend using it directly for better performance, significantly lower CPU and power cost and more flexibility.

Change the content of a div based on selection from dropdown menu

here is a jsfiddle with an example of showing/hiding div's via a select.

HTML:

<div id="option1" class="group">asdf</div>
<div id="option2" class="group">kljh</div>
<div id="option3" class="group">zxcv</div>
<div id="option4" class="group">qwerty</div>
<select id="selectMe">
  <option value="option1">option1</option>
  <option value="option2">option2</option>
  <option value="option3">option3</option>
  <option value="option4">option4</option>
</select>

jQuery:

$(document).ready(function () {
  $('.group').hide();
  $('#option1').show();
  $('#selectMe').change(function () {
    $('.group').hide();
    $('#'+$(this).val()).show();
  })
});

How to make HTML table cell editable?

I am using this for editable field

_x000D_
_x000D_
<table class="table table-bordered table-responsive-md table-striped text-center">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th class="text-center">Citation</th>_x000D_
      <th class="text-center">Security</th>_x000D_
      <th class="text-center">Implementation</th>_x000D_
      <th class="text-center">Description</th>_x000D_
      <th class="text-center">Solution</th>_x000D_
      <th class="text-center">Remove</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="pt-3-half" contenteditable="false">Aurelia Vega</td>_x000D_
      <td class="pt-3-half" contenteditable="false">30</td>_x000D_
      <td class="pt-3-half" contenteditable="false">Deepends</td>_x000D_
      <td class="pt-3-half" contenteditable="true"><input type="text" name="add1" value="spain" class="border-none"></td>_x000D_
      <td class="pt-3-half" contenteditable="true"><input type="text" name="add1" value="marid" class="border-none"></td>_x000D_
      <td>_x000D_
        <span class="table-remove"><button type="button"_x000D_
                              class="btn btn-danger btn-rounded btn-sm my-0">Remove</button></span>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I create/edit a Manifest file?

The simplest way to create a manifest is:

Project Properties -> Security -> Click "enable ClickOnce security settings" 
(it will generate default manifest in your project Properties) -> then Click 
it again in order to uncheck that Checkbox -> open your app.maifest and edit 
it as you wish.

Manifest location preview

Increment a database field by 1

You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column

create table logins (userid int auto_increment primary key, 
  username varchar(30), password varchar(30));

then no special code is needed on insert. Just

insert into logins (username, password) values ('user','pass');

The MySQL API has functions to tell you what userid was created when you execute this statement in client code.

What causes java.lang.IncompatibleClassChangeError?

An additional cause of this issue, is if you have Instant Run enabled for Android Studio.

The fix

If you find you start getting this error, turn off Instant Run.

  1. Android Studio main settings
  2. Build, Execution, Deployment
  3. Instant Run
  4. Untick "Enable instant run..."

Why

Instant Run modifies a large number of things during development, to make it quicker to provide updates to your running App. Hence instant run. When it works, it is really useful. However, when an issue such as this strikes, the best thing to do is to turn off Instant Run until the next version of Android Studio releases.

How to represent a DateTime in Excel

If, like me, you can't find a datetime under date or time in the format dialog, you should be able to find it in 'Custom'.

I just selected 'dd/mm/yyyy hh:mm' from 'Custom' and am happy with the results.

How to get row number in dataframe in Pandas?

 len(df[df["Lastname"]=="Smith"].values)

Git log to get commits only for a specific branch

In my situation, we are using Git Flow and GitHub. All you need to do this is: Compare your feature branch with your develop branch on GitHub.

It will show the commits only made to your feature branch.

For example:

https://github.com/your_repo/compare/develop...feature_branch_name

How to enable C++17 compiling in Visual Studio?

There's now a drop down (at least since VS 2017.3.5) where you can specifically select C++17. The available options are (under project > Properties > C/C++ > Language > C++ Language Standard)

  • ISO C++14 Standard. msvc command line option: /std:c++14
  • ISO C++17 Standard. msvc command line option: /std:c++17
  • The latest draft standard. msvc command line option: /std:c++latest

(I bet, once C++20 is out and more fully supported by Visual Studio it will be /std:c++20)

LISTAGG in Oracle to return distinct values

If you want distinct values across MULTIPLE columns, want control over sort order, don't want to use an undocumented function that may disappear, and do not want more than one full table scan, you may find this construct useful:

with test_data as 
(
      select 'A' as col1, 'T_a1' as col2, '123' as col3 from dual
union select 'A', 'T_a1', '456' from dual
union select 'A', 'T_a1', '789' from dual
union select 'A', 'T_a2', '123' from dual
union select 'A', 'T_a2', '456' from dual
union select 'A', 'T_a2', '111' from dual
union select 'A', 'T_a3', '999' from dual
union select 'B', 'T_a1', '123' from dual
union select 'B', 'T_b1', '740' from dual
union select 'B', 'T_b1', '846' from dual
)
select col1
     , (select listagg(column_value, ',') within group (order by column_value desc) from table(collect_col2)) as col2s
     , (select listagg(column_value, ',') within group (order by column_value desc) from table(collect_col3)) as col3s
from 
(
select col1
     , collect(distinct col2) as collect_col2
     , collect(distinct col3) as collect_col3
from test_data
group by col1
);

Simple CSS: Text won't center in a button

make sure:

box-sizing : content-box;

subtract two times in python

datetime.time does not support this, because it's nigh meaningless to subtract times in this manner. Use a full datetime.datetime if you want to do this.

What is the pythonic way to detect the last element in a 'for' loop?

Is there no possibility to iterate over all-but the last element, and treat the last one outside of the loop? After all, a loop is created to do something similar to all elements you loop over; if one element needs something special, it shouldn't be in the loop.

(see also this question: does-the-last-element-in-a-loop-deserve-a-separate-treatment)

EDIT: since the question is more about the "in between", either the first element is the special one in that it has no predecessor, or the last element is special in that it has no successor.

Get the (last part of) current directory name in C#

You're looking for Path.GetFileName.
Note that this won't work if the path ends in a \.

Find a string by searching all tables in SQL Server Management Studio 2008

A bit late, but you can easily find a string with this query

DECLARE
@search_string  VARCHAR(100),
@table_name     SYSNAME,
@table_id       INT,
@column_name    SYSNAME,
@sql_string     VARCHAR(2000)

SET @search_string = 'StringtoSearch'

DECLARE tables_cur CURSOR FOR SELECT ss.name +'.'+ so.name [name], object_id FROM sys.objects so INNER JOIN sys.schemas ss ON so.schema_id = ss.schema_id WHERE  type = 'U'

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id 
        AND system_type_id IN (167, 175, 231, 239)

    OPEN columns_cur

    FETCH NEXT FROM columns_cur INTO @column_name
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + '] 
            LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''

            EXECUTE(@sql_string)

        FETCH NEXT FROM columns_cur INTO @column_name
        END

    CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END

CLOSE tables_cur
DEALLOCATE tables_cur

Getting the HTTP Referrer in ASP.NET

Request.Headers["Referer"]

Explanation

The Request.UrlReferer property will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).

Therefore, the Request.UrlReferer property is not 100% reliable - it may contain data that cannot be parsed into a Uri class. To ensure the value is always readable, use Request.Headers["Referrer"] instead.

As for using Request.ServerVariables as others here have suggested, per MSDN:

Request.ServerVariables Collection

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Request.Headers Property

Gets a collection of HTTP headers.

Request.Headers is a better choice than Request.ServerVariables, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.

So the most reliable solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.

What is lexical scope?

I love the fully featured, language-agnostic answers from folks like @Arak. Since this question was tagged JavaScript though, I'd like to chip in some notes very specific to this language.

In JavaScript our choices for scoping are:

  • as-is (no scope adjustment)
  • lexical var _this = this; function callback(){ console.log(_this); }
  • bound callback.bind(this)

It's worth noting, I think, that JavaScript doesn't really have dynamic scoping. .bind adjusts the this keyword, and that's close, but not technically the same.

Here is an example demonstrating both approaches. You do this every time you make a decision about how to scope callbacks so this applies to promises, event handlers, and more.

Lexical

Here is what you might term Lexical Scoping of callbacks in JavaScript:

var downloadManager = {
  initialize: function() {
    var _this = this; // Set up `_this` for lexical access
    $('.downloadLink').on('click', function () {
      _this.startDownload();
    });
  },
  startDownload: function(){
    this.thinking = true;
    // Request the file from the server and bind more callbacks for when it returns success or failure
  }
  //...
};

Bound

Another way to scope is to use Function.prototype.bind:

var downloadManager = {
  initialize: function() {
    $('.downloadLink').on('click', function () {
      this.startDownload();
    }.bind(this)); // Create a function object bound to `this`
  }
//...

These methods are, as far as I know, behaviorally equivalent.

How to use sudo inside a docker container?

The other answers didn't work for me. I kept searching and found a blog post that covered how a team was running non-root inside of a docker container.

Here's the TL;DR version:

RUN apt-get update \
 && apt-get install -y sudo

RUN adduser --disabled-password --gecos '' docker
RUN adduser docker sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

USER docker

# this is where I was running into problems with the other approaches
RUN sudo apt-get update 

I was using FROM node:9.3 for this, but I suspect that other similar container bases would work as well.

how to create a Java Date object of midnight today and midnight tomorrow?

Using apache commons..

//For midnight today 
Date today = new Date(); 
DateUtils.truncate(today, Calendar.DATE);

//For midnight tomorrow   
Date tomorrow = DateUtils.addDays(today, 1); 
DateUtils.truncate(tomorrow, Calendar.DATE);

Parcelable encountered IOException writing serializable object getactivity()

if you POJO contains any other model inside that should also implements Serializable

clear table jquery

Use .remove()

$("#yourtableid tr").remove();

If you want to keep the data for future use even after removing it then you can use .detach()

$("#yourtableid tr").detach();

If the rows are children of the table then you can use child selector instead of descendant selector, like

$("#yourtableid > tr").remove();

Why can't static methods be abstract in Java?

A static method, by definition, doesn't need to know this. Thus, it cannot be a virtual method (that is overloaded according to dynamic subclass information available through this); instead, a static method overload is solely based on info available at compile time (this means: once you refer a static method of superclass, you call namely the superclass method, but never a subclass method).

According to this, abstract static methods would be quite useless because you will never have its reference substituted by some defined body.

"Least Astonishment" and the Mutable Default Argument

Python: The Mutable Default Argument

Default arguments get evaluated at the time the function is compiled into a function object. When used by the function, multiple times by that function, they are and remain the same object.

When they are mutable, when mutated (for example, by adding an element to it) they remain mutated on consecutive calls.

They stay mutated because they are the same object each time.

Equivalent code:

Since the list is bound to the function when the function object is compiled and instantiated, this:

def foo(mutable_default_argument=[]): # make a list the default argument
    """function that uses a list"""

is almost exactly equivalent to this:

_a_list = [] # create a list in the globals

def foo(mutable_default_argument=_a_list): # make it the default argument
    """function that uses a list"""

del _a_list # remove globals name binding

Demonstration

Here's a demonstration - you can verify that they are the same object each time they are referenced by

  • seeing that the list is created before the function has finished compiling to a function object,
  • observing that the id is the same each time the list is referenced,
  • observing that the list stays changed when the function that uses it is called a second time,
  • observing the order in which the output is printed from the source (which I conveniently numbered for you):

example.py

print('1. Global scope being evaluated')

def create_list():
    '''noisily create a list for usage as a kwarg'''
    l = []
    print('3. list being created and returned, id: ' + str(id(l)))
    return l

print('2. example_function about to be compiled to an object')

def example_function(default_kwarg1=create_list()):
    print('appending "a" in default default_kwarg1')
    default_kwarg1.append("a")
    print('list with id: ' + str(id(default_kwarg1)) + 
          ' - is now: ' + repr(default_kwarg1))

print('4. example_function compiled: ' + repr(example_function))


if __name__ == '__main__':
    print('5. calling example_function twice!:')
    example_function()
    example_function()

and running it with python example.py:

1. Global scope being evaluated
2. example_function about to be compiled to an object
3. list being created and returned, id: 140502758808032
4. example_function compiled: <function example_function at 0x7fc9590905f0>
5. calling example_function twice!:
appending "a" in default default_kwarg1
list with id: 140502758808032 - is now: ['a']
appending "a" in default default_kwarg1
list with id: 140502758808032 - is now: ['a', 'a']

Does this violate the principle of "Least Astonishment"?

This order of execution is frequently confusing to new users of Python. If you understand the Python execution model, then it becomes quite expected.

The usual instruction to new Python users:

But this is why the usual instruction to new users is to create their default arguments like this instead:

def example_function_2(default_kwarg=None):
    if default_kwarg is None:
        default_kwarg = []

This uses the None singleton as a sentinel object to tell the function whether or not we've gotten an argument other than the default. If we get no argument, then we actually want to use a new empty list, [], as the default.

As the tutorial section on control flow says:

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

MATLAB, Filling in the area between two sets of data, lines in one figure

Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill in conjunction with fliplr.

Example:

x=0:0.01:2*pi;                  %#initialize x array
y1=sin(x);                      %#create first curve
y2=sin(x)+.5;                   %#create second curve
X=[x,fliplr(x)];                %#create continuous x value array for plotting
Y=[y1,fliplr(y2)];              %#create y values for out and then back
fill(X,Y,'b');                  %#plot filled area

enter image description here

By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.

How to convert milliseconds into a readable date?

I just tested this and it works fine

var d = new Date(1441121836000);

The data object has a constructor which takes milliseconds as an argument.

Why does DEBUG=False setting make my django Static Files Access fail?

I agree with Marek Sapkota answer; But you can still use django URFConf to reallocate the url, if static file is requested.

Step 1: Define a STATIC_ROOT path in settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Step 2: Then collect the static files

$ python manage.py collectstatic

Step 3: Now define your URLConf that if static is in the beginning of url, access files from the static folder staticfiles. NOTE: This is your project's urls.py file:

from django.urls import re_path
from django.views.static import serve

urlpattern += [
  re_path(r'^static/(?:.*)$', serve, {'document_root': settings.STATIC_ROOT, })
]

Grouping functions (tapply, by, aggregate) and the *apply family

It is maybe worth mentioning ave. ave is tapply's friendly cousin. It returns results in a form that you can plug straight back into your data frame.

dfr <- data.frame(a=1:20, f=rep(LETTERS[1:5], each=4))
means <- tapply(dfr$a, dfr$f, mean)
##  A    B    C    D    E 
## 2.5  6.5 10.5 14.5 18.5 

## great, but putting it back in the data frame is another line:

dfr$m <- means[dfr$f]

dfr$m2 <- ave(dfr$a, dfr$f, FUN=mean) # NB argument name FUN is needed!
dfr
##   a f    m   m2
##   1 A  2.5  2.5
##   2 A  2.5  2.5
##   3 A  2.5  2.5
##   4 A  2.5  2.5
##   5 B  6.5  6.5
##   6 B  6.5  6.5
##   7 B  6.5  6.5
##   ...

There is nothing in the base package that works like ave for whole data frames (as by is like tapply for data frames). But you can fudge it:

dfr$foo <- ave(1:nrow(dfr), dfr$f, FUN=function(x) {
    x <- dfr[x,]
    sum(x$m*x$m2)
})
dfr
##     a f    m   m2    foo
## 1   1 A  2.5  2.5    25
## 2   2 A  2.5  2.5    25
## 3   3 A  2.5  2.5    25
## ...

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Create a model

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

Controllers Like Below

    public ActionResult PersonTest()
    {
        return View();
    }

    [HttpPost]
    public ActionResult PersonSubmit(Vh.Web.Models.Person person)
    {
        System.Threading.Thread.Sleep(2000);  /*simulating slow connection*/

        /*Do something with object person*/


        return Json(new {msg="Successfully added "+person.Name });
    }

Javascript

<script type="text/javascript">
    function send() {
        var person = {
            name: $("#id-name").val(),
            address:$("#id-address").val(),
            phone:$("#id-phone").val()
        }

        $('#target').html('sending..');

        $.ajax({
            url: '/test/PersonSubmit',
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            success: function (data) {
                $('#target').html(data.msg);
            },
            data: JSON.stringify(person)
        });
    }
</script>

Determining Referer in PHP

The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

Adding a favicon to a static HTML page

Actually, to make your favicon work in all browsers, you must have more than 10 images in the correct sizes and formats.

I created an App (faviconit.com) so people don´t have to create all these images and the correct tags by hand.

Hope you like it.

Wait until a process ends

I think you just want this:

var process = Process.Start(...);
process.WaitForExit();

See the MSDN page for the method. It also has an overload where you can specify the timeout, so you're not potentially waiting forever.

What JSON library to use in Scala?

You can try this: https://github.com/momodi/Json4Scala

It's simple, and has only one scala file with less than 300 lines code.

There are samples:

test("base") {
    assert(Json.parse("123").asInt == 123)
    assert(Json.parse("-123").asInt == -123)
    assert(Json.parse("111111111111111").asLong == 111111111111111l)
    assert(Json.parse("true").asBoolean == true)
    assert(Json.parse("false").asBoolean == false)
    assert(Json.parse("123.123").asDouble == 123.123)
    assert(Json.parse("\"aaa\"").asString == "aaa")
    assert(Json.parse("\"aaa\"").write() == "\"aaa\"")

    val json = Json.Value(Map("a" -> Array(1,2,3), "b" -> Array(4, 5, 6)))
    assert(json("a")(0).asInt == 1)
    assert(json("b")(1).asInt == 5)
}
test("parse base") {
    val str =
        """
          {"int":-123, "long": 111111111111111, "string":"asdf", "bool_true": true, "foo":"foo", "bool_false": false}
        """
    val json = Json.parse(str)
    assert(json.asMap("int").asInt == -123)
    assert(json.asMap("long").asLong == 111111111111111l)
    assert(json.asMap("string").asString == "asdf")
    assert(json.asMap("bool_true").asBoolean == true)
    assert(json.asMap("bool_false").asBoolean == false)
    println(json.write())
    assert(json.write().length > 0)
}
test("parse obj") {
    val str =
        """
           {"asdf":[1,2,4,{"bbb":"ttt"},432]}
        """
    val json = Json.parse(str)
    assert(json.asMap("asdf").asArray(0).asInt == 1)
    assert(json.asMap("asdf").asArray(3).asMap("bbb").asString == "ttt")
}
test("parse array") {
    val str =
        """
           [1,2,3,4,{"a":[1,2,3]}]
        """
    val json = Json.parse(str)
    assert(json.asArray(0).asInt == 1)
    assert(json(4)("a")(2).asInt == 3)
    assert(json(4)("a")(2).isInt)
    assert(json(4)("a").isArray)
    assert(json(4)("a").isMap == false)
}
test("real") {
    val str = "{\"styles\":[214776380871671808,214783111085424640,214851869216866304,214829406537908224],\"group\":100,\"name\":\"AO4614??????????? ???? ????@\",\"shopgrade\":8,\"price\":0.59,\"shop_id\":60095469,\"C3\":50018869,\"C2\":50024099,\"C1\":50008090,\"imguri\":\"http://img.geilicdn.com/taobao10000177139_425x360.jpg\",\"cag\":50006523,\"soldout\":0,\"C4\":50006523}"
    val json = Json.parse(str)
    println(json.write())
    assert(json.asMap.size > 0)
}

Filtering a pyspark dataframe using isin by exclusion

Got a gotcha for those with their headspace in Pandas and moving to pyspark

 from pyspark import SparkConf, SparkContext
 from pyspark.sql import SQLContext

 spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
 sc = SparkContext(conf = spark_conf)
 sqlContext = SQLContext(sc)

 records = [
     {"colour": "red"},
     {"colour": "blue"},
     {"colour": None},
 ]

 pandas_df = pd.DataFrame.from_dict(records)
 pyspark_df = sqlContext.createDataFrame(records)

So if we wanted the rows that are not red:

pandas_df[~pandas_df["colour"].isin(["red"])]

As expected in Pandas

Looking good, and in our pyspark DataFrame

pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()

Not what I expected

So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:

pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()

much ado about nothing

Why is __dirname not defined in node REPL?

I was running a script from batch file as SYSTEM user and all variables like process.cwd() , path.resolve() and all other methods would give me path to C:\Windows\System32 folder instead of actual path. During experiments I noticed that when an error is thrown the stack contains a true path to the node file.

Here's a very hacky way to get true path by triggering an error and extracting path from e.stack. Do not use.

// this should be the name of currently executed file
const currentFilename = 'index.js';

function veryHackyGetFolder() {
  try {
    throw new Error();
  } catch(e) {
    const fullMsg = e.stack.toString();
    const beginning = fullMsg.indexOf('file:///') + 8;
    const end = fullMsg.indexOf('\/' + currentFilename);
    const dir = fullMsg.substr(beginning, end - beginning).replace(/\//g, '\\');
    return dir;
  }
}

Usage

const dir = veryHackyGetFolder();

Reading my own Jar's Manifest

You can use Manifests from jcabi-manifests and read any attribute from any of available MANIFEST.MF files with just one line:

String value = Manifests.read("My-Attribute");

The only dependency you need is:

<dependency>
  <groupId>com.jcabi</groupId>
  <artifactId>jcabi-manifests</artifactId>
  <version>0.7.5</version>
</dependency>

Also, see this blog post for more details: http://www.yegor256.com/2014/07/03/how-to-read-manifest-mf.html

How to check if a Constraint exists in Sql server?

I use this to check for and remote constraints on a column. It should have everything you need.

DECLARE
  @ps_TableName VARCHAR(300)
  , @ps_ColumnName VARCHAR(300)

SET @ps_TableName = 'mytable'
SET @ps_ColumnName = 'mycolumn'

DECLARE c_ConsList CURSOR LOCAL STATIC FORWARD_ONLY FOR
    SELECT
    'ALTER TABLE ' + RTRIM(tb.name) + ' drop constraint ' + sco.name AS csql
    FROM
        sys.Objects tb
        INNER JOIN sys.Columns tc on (tb.Object_id = tc.object_id)
        INNER JOIN sys.sysconstraints sc ON (tc.Object_ID = sc.id and tc.column_id = sc.colid)
        INNER JOIN sys.objects sco ON (sc.Constid = sco.object_id)
    where
        tb.name=@ps_TableName
        AND tc.name=@ps_ColumnName
OPEN c_ConsList
FETCH c_ConsList INTO @ls_SQL
WHILE (@@FETCH_STATUS = 0) BEGIN

    IF RTRIM(ISNULL(@ls_SQL, '')) <> '' BEGIN
        EXECUTE(@ls_SQL)
    END
    FETCH c_ConsList INTO @ls_SQL
END
CLOSE c_ConsList
DEALLOCATE c_ConsList

SQL Query - how do filter by null or not null

set ansi_nulls off go select * from table t inner join otherTable o on t.statusid = o.statusid go set ansi_nulls on go

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

I got this error when trying to install a nuget package that I had previously downloaded and installed in another project.

Clicking Clear all NuGet Cache(s) under Tools > Options > NuGet Package Manager solved this for me

JavaScript: How to find out if the user browser is Chrome?

even shorter: var is_chrome = /chrome/i.test( navigator.userAgent );

How to declare a variable in SQL Server and use it in the same Stored Procedure

None of the above methods worked for me so i'm posting the way i did

DELIMITER $$
CREATE PROCEDURE AddBrand()
BEGIN 

DECLARE BrandName varchar(50);
DECLARE CategoryID,BrandID  int;
SELECT BrandID = BrandID FROM tblBrand 
WHERE BrandName = BrandName;

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (CategoryID, BrandID);
END$$

How to test the type of a thrown exception in Jest

I haven't tried it myself, but I would suggest using Jest's toThrow assertion. So I guess your example would look something like this:

it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', (t) => {
  const error = t.throws(() => {
    throwError();
  }, TypeError);

  expect(t).toThrowError('UNKNOWN ERROR');
  //or
  expect(t).toThrowError(TypeError);
});

Again, I haven't test it, but I think it should work.

How to split and modify a string in NodeJS?

Use split and map function:

var str = "123, 124, 234,252";
var arr = str.split(",");
arr = arr.map(function (val) { return +val + 1; });

Notice +val - string is casted to a number.

Or shorter:

var str = "123, 124, 234,252";
var arr = str.split(",").map(function (val) { return +val + 1; });

edit 2015.07.29

Today I'd advise against using + operator to cast variable to a number. Instead I'd go with a more explicit but also more readable Number call:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(function (val) {_x000D_
  return Number(val) + 1;_x000D_
});_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

edit 2017.03.09

ECMAScript 2015 introduced arrow function so it could be used instead to make the code more concise:

_x000D_
_x000D_
var str = "123, 124, 234,252";_x000D_
var arr = str.split(",").map(val => Number(val) + 1);_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

I found many of the Q&A on this topic, not nothing was helping me - that's because my issue was more basic ( what can I say I am not a networking guru :) ). My ip address in /etc/hosts was incorrect. What I had tried included the following for CATALINA_OPTS:

CATALINA_OPTS="$CATALINA_OPTS -Djava.awt.headless=true -Xmx128M -server 
-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.port=7091 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname=A.B.C.D"  #howeverI put the wrong ip here!

export CATALINA_OPTS

My problem was that I had changed my ip address many months ago, but never updated my /etc/hosts file. it seems that by default the jconsole uses the hostname -i ip address in some fashion even though I was viewing local processes. The best solution was to simply change the /etc/hosts file.

The other solution which can work is to get your correct ip address from /sbin/ifconfig and use that ip address when specifying the ip address in, for example, a catalina.sh script:

-Djava.rmi.server.hostname=A.B.C.D

Using Python String Formatting with Lists

Here is a one liner. A little improvised answer using format with print() to iterate a list.

How about this (python 3.x):

sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))

Read the docs here on using format().

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Strict equality is for the most part better

The fact that Javascript is a loosely typed language needs to be in the front of your mind constantly as you work with it. As long as the data structure is the same there really is no reason as to not use strict equality, with regular equality you often have an implicit conversion of values that happens automatically, this can have far-reaching effects on your code. It is very easy to have problems with this conversion seeing as they happen automatically.

With strict equality there is no automatic implicit conversion as the values must already be of the correct data structure.

Saving results with headers in Sql Server Management Studio

Tools > Options > Query Results > SQL Server > Results to Text (or Grid if you want) > Include columns headers in the result set

You might need to close and reopen SSMS after changing this option.

On the SQL Editor Toolbar you can select save to file without having to restart SSMS

the MySQL service on local computer started and then stopped

  1. Open Service
  2. Right click on MYSQL service
  3. select Log on
  4. check local system account
  5. start service

ASP.net page without a code behind

yes on your aspx page include a script tag with runat=server

<script language="c#" runat="server">

public void Page_Load(object sender, EventArgs e)
{
  // some load code
}
</script>

You can also use classic ASP Syntax

<% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>

The property 'value' does not exist on value of type 'HTMLElement'

A quick fix for this is use [ ] to select the attribute.

function greet(elementId) {
    var inputValue = document.getElementById(elementId)["value"];
    if(inputValue.trim() == "") {
        inputValue = "World";
    }
    document.getElementById("greet").innerText = greeter(inputValue);
}

I just try few methods and find out this solution,
I don't know what's the problem behind your original script.

For reference you may refer to Tomasz Nurkiewicz's post.

Difference between id and name attributes in HTML

name Vs id

name

  • Name of the element. For example used by the server to identify the fields in form submits.
  • Supporting elements are <button>, <form>, <fieldset>, <iframe>, <input>, <keygen>, <object>, <output>, <select>, <textarea>, <map>, <meta>, <param>
  • Name does not have to be unique.

id

  • Often used with CSS to style a specific element. The value of this attribute must be unique.
  • Id is Global attributes, they can be used on all elements, though the attributes may have no effect on some elements.
  • Must be unique in the whole document.
  • This attribute's value must not contain white spaces, in contrast to the class attribute, which allows space-separated values.
  • Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.

How to make inactive content inside a div?

div[disabled]
{
  pointer-events: none;
  opacity: 0.7;
}

The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.

<div disabled>
  /* Contents */
</div>

How to detect idle time in JavaScript elegantly?

You could probably hack something together by detecting mouse movement on the body of the form and updating a global variable with the last movement time. You'd then need to have an interval timer running that periodically checks the last movement time and does something if it has been sufficiently long since the last mouse movement was detected.

Warning :-Presenting view controllers on detached view controllers is discouraged

Many answers are right.

  • Check your presentingViewController have parentViewController or not.
  • If no, add it to somewhere it should be added
  • else, check it's parentViewController has parentViewController recursively until every viewController has parent

This issue happened to me when my co-worker add a AViewController to BViewController. Somehow, he just add the AViewController's view to BViewController's view.

Fixed by add bViewController.addChild(aViewController)

Difference between multitasking, multithreading and multiprocessing?

A multiprogramming is the process when a computer system is performing different tasks all at once in a single computer system.

Detect application heap size in Android

Do you mean programatically, or just while you're developing and debugging? If the latter, you can see that info from the DDMS perspective in Eclipse. When your emulator (possibly even physical phone that is plugged in) is running, it will list the active processes in a window on the left. You can select it and there's an option to track the heap allocations.

How to show one layout on top of the other programmatically in my case?

Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...

Here is an example where a TextView is displayed on top of an ImageView:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <ImageView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 

    android:scaleType="center"
    android:src="@drawable/golden_gate" />

  <TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="12dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Golden Gate" />

</FrameLayout>

Here is the result

Storing Python dictionaries

If you're after serialization, but won't need the data in other programs, I strongly recommend the shelve module. Think of it as a persistent dictionary.

myData = shelve.open('/path/to/file')

# Check for values.
keyVar in myData

# Set values
myData[anotherKey] = someValue

# Save the data for future use.
myData.close()

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Rob Heiser suggested checking out your java version by using 'java -version'.

That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).

http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path

java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.

I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).

Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.

Get all files that have been modified in git branch

The accepted answer - git diff --name-only <notMainDev> $(git merge-base <notMainDev> <mainDev>) - is very close, but I noticed that it got the status wrong for deletions. I added a file in a branch, and yet this command (using --name-status) gave the file I deleted "A" status and the file I added "D" status.

I had to use this command instead:

git diff --name-only $(git merge-base <notMainDev> <mainDev>)

Print a div content using Jquery

Some jQuery research has failed, so I moved to JavaScript (thanks for your suggestion Anders).

And it is working well...

HTML

<div id='DivIdToPrint'>
    <p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printDiv();'>

JavaScript

function printDiv() 
{

  var divToPrint=document.getElementById('DivIdToPrint');

  var newWin=window.open('','Print-Window');

  newWin.document.open();

  newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

  newWin.document.close();

  setTimeout(function(){newWin.close();},10);

}

Explain ExtJS 4 event handling

Just wanted to add a couple of pence to the excellent answers above: If you are working on pre Extjs 4.1, and don't have application wide events but need them, I've been using a very simple technique that might help: Create a simple object extending Observable, and define any app wide events you might need in it. You can then fire those events from anywhere in your app, including actual html dom element and listen to them from any component by relaying the required elements from that component.

Ext.define('Lib.MessageBus', {
    extend: 'Ext.util.Observable',

    constructor: function() {
        this.addEvents(
            /*
             * describe the event
             */
                  "eventname"

            );
        this.callParent(arguments);
    }
});

Then you can, from any other component:

 this.relayEvents(MesageBus, ['event1', 'event2'])

And fire them from any component or dom element:

 MessageBus.fireEvent('event1', somearg);

 <input type="button onclick="MessageBus.fireEvent('event2', 'somearg')">

Moment.js - two dates difference in number of days

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
  var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

JSON formatter in C#?

You could also use the Newtonsoft.Json library for this and call SerializeObject with the Formatting.Indented enum -

var x = JsonConvert.SerializeObject(jsonString, Formatting.Indented);

Documentation: Serialize an Object


Update -

Just tried it again. Pretty sure this used to work - perhaps it changed in a subsequent version or perhaps i'm just imagining things. Anyway, as per the comments below, it doesn't quite work as expected. These do, however (just tested in linqpad). The first one is from the comments, the 2nd one is an example i found elsewhere in SO -

void Main()
{
    //Example 1
    var t = "{\"x\":57,\"y\":57.0,\"z\":\"Yes\"}";
    var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(t); 
    var f = Newtonsoft.Json.JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(f);

    //Example 2
    JToken jt = JToken.Parse(t);
    string formatted = jt.ToString(Newtonsoft.Json.Formatting.Indented);
    Console.WriteLine(formatted);

    //Example 2 in one line -
    Console.WriteLine(JToken.Parse(t).ToString(Newtonsoft.Json.Formatting.Indented));
}

How to center a checkbox in a table cell?

Make sure that your <td> is not display: block;

Floating will do this, but much easier to just: display: inline;

Notepad++ Setting for Disabling Auto-open Previous Files

I read the answers. Then I noticed for me that the check box was already unchecked, but it still always reloaded the files. This is the Settings->Preferences->MISC->"Remember current session for next launch" check box on version 6.3.2. The following got rid of the problem:

1. Check the check box.
2. Exit the program.
3. Start the program again.
4. Uncheck the checkbox.

Link to reload current page

There is no global way of doing this unfortunately with only HTML. You can try doing <a href="">test</a> however it only works in some browsers.

jQuery Data vs Attr?

You can use data-* attribute to embed custom data. The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.

jQuery .data() method allows you to get/set data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

jQuery .attr() method get/set attribute value for only the first element in the matched set.

Example:

<span id="test" title="foo" data-kind="primary">foo</span>

$("#test").attr("title");
$("#test").attr("data-kind");
$("#test").data("kind");
$("#test").data("value", "bar");

call javascript function onchange event of dropdown list

Your code is working just fine, you have to declare javscript method before DOM ready.

your working example

Change the background color of CardView programmatically

In Kotlin, I was able to change the background color like this:

var card: CardView = itemView.findViewById(com.mullr.neurd.R.id.learn_def_card)
card.setCardBackgroundColor(ContextCompat.getColor(main,R.color.selected))

Then if you want to remove the color, you can do this:

card.setCardBackgroundColor(Color.TRANSPARENT)

Using this method I was able to create a selection animation.
https://gfycat.com/equalcarefreekitten

PostgreSQL naming conventions

There isn't really a formal manual, because there's no single style or standard.

So long as you understand the rules of identifier naming you can use whatever you like.

In practice, I find it easier to use lower_case_underscore_separated_identifiers because it isn't necessary to "Double Quote" them everywhere to preserve case, spaces, etc.

If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42" you'd be free to do that, though it'd be pain to type everywhere.

The main things to understand are:

  • Unless double-quoted, identifiers are case-folded to lower-case, so MyTable, MYTABLE and mytable are all the same thing, but "MYTABLE" and "MyTable" are different;

  • Unless double-quoted:

    SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).

  • You must double-quote keywords if you wish to use them as identifiers.

In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with" doesn't mean you should.

7-Zip command to create and extract a password-protected ZIP file on Windows?

To fully script-automate:

Create:

7z -mhc=on -mhe=on -pPasswordHere a %ZipDest% %WhatYouWantToZip%

Unzip:

7z x %ZipFile% -pPasswordHere

(Depending, you might need to: Set Path=C:\Program Files\7-Zip;%Path% )

Make Vim show ALL white spaces as a character

Adding this to my .vimrc works for me. Just make sure you don't have anything else conflicting..

autocmd VimEnter * :syn match space /\s/
autocmd VimEnter * :hi space ctermbg=lightgray ctermfg=black guibg=lightgray guifg=black

Convert nullable bool? to bool

Something like:

if (bn.HasValue)
{
  b = bn.Value
}

Getting the folder name from a path

Simple & clean. Only uses System.IO.FileSystem - works like a charm:

string path = "C:/folder1/folder2/file.txt";
string folder = new DirectoryInfo(path).Name;

C++ convert hex string to signed integer

just use stoi/stol/stoll for example:

std::cout << std::stol("fffefffe", nullptr, 16) << std::endl;

output: 4294901758

How to calculate time elapsed in bash script?

Another option is to use datediff from dateutils (http://www.fresse.org/dateutils/#datediff):

$ datediff 10:33:56 10:36:10
134s
$ datediff 10:33:56 10:36:10 -f%H:%M:%S
0:2:14
$ datediff 10:33:56 10:36:10 -f%0H:%0M:%0S
00:02:14

You could also use gawk. mawk 1.3.4 also has strftime and mktime but older versions of mawk and nawk don't.

$ TZ=UTC0 awk 'BEGIN{print strftime("%T",mktime("1970 1 1 10 36 10")-mktime("1970 1 1 10 33 56"))}'
00:02:14

Or here's another way to do it with GNU date:

$ date -ud@$(($(date -ud'1970-01-01 10:36:10' +%s)-$(date -ud'1970-01-01 10:33:56' +%s))) +%T
00:02:14

Parenthesis/Brackets Matching using Stack algorithm

Was asked to implement this algorithm at live coding interview, here's my refactored solution in C#:

Git Tests

git: fatal: I don't handle protocol '??http'

Well looks like if you copy paste the repository link you end up with this issue.

What I have noticed it this

  1. If you use the copy button on GitHub and then paste the URL in GitBash(Windows) it throws this error
  2. If you select the link and then paste then it works, or you could also just type the URL that works as well.

So I think it might be an issue with the GitHub copy button

How do I check for a network connection?

The marked answer is 100% fine, however, there are certain cases when the standard method is fooled by virtual cards (virtual box, ...). It's also often desirable to discard some network interfaces based on their speed (serial ports, modems, ...).

Here is a piece of code that checks for these cases:

    /// <summary>
    /// Indicates whether any network connection is available
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable()
    {
        return IsNetworkAvailable(0);
    }

    /// <summary>
    /// Indicates whether any network connection is available.
    /// Filter connections below a specified speed, as well as virtual network cards.
    /// </summary>
    /// <param name="minimumSpeed">The minimum speed required. Passing 0 will not filter connection using speed.</param>
    /// <returns>
    ///     <c>true</c> if a network connection is available; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsNetworkAvailable(long minimumSpeed)
    {
        if (!NetworkInterface.GetIsNetworkAvailable())
            return false;

        foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
        {
            // discard because of standard reasons
            if ((ni.OperationalStatus != OperationalStatus.Up) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
                (ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))
                continue;

            // this allow to filter modems, serial, etc.
            // I use 10000000 as a minimum speed for most cases
            if (ni.Speed < minimumSpeed)
                continue;

            // discard virtual cards (virtual box, virtual pc, etc.)
            if ((ni.Description.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0) ||
                (ni.Name.IndexOf("virtual", StringComparison.OrdinalIgnoreCase) >= 0))
                continue;

            // discard "Microsoft Loopback Adapter", it will not show as NetworkInterfaceType.Loopback but as Ethernet Card.
            if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
                continue;

            return true;
        }
        return false;
    }

Install opencv for Python 3.3

I know this is an old thread, but just in case anyone is looking, here is how I got it working on El Capitan:

brew install opencv3 --with-python3

and wait a while for it to finish.

Then run the following as necessary:

brew unlink opencv

Then run the following as the final step:

brew ln opencv3 --force

Now you should be able to run import cv2 no problem in a python 3.x script.

PHP Warning: Division by zero

try this

if(isset($itemCost) != '' && isset($itemQty) != '')
{
    $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}
else
{
    echo "either of itemCost or itemQty are null";
}

How To Include CSS and jQuery in my WordPress plugin?

See http://codex.wordpress.org/Function_Reference/wp_enqueue_script

Example

<?php
function my_init_method() {
    wp_deregister_script( 'jquery' );
    wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js');
}    

add_action('init', 'my_init_method');
?> 

apache server reached MaxClients setting, consider raising the MaxClients setting

I recommend to use bellow formula suggested on Apache:

MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)

Find my script here which is running on Rhel 6.7. you can made change according to your OS.

#!/bin/bash

echo "HostName=`hostname`"

#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit

What is the difference between a .cpp file and a .h file?

A good rule of thumb is ".h files should have declarations [potentially] used by multiple source files, but no code that gets run."

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

Use this extension for chrome. Allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related

How to get back to the latest commit after checking out a previous commit?

You can use one of the following git command for this:

git checkout master
git checkout branchname