Programs & Examples On #Sharepoint wiki

Selenium Webdriver move mouse to Point

Got it working with

Actions builder = new Actions(driver);
WebElement el = some element;
builder.keyDown(Keys.CONTROL)
.moveByOffset( 10, 25 )
.clickAndHold(el)
.build().perform();

Read and overwrite a file in Python

I find it easier to remember to just read it and then write it.

For example:

with open('file') as f:
    data = f.read()
with open('file', 'w') as f:
    f.write('hello')

How to multi-line "Replace in files..." in Notepad++

Actually it's way easier to use ToolBucket plugin for Notepad++ to multiline replace.

To activate it just go to N++ menu:

Plugins > Plugin Manager > Show Plugin Manager > Check ToolBucket > Install.

Restart N++ and press ALT + SHIFT + F to multiline edit.

Check if list is empty in C#

If the list implementation you're using is IEnumerable<T> and Linq is an option, you can use Any:

if (!list.Any()) {

}

Otherwise you generally have a Length or Count property on arrays and collection types respectively.

AngularJS - $http.post send data as json

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):

$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
        .then(function (response) {
            return response;
        });

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

You should simply apply the following transformation to your input data array.

input_data = input_data.reshape((-1, image_side1, image_side2, channels))

Dynamically update values of a chartjs chart

You just need to change the chartObject.data.datasets value and call update() like this:

chartObject.data.datasets = newData.datasets;
chartObject.data.labels = newData.labels;
chartObject.update();

How to get Android crash logs?

I have created this library to solve all your problems. Crash Reporter is a handy tool to capture all your crashes and log them in device locally

Just add this dependency and you're good to go.

compile 'com.balsikandar.android:crashreporter:1.0.1'

Find all your crashes in device locally and fix them at your convenience. Crashes are saved using date and time format easy to track. Plus it also provides API for capture Logged Exceptions using below method.

CrashRepoter.logException(Exception e)

How to get a complete list of object's methods and attributes?

Here is a practical addition to the answers of PierreBdR and Moe:

  • For Python >= 2.6 and new-style classes, dir() seems to be enough.
  • For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir(), look for __class__, and then to go for its __bases__:

    # code borrowed from the rlcompleter module
    # tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
    
    # or: from rlcompleter import get_class_members
    def get_class_members(klass):
        ret = dir(klass)
        if hasattr(klass,'__bases__'):
            for base in klass.__bases__:
                ret = ret + get_class_members(base)
        return ret
    
    
    def uniq( seq ): 
        """ the 'set()' way ( use dict when there's no set ) """
        return list(set(seq))
    
    
    def get_object_attrs( obj ):
        # code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
        ret = dir( obj )
        ## if "__builtins__" in ret:
        ##    ret.remove("__builtins__")
    
        if hasattr( obj, '__class__'):
            ret.append('__class__')
            ret.extend( get_class_members(obj.__class__) )
    
            ret = uniq( ret )
    
        return ret
    

(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs() as for dir(), and for old-style classes the main addition to the dir() output seem to be the __class__ attribute.)

How do I modify fields inside the new PostgreSQL JSON datatype?

To build upon @pozs's answers, here are a couple more PostgreSQL functions which may be useful to some. (Requires PostgreSQL 9.3+)

Delete By Key: Deletes a value from JSON structure by key.

CREATE OR REPLACE FUNCTION "json_object_del_key"(
  "json"          json,
  "key_to_del"    TEXT
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_to_del") IS NULL THEN "json"
  ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
          FROM (SELECT *
                  FROM json_each("json")
                 WHERE "key" <> "key_to_del"
               ) AS "fields")::json
END
$function$;

Recursive Delete By Key: Deletes a value from JSON structure by key-path. (requires @pozs's json_object_set_key function)

CREATE OR REPLACE FUNCTION "json_object_del_path"(
  "json"          json,
  "key_path"      TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_path"[l] ) IS NULL THEN "json"
  ELSE
     CASE COALESCE(array_length("key_path", 1), 0)
         WHEN 0 THEN "json"
         WHEN 1 THEN "json_object_del_key"("json", "key_path"[l])
         ELSE "json_object_set_key"(
           "json",
           "key_path"[l],
           "json_object_del_path"(
             COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
             "key_path"[l+1:u]
           )
         )
       END
    END
  FROM array_lower("key_path", 1) l,
       array_upper("key_path", 1) u
$function$;

Usage examples:

s1=# SELECT json_object_del_key ('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 'foo'),
            json_object_del_path('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 '{"foo","moe"}');

 json_object_del_key |          json_object_del_path
---------------------+-----------------------------------------
 {"hello":[7,3,1]}   | {"hello":[7,3,1],"foo":{"mofu":"fuwa"}}

Open window in JavaScript with HTML inserted

I would not recomend you to use document.write as others suggest, because if you will open such window twice your HTML will be duplicated 2 times (or more).

Use innerHTML instead

var win = window.open("", "Title", "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top="+(screen.height-400)+",left="+(screen.width-840));
win.document.body.innerHTML = "HTML";

how to permit an array with strong parameters

when you want to permit multiple array fields you will have to list array fields at last while permitting ,as given -

params.require(:questions).permit(:question, :user_id, answers: [], selected_answer: [] )

(this works)

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

How to get arguments with flags in Bash

This is the idiom I usually use:

while test $# -gt 0; do
  case "$1" in
    -h|--help)
      echo "$package - attempt to capture frames"
      echo " "
      echo "$package [options] application [arguments]"
      echo " "
      echo "options:"
      echo "-h, --help                show brief help"
      echo "-a, --action=ACTION       specify an action to use"
      echo "-o, --output-dir=DIR      specify a directory to store output in"
      exit 0
      ;;
    -a)
      shift
      if test $# -gt 0; then
        export PROCESS=$1
      else
        echo "no process specified"
        exit 1
      fi
      shift
      ;;
    --action*)
      export PROCESS=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    -o)
      shift
      if test $# -gt 0; then
        export OUTPUT=$1
      else
        echo "no output dir specified"
        exit 1
      fi
      shift
      ;;
    --output-dir*)
      export OUTPUT=`echo $1 | sed -e 's/^[^=]*=//g'`
      shift
      ;;
    *)
      break
      ;;
  esac
done

Key points are:

  • $# is the number of arguments
  • while loop looks at all the arguments supplied, matching on their values inside a case statement
  • shift takes the first one away. You can shift multiple times inside of a case statement to take multiple values.

Why calling react setState method doesn't mutate the state immediately?

As mentioned in the React documentation, there is no guarantee of setState being fired synchronously, so your console.log may return the state prior to it updating.

Michael Parker mentions passing a callback within the setState. Another way to handle the logic after state change is via the componentDidUpdate lifecycle method, which is the method recommended in React docs.

Generally we recommend using componentDidUpdate() for such logic instead.

This is particularly useful when there may be successive setStates fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState, you could place the function inside of the componentDidUpdate, with specific logic inside if necessary.

// example
componentDidUpdate(prevProps, prevState) {
  if (this.state.value > prevState.value) {
    this.foo();  
  }
}

How to fix apt-get: command not found on AWS EC2?

please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like

AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1 

hope it helps

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Just add autofocus in first input or textarea.

<input type="text" name="name" id="xax" autofocus="autofocus" />

Pass array to MySQL stored routine

Use a join with a temporary table. You don't need to pass temporary tables to functions, they are global.

create temporary table ids( id int ) ;
insert into ids values (1),(2),(3) ;

delimiter //
drop procedure if exists tsel //
create procedure tsel() -- uses temporary table named ids. no params
READS SQL DATA
BEGIN
  -- use the temporary table `ids` in the SELECT statement or
  -- whatever query you have
  select * from Users INNER JOIN ids on userId=ids.id ;
END //
DELIMITER ;

CALL tsel() ; -- call the procedure

How to change color of Android ListView separator line?

For a single color line use:

list.setDivider(new ColorDrawable(0x99F10529));   //0xAARRGGBB
list.setDividerHeight(1);

It's important that DividerHeight is set after the divider, else you won't get anything.

Android webview launches browser when calling loadurl

Make your Activity like this.

public class MainActivity extends Activity {
WebView browser;

@Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // find the WebView by name in the main.xml of step 2
    browser=(WebView)findViewById(R.id.wvwMain);

    // Enable javascript
    browser.getSettings().setJavaScriptEnabled(true);  

    // Set WebView client
    browser.setWebChromeClient(new WebChromeClient());

    browser.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
                }
        });
     // Load the webpage
    browser.loadUrl("http://google.com/");
   }
}

Initialize a byte array to a certain value, other than the default null?

You could speed up the initialization and simplify the code by using the the Parallel class (.NET 4 and newer):

public static void PopulateByteArray(byte[] byteArray, byte value)
{
    Parallel.For(0, byteArray.Length, i => byteArray[i] = value);
}

Of course you can create the array at the same time:

public static byte[] CreateSpecialByteArray(int length, byte value)
{
    var byteArray = new byte[length];
    Parallel.For(0, length, i => byteArray[i] = value);
    return byteArray;
}

Add new field to every document in a MongoDB collection

Since MongoDB version 3.2 you can use updateMany():

> db.yourCollection.updateMany({}, {$set:{"someField": "someValue"}})

Font is not available to the JVM with Jasper Reports

I tried installing mscorefonts, but the package was installed and up-to-date.

sudo apt-get update
sudo apt-get install ttf-mscorefonts-installer

I tried searching for the font in the filesystem, with:

ls /usr/share/fonts/truetype/msttcorefonts/

This folder just had the README, with the correct instructions on how to install.

cat /usr/share/fonts/truetype/msttcorefonts/README

You need an internet connection for this:

sudo apt-get install --reinstall ttf-mscorefonts-installer

I re-installed ttf-mscorefonts-installer (as shown above, making sure to accept the EULA!) and the problem was solved.

How can I change my Cygwin home folder after installation?

Starting with Cygwin 1.7.34, the recommended way to do this is to add a custom db_home setting to /etc/nsswitch.conf. A common wish when doing this is to make your Cygwin home directory equal to your Windows user profile directory. This setting will do that:

db_home: windows

Or, equivalently:

db_home: /%H

You need to use the latter form if you want some variation on this scheme, such as to segregate your Cygwin home files into a subdirectory of your Windows user profile directory:

db_home: /%H/cygwin

There are several other alternative schemes for the windows option plus several other % tokens you can use instead of %H or in addition to it. See the nsswitch.conf syntax description in the Cygwin User Guide for details.

If you installed Cygwin prior to 1.7.34 or have run its mkpasswd utility so that you have an /etc/passwd file, you can change your Cygwin home directory by editing your user's entry in that file. Your home directory is the second-to-last element on your user's line in /etc/passwd

Whichever way you do it, this causes the HOME environment variable to be set during shell startup.²

See this FAQ item for more on the topic.


Footnotes:

  1. Consider moving /etc/passwd and /etc/group out of the way in order to use the new SAM/AD-based mechanism instead.

  2. While it is possible to simply set %HOME% via the Control Panel, it is officially discouraged. Not only does it unceremoniously override the above mechanisms, it doesn't always work, such as when running shell scripts via cron.

How to get Printer Info in .NET?

As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.

using System.Management;

...

string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
    try
    {
        foreach (ManagementObject printer in coll)
        {
            foreach (PropertyData property in printer.Properties)
            {
                Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
            }
        }
    }
    catch (ManagementException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

How can I get the order ID in WooCommerce?

it worked. Just modified it

global $woocommerce, $post;

$order = new WC_Order($post->ID);

//to escape # from order id 

$order_id = trim(str_replace('#', '', $order->get_order_number()));

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

Remove IE10's "clear field" X button on certain inputs?

To hide arrows and cross in a "time" input :

#inputId::-webkit-outer-spin-button,
#inputId::-webkit-inner-spin-button,
#inputId::-webkit-clear-button{
    -webkit-appearance: none;
    margin: 0;
}

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

How do I revert a Git repository to a previous commit?

Revert is the command to rollback the commits.

git revert <commit1> <commit2> 

Sample:

git revert 2h3h23233

It is capable of taking range from the HEAD like below. Here 1 says "revert last commit."

git revert HEAD~1..HEAD

and then do git push

How to remove unused dependencies from composer?

Just run composer install - it will make your vendor directory reflect dependencies in composer.lock file.

In other words - it will delete any vendor which is missing in composer.lock.

Please update the composer itself before running this.

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio Code is integrated with a command prompt / terminal, hence it will be handy when there is switching between IDE and terminal / command prompt required, for example: connecting to Linux.

How do I horizontally center a span element inside a div

I assume you want to center them on one line and not on two separate lines based on your fiddle. If that is the case, try the following css:

 div { background:red;
      overflow:hidden;
}
span { display:block;
       margin:0 auto;
       width:200px;
}
span a { padding:5px 10px;
         color:#fff;
         background:#222;
}

I removed the float since you want to center it, and then made the span surrounding the links centered by adding margin:0 auto to them. Finally, I added a static width to the span. This centers the links on one line within the red div.

Avoid printStackTrace(); use a logger call instead

It means you should use logging framework like or and instead of printing exceptions directly:

e.printStackTrace();

you should log them using this frameworks' API:

log.error("Ops!", e);

Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

How to move screen without moving cursor in Vim?

my mnemonic for scrolling...

Adding to other answers also pay attention to ze and zs, meaning: move screen to the left/right of the cursor (without moving the cursor)

+-------------------------------+
^                               |
|c-e (keep cursor)              |
|H(igh)             zt (top)    |
|                   ^           |
|           ze      |      zs   |
|M(iddle)  zh/zH <--zz--> zl/zL |
|                   |           |
|                   v           |
|L(ow)              zb (bottom) |
|c-y (keep cursor)              |
v                               |
+-------------------------------+

also look at the position of h and l and t and b and (with qwertz keyboard) c-e and c-y (also the "y" somehow points to the bottom) on the keyboard to remember where the screen is moving.

How to "add existing frameworks" in Xcode 4?

I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.

Formula px to dp, dp to px android

Feel free to use this method I wrote:

int dpToPx(int dp)
{
    return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}

Characters allowed in GET parameter

Alphanumeric characters and all of

~ - _ . ! * ' ( ) ,

are valid within an URL.

All other characters must be encoded.

Check if a value exists in pandas dataframe index

Code below does not print boolean, but allows for dataframe subsetting by index... I understand this is likely not the most efficient way to solve the problem, but I (1) like the way this reads and (2) you can easily subset where df1 index exists in df2:

df3 = df1[df1.index.isin(df2.index)]

or where df1 index does not exist in df2...

df3 = df1[~df1.index.isin(df2.index)]

How to use onClick with divs in React.js

Your box doesn't have a size. If you set the width and height, it works just fine:

_x000D_
_x000D_
var Box = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return {_x000D_
            color: 'black'_x000D_
        };_x000D_
    },_x000D_
_x000D_
    changeColor: function() {_x000D_
        var newColor = this.state.color == 'white' ? 'black' : 'white';_x000D_
        this.setState({_x000D_
            color: newColor_x000D_
        });_x000D_
    },_x000D_
_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <div_x000D_
                    style = {{_x000D_
                        background: this.state.color,_x000D_
                        width: 100,_x000D_
                        height: 100_x000D_
                    }}_x000D_
                    onClick = {this.changeColor}_x000D_
                >_x000D_
                </div>_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Box />,_x000D_
  document.getElementById('box')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='box'></div>
_x000D_
_x000D_
_x000D_

What are the different NameID format used for?

Refer to Section 8.3 of this SAML core pdf of oasis SAML specification.

SP and IdP usually communicate each other about a subject. That subject should be identified through a NAME-IDentifier , which should be in some format so that It is easy for the other party to identify it based on the Format.

All these

1.urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified [default]

2.urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress

3.urn:oasis:names:tc:SAML:2.0:nameid-format:persistent

4.urn:oasis:names:tc:SAML:2.0:nameid-format:transient

are format for the Name Identifiers.

The name format for a transient ID in SAML 1 is urn:mace:shibboleth:1.0:nameIdentifier and in SAML 2 is urn:oasis:names:tc:SAML:2.0:nameid-format:transient

Transient is for [section 8.3.8 of SAML Core]

Indicates that the content of the element is an identifier with transient semantics and SHOULD be treated as an opaque and temporary value by the relying party.

Unspecified can be used and it purely depends on the entities implementation on their own wish.

How to list the size of each file and directory and sort by descending size in Bash?

I tend to use du in a simple way.

du -sh */ | sort -n

This provides me with an idea of what directories are consuming the most space. I can then run more precise searches later.

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

In Run->Run Configuration find the Name of the class you have been running, select it, click the Arguments tab then add:

-Xms512M -Xmx1524M

to the VM Arguments section

Extracting Ajax return data in jQuery

You can use .filter on a jQuery object that was created from the response:

success: function(data){
    //Create jQuery object from the response HTML.
    var $response=$(data);

    //Query the jQuery object for the values
    var oneval = $response.filter('#one').text();
    var subval = $response.filter('#sub').text();
}

How to set Python's default version to 3.x on OS X?

If you are using a virtualenvwrapper, you can just locate it using which virtualenvwrapper.sh, then open it using vim or any other editor then change the following

# Locate the global Python where virtualenvwrapper is installed.
if [ "${VIRTUALENVWRAPPER_PYTHON:-}" = "" ]
then
    VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
fi

Change the line VIRTUALENVWRAPPER_PYTHON="$(command \which python)" to VIRTUALENVWRAPPER_PYTHON="$(command \which python3)".

How can I define colors as variables in CSS?

You could pass the CSS through javascript and replace all instances of COLOUR1 with a certain color (basically regex it) and provide a backup stylesheet incase the end user has JS turned off

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

'MOD' is not a recognized built-in function name

The MOD keyword only exists in the DAX language (tabular dimensional queries), not TSQL

Use % instead.

Ref: Modulo

Android canvas draw rectangle

Try paint.setStyle(Paint.Style.STROKE)?

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

Spring Boot Multiple Datasource

Using two datasources you need their own transaction managers.

@Configuration
public class MySqlDBConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="datasource.test.mysql")
    public DataSource mysqlDataSource(){
         return DataSourceBuilder
                 .create()
                 .build();
    }

    @Bean("mysqlTx")
    public DataSourceTransactionManager mysqlTx() {
        return new DataSourceTransactionManager(mysqlDataSource());
    }

    // same for another DS
}

And then use it accordingly within @Transaction

@Transactional("mysqlTx")
@Repository
public interface UserMysqlDao extends CrudRepository<UserMysql, Integer>{
    public UserMysql findByName(String name);
}

How to start jenkins on different port rather than 8080 using command prompt in Windows?

To change the default port of 8080. All you need to do:

  1. Goto Jenkins folder present in C:\Program Files (x86)
  2. Open a notepad or text pad and run them as administrator and then try opening the jenkins.xml file present in the jenkins folder.
  3. Change the port number as below: <arguments>-Xrs -Xmx256m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=9090</arguments>
  4. Click Save.

How can I remove a pytz timezone from a datetime object?

To remove a timezone (tzinfo) from a datetime object:

# dt_tz is a datetime.datetime object
dt = dt_tz.replace(tzinfo=None)

If you are using a library like arrow, then you can remove timezone by simply converting an arrow object to to a datetime object, then doing the same thing as the example above.

# <Arrow [2014-10-09T10:56:09.347444-07:00]>
arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444, tzinfo=tzoffset(None, -25200))
tmpDatetime = arrowObj.datetime

# datetime.datetime(2014, 10, 9, 10, 56, 9, 347444)
tmpDatetime = tmpDatetime.replace(tzinfo=None)

Why would you do this? One example is that mysql does not support timezones with its DATETIME type. So using ORM's like sqlalchemy will simply remove the timezone when you give it a datetime.datetime object to insert into the database. The solution is to convert your datetime.datetime object to UTC (so everything in your database is UTC since it can't specify timezone) then either insert it into the database (where the timezone is removed anyway) or remove it yourself. Also note that you cannot compare datetime.datetime objects where one is timezone aware and another is timezone naive.

##############################################################################
# MySQL example! where MySQL doesn't support timezones with its DATETIME type!
##############################################################################

arrowObj = arrow.get('2014-10-09T10:56:09.347444-07:00')

arrowDt = arrowObj.to("utc").datetime

# inserts datetime.datetime(2014, 10, 9, 17, 56, 9, 347444, tzinfo=tzutc())
insertIntoMysqlDatabase(arrowDt)

# returns datetime.datetime(2014, 10, 9, 17, 56, 9, 347444)
dbDatetimeNoTz = getFromMysqlDatabase()

# cannot compare timzeone aware and timezone naive
dbDatetimeNoTz == arrowDt # False, or TypeError on python versions before 3.3

# compare datetimes that are both aware or both naive work however
dbDatetimeNoTz == arrowDt.replace(tzinfo=None) # True

How to install an APK file on an Android phone?

For debugging:

  • Enable USB debugging on your phone (settings -> applications -> development).
  • Connect your phone to the computer, and make sure you have the correct drivers installed.
  • In Eclipse, run your project as an Android application (right click project -> run as -> Android application).

Installing the APK file:

  • Export the APK file, make sure you sign it (right click project -> Android tools -> export signed application package).
  • Connect your phone, USB debugging enabled.
  • from the terminal, use ADB to install the APK file (adb install path-to-your-apk-file.apk).

Get data from fs.readFile

var path = "index.html"

const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)

using simple readFileSync works for me.

What does -1 mean in numpy reshape?

It is fairly easy to understand. The "-1" stands for "unknown dimension" which can should be infered from another dimension. In this case, if you set your matrix like this:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])

Modify your matrix like this:

b = numpy.reshape(a, -1)

It will call some deafult operations to the matrix a, which will return a 1-d numpy array/martrix.

However, I don't think it is a good idea to use code like this. Why not try:

b = a.reshape(1,-1)

It will give you the same result and it's more clear for readers to understand: Set b as another shape of a. For a, we don't how much columns it should have(set it to -1!), but we want a 1-dimension array(set the first parameter to 1!).

Wait until an HTML5 video loads

you can use preload="none" in the attribute of video tag so the video will be displayed only when user clicks on play button.

_x000D_
_x000D_
<video preload="none">
_x000D_
_x000D_
_x000D_

How does one represent the empty char?

The empty space char would be ' '. If you're looking for null that would be '\0'.

What are bitwise shift (bit-shift) operators and how do they work?

Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.

For example:

(long) 4 >> 65

equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:

(long) 4 >> (65 % 64)

This is true for <<, >>, and >>>. I have not tried it out in other languages.

Is it possible to serialize and deserialize a class in C++?

You can check the amef protocol, an example of C++ encoding in amef would be like,

    //Create a new AMEF object
    AMEFObject *object = new AMEFObject();

    //Add a child string object
    object->addPacket("This is the Automated Message Exchange Format Object property!!","adasd");   

    //Add a child integer object
    object->addPacket(21213);

    //Add a child boolean object
    object->addPacket(true);

    AMEFObject *object2 = new AMEFObject();
    string j = "This is the property of a nested Automated Message Exchange Format Object";
    object2->addPacket(j);
    object2->addPacket(134123);
    object2->addPacket(false);

    //Add a child character object
    object2->addPacket('d');

    //Add a child AMEF Object
    object->addPacket(object2);

    //Encode the AMEF obejct
    string str = new AMEFEncoder()->encode(object,false);

Decoding in java would be like,

    string arr = amef encoded byte array value;
    AMEFDecoder decoder = new AMEFDecoder()
    AMEFObject object1 = AMEFDecoder.decode(arr,true);

The Protocol implementation has codecs for both C++ and Java, the interesting part is it can retain object class representation in the form of name value pairs, I required a similar protocol in my last project, when i incidentally stumbled upon this protocol, i had actually modified the base library according to my requirements. Hope this helps you.

How can I make one python file run another?

  • you can run your .py file simply with this code:

import os 
os.system('python filename.py')

note: put the file in the same directory of your main python file.

I want to show all tables that have specified column name

You can find what you're looking for in the information schema: SQL Server 2005 System Tables and Views I think you need SQL Server 2005 or higher to use the approach described in this article, but a similar method can be used for earlier versions.

Redirect output of mongo query to a csv file

Extending other answers:

I found @GEverding's answer most flexible. It also works with aggregation:

test_db.js

print("name,email");

db.users.aggregate([
    { $match: {} }
]).forEach(function(user) {
        print(user.name+","+user.email);
    }
});

Execute the following command to export results:

mongo test_db < ./test_db.js >> ./test_db.csv

Unfortunately, it adds additional text to the CSV file which requires processing the file before we can use it:

MongoDB shell version: 3.2.10 
connecting to: test_db

But we can make mongo shell stop spitting out those comments and only print what we have asked for by passing the --quiet flag

mongo --quiet test_db < ./test_db.js >> ./test_db.csv

Convert NSData to String?

Swift 5:

String(data: data!, encoding: String.Encoding.utf8)

How to concatenate strings in django templates?

You do not need to write a custom tag. Just evaluate the vars next to each other.

"{{ shop name }}{{ other_path_var}}"

Unique constraint violation during insert: why? (Oracle)

Presumably, since you're not providing a value for the DB_ID column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.

Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID that is currently in the table leading to the error.

You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a

SELECT <<sequence name>>.nextval
  FROM dual

and comparing that to

SELECT MAX(db_id)
  FROM cmdb_db

If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT to something very large, get the nextval once, and set the INCREMENT back to 1.

Algorithm to calculate the number of divisors of a given number

Isn't this just a question of factoring the number - determining all the factors of the number? You can then decide whether you need all combinations of one or more factors.

So, one possible algorithm would be:

factor(N)
    divisor = first_prime
    list_of_factors = { 1 }
    while (N > 1)
        while (N % divisor == 0)
            add divisor to list_of_factors
            N /= divisor
        divisor = next_prime
    return list_of_factors

It is then up to you to combine the factors to determine the rest of the answer.

Array.push() and unique items

Yep, it's a small mistake.

if(this.items.indexOf(item) === -1) {
    this.items.push(item);
    console.log(this.items);
}

Completely removing phpMyAdmin

I was having a similar problem. PHP was working on my sites configured by virtualmin but not for phpmyadmin. PHPMyAdmin would not execute and the file was being downloaded by the browser. Everything I was reading was saying that libapache2-mod-php5 was not installed but I knew it was... so the thing to do was to purge it and reinstall.

sudo apt-get purge libapache2-mod-php5

sudo apt-get install libapache2-mod-php5

sudo apt-get purge phpmyadmin

sudo apt-get install phpmyadmin

sudo /etc/init.d/apache2 restart

jQuery - getting custom attribute from selected option

Try this:

$(function() { 
    $("#location").change(function(){ 
        var element = $(this).find('option:selected'); 
        var myTag = element.attr("myTag"); 

        $('#setMyTag').val(myTag); 
    }); 
}); 

Brew doctor says: "Warning: /usr/local/include isn't writable."

Work for me

$ sudo chown -R $(whoami):admin /usr/local

$ cd /usr/local/Library && git stash && git clean -d -f

How to label each equation in align environment?

like this

\begin{align} 

x_{\rm L} & = L \int{\cos\theta\left(\xi\right) d\xi}, \label{eq_1} \\\\

y_{\rm L} & = L \int{\sin\theta\left(\xi\right) d\xi}, \nonumber

\end{align}

Maven : error in opening zip file when running maven

  1. I deleted the jar downloaded by maven
  2. manually download the jar from google
  3. place the jar in the local repo in place of deleted jar.

This resolved my problem.

Hope it helps

List names of all tables in a SQL Server 2012 schema

SELECT *
FROM sys.tables t
INNER JOIN sys.objects o on o.object_id = t.object_id
WHERE o.is_ms_shipped = 0;

FileNotFoundException..Classpath resource not found in spring?

This is due to spring-config.xml is not in classpath.

Add complete path of spring-config.xml to your classpath.

Also write command you execute to run your project. You can check classpath in command.

Regex Last occurrence?

One that worked for me was:

.+(\\.+)$

Try it online!

Explanation:

.+     - any character except newline
(      - create a group
 \\.+   - match a backslash, and any characters after it
)      - end group
$      - this all has to happen at the end of the string

Center Contents of Bootstrap row container

I solved this by doing the following:

<body class="container-fluid">
    <div class="row">
        <div class="span6" style="float: none; margin: 0 auto;">
           ....
        </div>
    </div>
</body>

Pass parameters in setInterval function

I have had the same problem with Vue app. In my case this solution is only works if anonymous function has declared as arrow function, regarding declaration at mounted () life circle hook.

text-overflow: ellipsis not working

You may try using ellipsis by adding the following in CSS:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631

Submit form using AJAX and jQuery

First give your form an id attribute, then use code like this:

$(document).ready( function() {
  var form = $('#my_awesome_form');

  form.find('select:first').change( function() {
    $.ajax( {
      type: "POST",
      url: form.attr( 'action' ),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );
  } );

} );

So this code uses .serialize() to pull out the relevant data from the form. It also assumes the select you care about is the first one in the form.

For future reference, the jQuery docs are very, very good.

Appending HTML string to the DOM

Performance

AppendChild (E) is more than 2x faster than other solutions on chrome and safari, insertAdjacentHTML(F) is fastest on firefox. The innerHTML= (B) (do not confuse with += (A)) is second fast solution on all browsers and it is much more handy than E and F.

Details

Set up environment (2019.07.10) MacOs High Sierra 10.13.4 on Chrome 75.0.3770 (64-bit), Safari 11.1.0 (13604.5.6), Firefox 67.0.0 (64-bit)

enter image description here

  • on Chrome E (140k operations per second) is fastest, B (47k) and F (46k) are second, A (332) is slowest
  • on firefox F (94k) is fastest, then B(80k), D (73k), E(64k), C (21k) slowest is A(466)
  • on Safari E(207k) is fastest, then B(89k), F(88k), D(83k), C (25k), slowest is A(509)

You can replay test in your machine here

_x000D_
_x000D_
function A() {    _x000D_
  container.innerHTML += '<p>A: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function B() {    _x000D_
  container.innerHTML = '<p>B: Just some <span>text</span> here</p>';_x000D_
}_x000D_
_x000D_
function C() {    _x000D_
  $('#container').append('<p>C: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
function D() {_x000D_
  var p = document.createElement("p");_x000D_
  p.innerHTML = 'D: Just some <span>text</span> here';_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function E() {    _x000D_
  var p = document.createElement("p");_x000D_
  var s = document.createElement("span"); _x000D_
  s.appendChild( document.createTextNode("text ") );_x000D_
  p.appendChild( document.createTextNode("E: Just some ") );_x000D_
  p.appendChild( s );_x000D_
  p.appendChild( document.createTextNode(" here") );_x000D_
  container.appendChild(p);_x000D_
}_x000D_
_x000D_
function F() {    _x000D_
  container.insertAdjacentHTML('beforeend', '<p>F: Just some <span>text</span> here</p>');_x000D_
}_x000D_
_x000D_
A();_x000D_
B();_x000D_
C();_x000D_
D();_x000D_
E();_x000D_
F();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
This snippet only for show code used in test (in jsperf.com) - it not perform test itself. _x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

What is the difference between a candidate key and a primary key?

Candidate Key – A Candidate Key can be any column or a combination of columns that can qualify as unique key in database. There can be multiple Candidate Keys in one table. Each Candidate Key can qualify as Primary Key.

Primary Key – A Primary Key is a column or a combination of columns that uniquely identify a record. Only one Candidate Key can be Primary Key.

More on this link with example

Bootstrap 3 Gutter Size

@Bass Jobsen and @ElwoodP attempted to answer this question in reverse--giving the outer margins the same DOUBLE size as the gutters. The OP (and me, as well) was searching for a way to have a SINGLE size gutter in all places. Here are the correct CSS adjustments to do so:

.row {
    margin-left: -7px;
    margin-right: -7px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
    padding-left: 7px;
    padding-right: 7px;
}
.container {
    padding-left: 14px;
    padding-right: 14px;
}

This leaves a 14px gutter and outside margin in all places.

Jackson serialization: ignore empty values (or null)

Also you can try to use

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

if you are dealing with jackson with version below 2+ (1.9.5) i tested it, you can easily use this annotation above the class. Not for specified for the attributes, just for class decleration.

Nginx - Customizing 404 page

You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.

To redirect to a simple 404 not found page for a specific location:

location /my_blog {
    error_page    404 /blog_article_not_found.html;
}

A site wide 404 page:

server {
    listen 80;
    error_page  404  /website_page_not_found.html;
    ...

You can append standard error codes together to have a single page for several types of errors:

location /my_blog {
    error_page 500 502 503 504 /server_error.html
}

To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:

upstream server2 {
    server 10.0.0.1:80;
}
server {
    location /my_blog {
        error_page    404 @try_server2;
    }
    location @try_server2 {
        proxy_pass http://server2;
    }

The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.

Getting a machine's external IP address with Python

I use IPGrab because it's easy to remember:

# This example requires the requests library be installed.  You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/
from requests import get

ip = get('http://ipgrab.io').text
print('My public IP address is: {}'.format(ip))

How can I change cols of textarea in twitter-bootstrap?

Another option is to split off the textarea in the Site.css as follows:

/* Set width on the form input elements since they're 100% wide by default */

input,
select {

  max-width: 280px;
}

textarea {

  /*max-width: 280px;*/
  max-width: 500px;
  width: 280px;
  height: 200px;
}

also (in my MVC 5) add ref to textarea:

@Html.TextAreaFor(model => ................... @class = "form-control", @id="textarea"............

It worked for me

Check if string begins with something?

Use stringObject.substring

if (pathname.substring(0, 6) == "/sub/1") {
    // ...
}

Get the first element of each tuple in a list in Python

res_list = [x[0] for x in rows]

c.f. http://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

For a discussion on why to prefer comprehensions over higher-order functions such as map, go to http://www.artima.com/weblogs/viewpost.jsp?thread=98196.

How do you convert a JavaScript date to UTC?

const event = new Date();

console.log(event.toUTCString());

Edit and replay XHR chrome/firefox etc?

My two suggestions:

  1. Chrome's Postman plugin + the Postman Interceptor Plugin. More Info: Postman Capturing Requests Docs

  2. If you're on Windows then Telerik's Fiddler is an option. It has a composer option to replay http requests, and it's free.

How to get HTTP Response Code using Selenium WebDriver

It is possible to get the response code of a http request using Selenium and Chrome or Firefox. All you have to do is start either Chrome or Firefox in logging mode. I will show you some examples below.

java + Selenium + Chrome Here is an example of java + Selenium + Chrome, but I guess that it can be done in any language (python, c#, ...).

All you need to do is tell chromedriver to do "Network.enable". This can be done by enabling Performance logging.

LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

After the request is done, all you have to do is get and iterate the Perfomance logs and find "Network.responseReceived" for the requested url:

LogEntries logs = driver.manage().logs().get("performance");

Here is the code:

import java.util.Iterator;
import java.util.logging.Level;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class TestResponseCode
{
    public static void main(String[] args)
    {
        // simple page (without many resources so that the output is
        // easy to understand
        String url = "http://www.york.ac.uk/teaching/cws/wws/webpage1.html";

        DownloadPage(url);
    }

    private static void DownloadPage(String url)
    {
        ChromeDriver driver = null;

        try
        {
            ChromeOptions options = new ChromeOptions();
            // add whatever extensions you need
            // for example I needed one of adding proxy, and one for blocking
            // images
            // options.addExtensions(new File(file, "proxy.zip"));
            // options.addExtensions(new File("extensions",
            // "Block-image_v1.1.crx"));

            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(ChromeOptions.CAPABILITY, options);

            // set performance logger
            // this sends Network.enable to chromedriver
            LoggingPreferences logPrefs = new LoggingPreferences();
            logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
            cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

            driver = new ChromeDriver(cap);

            // navigate to the page
            System.out.println("Navigate to " + url);
            driver.navigate().to(url);

            // and capture the last recorded url (it may be a redirect, or the
            // original url)
            String currentURL = driver.getCurrentUrl();

            // then ask for all the performance logs from this request
            // one of them will contain the Network.responseReceived method
            // and we shall find the "last recorded url" response
            LogEntries logs = driver.manage().logs().get("performance");

            int status = -1;

            System.out.println("\nList of log entries:\n");

            for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();)
            {
                LogEntry entry = it.next();

                try
                {
                    JSONObject json = new JSONObject(entry.getMessage());

                    System.out.println(json.toString());

                    JSONObject message = json.getJSONObject("message");
                    String method = message.getString("method");

                    if (method != null
                            && "Network.responseReceived".equals(method))
                    {
                        JSONObject params = message.getJSONObject("params");

                        JSONObject response = params.getJSONObject("response");
                        String messageUrl = response.getString("url");

                        if (currentURL.equals(messageUrl))
                        {
                            status = response.getInt("status");

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! returned response for "
                                            + messageUrl + ": " + status);

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! headers: "
                                            + response.get("headers"));
                        }
                    }
                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            System.out.println("\nstatus code: " + status);
        } finally
        {
            if (driver != null)
            {
                driver.quit();
            }
        }
    }
}

The output looks like this:

    Navigate to http://www.york.ac.uk/teaching/cws/wws/webpage1.html

    List of log entries:

    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameAttached","params":{"parentFrameId":"172.1","frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"://","loaderId":"172.1","name":"chromedriver dummy frame","id":"172.2","mimeType":"text/html","parentId":"172.1","url":"about:blank"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"VeryHigh","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"},"frameId":"3928.1","requestId":"3928.1","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492749007E9,"type":"Document","timestamp":20226.652971}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.responseReceived","params":{"frameId":"3928.1","requestId":"3928.1","response":{"headers":{"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"},"connectionReused":false,"timing":{"pushEnd":0,"workerStart":-1,"proxyEnd":-1,"workerReady":-1,"sslEnd":-1,"pushStart":0,"requestTime":20226.65335,"sslStart":-1,"dnsStart":0,"sendEnd":31.6569999995409,"connectEnd":31.4990000006219,"connectStart":0,"sendStart":31.5860000009707,"dnsEnd":0,"receiveHeadersEnd":115.645999998378,"proxyStart":-1},"encodedDataLength":-1,"remotePort":80,"mimeType":"text/html","headersText":"HTTP/1.1 200 OK\r\nDate: Tue, 11 Oct 2016 14:08:47 GMT\r\nServer: Apache/2.2.22 (Ubuntu)\r\nAccept-Ranges: bytes\r\nCache-Control: max-age=300\r\nExpires: Tue, 11 Oct 2016 14:13:47 GMT\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 1957\r\nKeep-Alive: timeout=4, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n","securityState":"neutral","requestHeadersText":"GET /teaching/cws/wws/webpage1.html HTTP/1.1\r\nHost: www.york.ac.uk\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, sdch\r\nAccept-Language: en-GB,en-US;q=0.8,en;q=0.6\r\n\r\n","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","protocol":"http/1.1","fromDiskCache":false,"fromServiceWorker":false,"requestHeaders":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Upgrade-Insecure-Requests":"1","Connection":"keep-alive","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36","Host":"www.york.ac.uk","Accept-Encoding":"gzip, deflate, sdch","Accept-Language":"en-GB,en-US;q=0.8,en;q=0.6"},"remoteIPAddress":"144.32.128.84","statusText":"OK","connectionId":11,"status":200},"loaderId":"3928.1","type":"Document","timestamp":20226.770012}}}
    ---------- bingo !!!!!!!!!!!!!! returned response for http://www.york.ac.uk/teaching/cws/wws/webpage1.html: 200
    ---------- bingo !!!!!!!!!!!!!! headers: {"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":2111,"requestId":"3928.1","encodedDataLength":1460,"timestamp":20226.770425}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"http://www.york.ac.uk","loaderId":"3928.1","id":"3928.1","mimeType":"text/html","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":1943,"requestId":"3928.1","encodedDataLength":825,"timestamp":20226.782673}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.loadingFinished","params":{"requestId":"3928.1","encodedDataLength":2285,"timestamp":20226.770199}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.loadEventFired","params":{"timestamp":20226.799391}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.domContentEventFired","params":{"timestamp":20226.845769}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Referer":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"High","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/favicon.ico"},"frameId":"3928.1","requestId":"3928.2","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492768527E9,"type":"Other","timestamp":20226.848174}}}

    status code: 200

java + Selenium + Firefox I have finally found the trick for Firefox too. You need to start firefox using MOZ_LOG and MOZ_LOG_FILE environment variables, and log http requests at debug level (4 = PR_LOG_DEBUG) - map.put("MOZ_LOG", "timestamp,sync,nsHttp:4"). Save the log in a temporary file. After that, get the content of the saved log file and parse it for the response code (using some simple regular expressions). First detect the start of the request, identifying its id (nsHttpChannel::BeginConnect [this=000000CED8094000]), then at the second step, find the response code for that request id (nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]).

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;

public class TestFirefoxResponse
{
  public static void main(String[] args)
      throws InterruptedException, IOException
  {
    GeckoDriverService service = null;

    // tell firefox to log http requests
    // at level 4 = PR_LOG_DEBUG: debug messages, notices
    // you could log everything at level 5, but the log file will 
    // be larger. 
    // create a temporary log file that will be parsed for
    // response code
    Map<String, String> map = new HashMap<String, String>();
    map.put("MOZ_LOG", "timestamp,sync,nsHttp:4");
    File tempFile = File.createTempFile("mozLog", ".txt");    
    map.put("MOZ_LOG_FILE", tempFile.getAbsolutePath());      

    GeckoDriverService.Builder builder = new GeckoDriverService.Builder();
    service = builder.usingAnyFreePort()
      .withEnvironment(map)
      .build();

    service.start();      

    WebDriver driver = new FirefoxDriver(service);

    // test 200
     String url = "https://api.ipify.org/?format=text";
    // test 404
    // String url = "https://www.advancedwebranking.com/lsdkjflksdjfldksfj";
    driver.get(url);

    driver.quit();

    String logContent = FileUtils.readFileToString(tempFile);

    ParseLog(logContent, url);
  }

  private static void ParseLog(String logContent, String url) throws MalformedURLException
  {
    // this is how the log looks like when the request starts
    // I have to get the id of the request using a regular expression
    // and use that id later to get the response
    //
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::BeginConnect [this=000000BFF27A5000]
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp host=api.ipify.org port=-1
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp uri=https://api.ipify.org/?format=text
    String pattern = "BeginConnect \\[this=(.*?)\\](?:.*?)uri=(.*?)\\s";

    Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(logContent);

    String urlID = null;
    while (m.find())
    {
      String id = m.group(1);
      String uri = m.group(2);

      if (uri.equals(url))
      {
        urlID = id;
        break;
      }      
    }

    System.out.println("request id = " + urlID);

    // this is how the response looks like in the log file
    // ProcessResponse [this=000000CED8094000 httpStatus=200]
    // I will use another regular espression to get the httpStatus
    //
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=000000CED8094000 request=000000CED8014BB0 status=0]
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]    

    pattern = "ProcessResponse \\[this=" + urlID + " httpStatus=(.*?)\\]";

    p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    m = p.matcher(logContent);

    if (m.find())
    {
      String responseCode = m.group(1);
      System.out.println("response code found " + responseCode);
    }
    else
    {
      System.out.println("response code not found");
    }
  }
}

The output for this will be

request id = 0000007653D67000 response code found 200

The response headers can also be found in the log file. You can get them if you want.

    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp http response [
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   HTTP/1.1 404 Not Found
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp     OriginalHeaders
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp ]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=0000008A65D85000 request=0000008A65D1F900 status=0]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=0000008A65D85000 httpStatus=404]

How to advance to the next form input when the current input has a value?

This should work. Working with and without tabindex.

_x000D_
_x000D_
var currentlyFocused = undefined;_x000D_
var tabableElements = undefined;_x000D_
_x000D_
/**_x000D_
 * Compare function for element sort_x000D_
 * @param {string | null} a_x000D_
 * @param {string | null} b_x000D_
 * @param {boolean} asc_x000D_
 */_x000D_
function sortCompare(a, b, asc = true) {_x000D_
  let result = null;_x000D_
  if (a == null) result = 1;_x000D_
  else if (b == null) result = -1;_x000D_
  else if (parseInt(a) > parseInt(b)) result = 1;_x000D_
  else if (parseInt(a) < parseInt(b)) result = -1;_x000D_
  else result = 0;_x000D_
  return result * (asc ? 1 : -1);_x000D_
}_x000D_
_x000D_
/**_x000D_
 * When an element is focused assign it to the currentlyFocused variable_x000D_
 * @param {Element} element_x000D_
 */_x000D_
function registerOnElementFocus(element) {_x000D_
  element.addEventListener("focus", function(el) {_x000D_
    currentlyFocused = el.srcElement;_x000D_
  });_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Tab Trigger_x000D_
 */_x000D_
function onTabClick() {_x000D_
  //Select currently focused element_x000D_
  let currentIndex;_x000D_
  tabableElements.forEach((el, idx) => {_x000D_
    //return if no element is focused_x000D_
    if (!currentlyFocused) return;_x000D_
    if (currentlyFocused.isEqualNode(el)) {_x000D_
      //assign current index and return_x000D_
      currentIndex = idx;_x000D_
      return;_x000D_
    }_x000D_
  });_x000D_
  //if theres no focused element or the current focused element is last start over_x000D_
  let lastIndex = tabableElements.length - 1;_x000D_
  let nextElementidx = currentIndex === undefined || currentIndex == lastIndex ? 0 : currentIndex + 1;_x000D_
  //Focus_x000D_
  currentlyFocused = tabableElements[nextElementidx];_x000D_
  currentlyFocused.focus();_x000D_
}_x000D_
/**_x000D_
 * Init must be run after all elements are loadead in the dom_x000D_
 */_x000D_
function init() {_x000D_
  //Get all tab-able elements_x000D_
  let nodeList = document.querySelectorAll("input, button, a, area, object, select, textarea, [tabindex]");_x000D_
  //To array for easier manipulation_x000D_
  tabableElements = Array.prototype.slice.call(nodeList, 0);_x000D_
  //Correcting tabindexes to ensure correct order_x000D_
  tabableElements.forEach((el, idx, list) => {_x000D_
    let tabindex = el.getAttribute("tabindex");_x000D_
    //-1 tabindex will not receive focus_x000D_
    if (tabindex == -1) list.splice(idx, 1);_x000D_
    //null or 0 tabindex in normal source order_x000D_
    else if (tabindex == null || tabindex == 0) {_x000D_
      list[idx].setAttribute("tabindex", 9999 + idx);_x000D_
    }_x000D_
  });_x000D_
  //sort elements by their tabindex in ascending order_x000D_
  tabableElements.sort((elementA, elementB) => sortCompare(elementA.getAttribute("tabindex"), elementB.getAttribute("tabindex")));_x000D_
  //register focus event to elements_x000D_
  tabableElements.forEach(el => registerOnElementFocus(el));_x000D_
}
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <!-- Required meta tags -->_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">_x000D_
_x000D_
  <!-- Bootstrap CSS -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">_x000D_
_x000D_
  <title>Virtual tab</title>_x000D_
</head>_x000D_
_x000D_
<body onload="init()">_x000D_
  <div class="container">_x000D_
    <h3>Virtual Tab Demo</h3>_x000D_
    <form>_x000D_
      <div class="btn btn-primary" style="position: fixed;" onclick="onTabClick()">_x000D_
        Tab!_x000D_
      </div>_x000D_
      <br>_x000D_
      <br>_x000D_
      <button id="button1" type="button" onclick="alert('button 1')">Button1</button>_x000D_
      <button id="button2" type="button" onclick="alert('button 2')">Button2</button>_x000D_
      <br>_x000D_
      <br>_x000D_
      <input id="text" type='text'>text_x000D_
      <br>_x000D_
      <input id="password" type='password' tabindex="-1">password_x000D_
      <br>_x000D_
      <input id="number" type='number' tabindex="5">number_x000D_
      <br>_x000D_
      <input id="checkbox" type='checkbox'>checkbox_x000D_
      <br>_x000D_
      <input id="radio" type='radio'>radio_x000D_
      <br>_x000D_
      <br>_x000D_
      <button id="button3" type="button" onclick="alert('button 3')">Button3</button>_x000D_
      <button id="button4" type="button" onclick="alert('button 4')">Button4</button>_x000D_
      <br>_x000D_
      <br>_x000D_
      <select id="select">_x000D_
        <option value="volvo">Volvo</option>_x000D_
        <option value="saab">Saab</option>_x000D_
        <option value="mercedes">Mercedes</option>_x000D_
        <option value="audi">Audi</option>_x000D_
      </select>_x000D_
      <br>_x000D_
      <br> textarea_x000D_
      <br>_x000D_
      <textarea id="textarea"></textarea>_x000D_
        <br>_x000D_
        <br>_x000D_
        <span id="span" tabindex="1">Focus other elements.</span>_x000D_
    </form>_x000D_
  </div>_x000D_
  <!-- Optional JavaScript -->_x000D_
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->_x000D_
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

JFrame in full screen Java

You only need this:

JFrame frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

When you use the MAXIMIZED_BOTH modifier, it will max all the way across the window (height and width).

There are some that suggested using this:

frame.setUndecorated(true);

I won't recommend it, because your window won't have a header, thus no close/restore/minimize button.

JAX-WS - Adding SOAP Headers

you can add the username and password to the SOAP Header

BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                "your end point"));
Map<String, List<String>> headers = new HashMap<String, List<String>>();
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
prov.getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, headers);

How to flush output after each `echo` call?

The correct function to use is flush().

<html>
<body>
<p>
Hello! I am waiting for the next message...<br />
<?php flush(); sleep(5); ?>
I am the next message!<br />
<?php flush(); sleep(5); ?>
And I am the last message. Good bye.
</p>
</body>
</html>

Please note that there is a "problem" with IE, which only outputs the flushed content when it is at least 256 byte, so your first part of the page needs to be at least 256 byte.

How to get JSON from webpage into Python script

In Python 2, json.load() will work instead of json.loads()

import json
import urllib

url = 'https://api.github.com/users?since=100'
output = json.load(urllib.urlopen(url))
print(output)

Unfortunately, that doesn't work in Python 3. json.load is just a wrapper around json.loads that calls read() for a file-like object. json.loads requires a string object and the output of urllib.urlopen(url).read() is a bytes object. So one has to get the file encoding in order to make it work in Python 3.

In this example we query the headers for the encoding and fall back to utf-8 if we don't get one. The headers object is different between Python 2 and 3 so it has to be done different ways. Using requests would avoid all this, but sometimes you need to stick to the standard library.

import json
from six.moves.urllib.request import urlopen

DEFAULT_ENCODING = 'utf-8'
url = 'https://api.github.com/users?since=100'
urlResponse = urlopen(url)

if hasattr(urlResponse.headers, 'get_content_charset'):
    encoding = urlResponse.headers.get_content_charset(DEFAULT_ENCODING)
else:
    encoding = urlResponse.headers.getparam('charset') or DEFAULT_ENCODING

output = json.loads(urlResponse.read().decode(encoding))
print(output)

Writing string to a file on a new line every time

I really didn't want to type \n every single time and @matthause's answer didn't seem to work for me, so I created my own class

class File():

    def __init__(self, name, mode='w'):
        self.f = open(name, mode, buffering=1)
        
    def write(self, string, newline=True):
        if newline:
            self.f.write(string + '\n')
        else:
            self.f.write(string)

And here it is implemented

f = File('console.log')

f.write('This is on the first line')
f.write('This is on the second line', newline=False)
f.write('This is still on the second line')
f.write('This is on the third line')

This should show in the log file as

This is on the first line
This is on the second lineThis is still on the second line
This is on the third line

Converting cv::Mat to IplImage*

cv::Mat is the new type introduce in OpenCV2.X while the IplImage* is the "legacy" image structure.

Although, cv::Mat does support the usage of IplImage in the constructor parameters, the default library does not provide function for the other way. You will need to extract the image header information manually. (Do remember that you need to allocate the IplImage structure, which is lack in your example).

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

How do I get the localhost name in PowerShell?

All above questions are correct but if you want the hostname and domain name try this:

 [System.Net.DNS]::GetHostByName('').HostName

SQL: capitalize first letter only

Are you asking for renaming column itself or capitalise the data inside column? If its data you've to change, then use this:

UPDATE [yourtable]
SET word=UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word)))

If you just wanted to change it only for displaying and do not need the actual data in table to change:

SELECT UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word))) FROM [yourtable]

Hope this helps.

EDIT: I realised about the '-' so here is my attempt to solve this problem in a function.

CREATE FUNCTION [dbo].[CapitalizeFirstLetter]
(
--string need to format
@string VARCHAR(200)--increase the variable size depending on your needs.
)
RETURNS VARCHAR(200)
AS

BEGIN
--Declare Variables
DECLARE @Index INT,
@ResultString VARCHAR(200)--result string size should equal to the @string variable size
--Initialize the variables
SET @Index = 1
SET @ResultString = ''
--Run the Loop until END of the string

WHILE (@Index <LEN(@string)+1)
BEGIN
IF (@Index = 1)--first letter of the string
BEGIN
--make the first letter capital
SET @ResultString =
@ResultString + UPPER(SUBSTRING(@string, @Index, 1))
SET @Index = @Index+ 1--increase the index
END

-- IF the previous character is space or '-' or next character is '-'

ELSE IF ((SUBSTRING(@string, @Index-1, 1) =' 'or SUBSTRING(@string, @Index-1, 1) ='-' or SUBSTRING(@string, @Index+1, 1) ='-') and @Index+1 <> LEN(@string))
BEGIN
--make the letter capital
SET
@ResultString = @ResultString + UPPER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--increase the index
END
ELSE-- all others
BEGIN
-- make the letter simple
SET
@ResultString = @ResultString + LOWER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--incerase the index
END
END--END of the loop

IF (@@ERROR
<> 0)-- any error occur return the sEND string
BEGIN
SET
@ResultString = @string
END
-- IF no error found return the new string
RETURN @ResultString
END

So then the code would be:

UPDATE [yourtable]
SET word=dbo.CapitalizeFirstLetter([STRING TO GO HERE])

Python Pandas - Missing required dependencies ['numpy'] 1

I had this problem with last version of numpy 1.16.x

Problem resolved with

python3 -m pip uninstall numpy

python3 -m pip install numpy==1.14.0

Flash CS4 refuses to let go

Try deleting your ASO files.

ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.

This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.

Can I disable a CSS :hover effect via JavaScript?

You can manipulate the stylesheets and stylesheet rules themselves with javascript

var sheetCount = document.styleSheets.length;
var lastSheet = document.styleSheets[sheetCount-1];
var ruleCount;
if (lastSheet.cssRules) { // Firefox uses 'cssRules'
    ruleCount = lastSheet.cssRules.length;
}
else if (lastSheet.rules) { / /IE uses 'rules'
    ruleCount = lastSheet.rules.length;
}
var newRule = "a:hover { text-decoration: none !important; color: #000 !important; }";
// insert as the last rule in the last sheet so it
// overrides (not overwrites) previous definitions
lastSheet.insertRule(newRule, ruleCount);

Making the attributes !important and making this the very last CSS definition should override any previous definition, unless one is more specifically targeted. You may have to insert more rules in that case.

How to get a list of user accounts using the command line in MySQL?

The mysql.db table is possibly more important in determining user rights. I think an entry in it is created if you mention a table in the GRANT command. In my case the mysql.users table showed no permissions for a user when it obviously was able to connect and select, etc.

mysql> select * from mysql.db;
mysql> select * from db;
+---------------+-----------------+--------+-------------+-------------+-------------+--------
| Host          | Db              | User   | Select_priv | Insert_priv | Update_priv | Del...

How open PowerShell as administrator from the run window

The easiest way to open an admin Powershell window in Windows 10 (and Windows 8) is to add a "Windows Powershell (Admin)" option to the "Power User Menu". Once this is done, you can open an admin powershell window via Win+X,A or by right-clicking on the start button and selecting "Windows Powershell (Admin)":

[Windows 10/Windows 8 Power User menu with "Windows Powershell (Admin)

Here's where you replace the "Command Prompt" option with a "Windows Powershell" option:

[Taskbar and Start Menu Properties: "Replace Command Prompt With Windows Powershell"

The character encoding of the HTML document was not declared

Your initial page is a complete HTML page containing a form, the contents of which are posted to insert.php when the submit button is clicked, but insert.php needs to process the form's contents and do something with them, like add them to a database, or output them to a new page. Your current insert.php just outputs the contents of the title field, so your browser tries to interpret that as an HTML page, and fails, obviously, because it isn't valid HTML (i.e. it isn't contained in an 'HTML' tag, etc.).

Your insert.php needs to output the necessary HTML, and insert the form data in there somewhere.

For example:

<?php 

   $title = $_POST["title"];
   $price = $_POST["price"];

  echo '<html xmlns="http://www.w3.org/1999/xhtml">';
  echo '<head>';
  echo '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
  echo '<title>';
  echo $title;
  echo '</title>';
  echo '</head>';
  echo '<body>';
  echo 'Hello, world.';
  echo '</body>';

 ?>

Remove duplicates from a list of objects based on property in Java 8

Another solution is to use a Predicate, then you can use this in any filter:

public static <T> Predicate<T> distinctBy(Function<? super T, ?> f) {
  Set<Object> objects = new ConcurrentHashSet<>();
  return t -> objects.add(f.apply(t));
}

Then simply reuse the predicate anywhere:

employees.stream().filter(distinctBy(e -> e.getId));

Note: in the JavaDoc of filter, which says it takes a stateless Predicte. Actually, this works fine even if the stream is parallel.


About other solutions:

1) Using .collect(Collectors.toConcurrentMap(..)).values() is a good solution, but it's annoying if you want to sort and keep the order.

2) stream.removeIf(e->!seen.add(e.getID())); is also another very good solution. But we need to make sure the collection implemented removeIf, for example it will throw exception if we construct the collection use Arrays.asList(..).

Group by month and year in MySQL

You must do something like this

SELECT onDay, id, 
sum(pxLow)/count(*),sum(pxLow),count(`*`),
CONCAT(YEAR(onDay),"-",MONTH(onDay)) as sdate 
FROM ... where stockParent_id =16120 group by sdate order by onDay

".addEventListener is not a function" why does this error occur?

_x000D_
_x000D_
var comment = document.getElementsByClassName("button");_x000D_
_x000D_
function showComment() {_x000D_
  var place = document.getElementById('textfield');_x000D_
  var commentBox = document.createElement('textarea');_x000D_
  place.appendChild(commentBox);_x000D_
}_x000D_
_x000D_
for (var i in comment) {_x000D_
  comment[i].onclick = function() {_x000D_
    showComment();_x000D_
  };_x000D_
}
_x000D_
<input type="button" class="button" value="1">_x000D_
<input type="button" class="button" value="2">_x000D_
<div id="textfield"></div>
_x000D_
_x000D_
_x000D_

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

Best way to create a simple python web service

Look at the WSGI reference implementation. You already have it in your Python libraries. It's quite simple.

IOS - How to segue programmatically using swift

What you want to do is really important for unit testing. Basically you need to create a small local function in the view controller. Name the function anything, just include the performSegueWithIndentifier.

func localFunc() {
    println("we asked you to do it")
    performSegueWithIdentifier("doIt", sender: self)
}

Next change your utility class FBManager to include an initializer that takes an argument of a function and a variable to hold the ViewController's function that performs the segue.

public class UtilClass {

    var yourFunction : () -> ()

    init (someFunction: () -> ()) {
        self.yourFunction = someFunction
        println("initialized UtilClass")
    }

    public convenience init() {
        func dummyLog () -> () {
            println("no action passed")
        }
        self.init(dummyLog)
    }

    public func doThatThing() -> () {
        // the facebook login function
        println("now execute passed function")
        self.yourFunction()
        println("did that thing")
    }
}

(The convenience init allows you to use this in unit testing without executing the segue.)

Finally, where you have //todo: segue to the next view???, put something along the lines of:

self.yourFunction()

In your unit tests, you can simply invoke it as:

let f = UtilClass()
f.doThatThing()

where doThatThing is your fbsessionstatechange and UtilClass is FBManager.

For your actual code, just pass localFunc (no parenthesis) to the FBManager class.

Reporting Services permissions on SQL Server R2 SSRS

in my case this error resolved by adding permission level to root folder .

i previously only granted permission in 2 place. one in site setting and one in a new folder that has custom permission .

but the user permission to browse the root folder was also required. Note The "Folder setting" in root folder

another time i had similar problem and adding users in the following windows group SQLServerReportServerUser$servername$MSRS10_50.MSSQLSERVER and running IE as Administrator or turning off UAC resolved my problem .

How to filter for multiple criteria in Excel?

The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.

http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm

Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.

  1. E1 : Letters
  2. E2 : =m
  3. E3 : =h
  4. E4 : =j

I put the data starting on row 5:

  1. A5 : Letters
  2. A6 :
  3. A7 :
  4. ...

Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.

That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.

Submitting the value of a disabled input field

Input elements have a property called disabled. When the form submits, just run some code like this:

var myInput = document.getElementById('myInput');
myInput.disabled = true;

How to revert multiple git commits?

The easy way to revert a group of commits on shared repository (that people use and you want to preserve the history) is to use git revert in conjunction with git rev-list. The latter one will provide you with a list of commits, the former will do the revert itself.

There are two ways to do that. If you want the revert multiple commits in a single commit use:

for i in `git rev-list <first-commit-sha>^..<last-commit-sha>`; do git revert --no-commit $i; done

this will revert a group of commits you need, but leave all the changes on your working tree, you should commit them all as usual afterward.

Another option is to have a single commit per reverted change:

for i in `git rev-list <first-commit-sha>^..<last-commit-sha>`; do git revert --no-edit -s $i; done

For instance, if you have a commit tree like

 o---o---o---o---o---o--->    
fff eee ddd ccc bbb aaa

to revert the changes from eee to bbb, run

for i in `git rev-list eee^..bbb`; do git revert --no-edit -s $i; done

MySQL TEXT vs BLOB vs CLOB

It's worth to mention that CLOB / BLOB data types and their sizes are supported by MySQL 5.0+, so you can choose the proper data type for your need.

http://dev.mysql.com/doc/refman/5.7/en/storage-requirements.html

Data Type   Date Type   Storage Required
(CLOB)      (BLOB)

TINYTEXT    TINYBLOB    L + 1 bytes, where L < 2**8  (255)
TEXT        BLOB        L + 2 bytes, where L < 2**16 (64 K)
MEDIUMTEXT  MEDIUMBLOB  L + 3 bytes, where L < 2**24 (16 MB)
LONGTEXT    LONGBLOB    L + 4 bytes, where L < 2**32 (4 GB)

where L stands for the byte length of a string

phpexcel to download

Use this call

$objWriter->save('php://output');

To output the XLS sheet to the page you are on, just make sure that the page you are on has no other echo's,print's, outputs.

How to use multiple conditions (With AND) in IIF expressions in ssrs

You don't need an IIF() at all here. The comparisons return true or false anyway.

Also, since this row visibility is on a group row, make sure you use the same aggregate function on the fields as you use in the fields in the row. So if your group row shows sums, then you'd put this in the Hidden property.

=Sum(Fields!OpeningStock.Value) = 0 And
Sum(Fields!GrossDispatched.Value) = 0 And 
Sum(Fields!TransferOutToMW.Value) = 0 And
Sum(Fields!TransferOutToDW.Value) = 0 And
Sum(Fields!TransferOutToOW.Value) = 0 And
Sum(Fields!NetDispatched.Value) = 0 And
Sum(Fields!QtySold.Value) = 0 And
Sum(Fields!StockAdjustment.Value) = 0 And
Sum(Fields!ClosingStock.Value) = 0

But with the above version, if one record has value 1 and one has value -1 and all others are zero then sum is also zero and the row could be hidden. If that's not what you want you could write a more complex expression:

=Sum(
    IIF(
        Fields!OpeningStock.Value=0 AND
        Fields!GrossDispatched.Value=0 AND
        Fields!TransferOutToMW.Value=0 AND
        Fields!TransferOutToDW.Value=0 AND 
        Fields!TransferOutToOW.Value=0 AND
        Fields!NetDispatched.Value=0 AND
        Fields!QtySold.Value=0 AND
        Fields!StockAdjustment.Value=0 AND
        Fields!ClosingStock.Value=0,
        0,
        1
    )
) = 0

This is essentially a fancy way of counting the number of rows in which any field is not zero. If every field is zero for every row in the group then the expression returns true and the row is hidden.

Import Libraries in Eclipse?

For the Android library projects, I do it as in the attached screenshot:

Right click the project, select Properties->Android and in the library section click Add. From here you can select the available libraries.

If you are importing a jar file, then importing them as jar or external jar, as other posters posted would work. I prefer to copy/paste jar file in the libs folder (create one if it doesn't exist) and then import as jar.

Adding a library

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

How to get file path from OpenFileDialog and FolderBrowserDialog?

Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.

How to use unicode characters in Windows command line?

As I haven't seen any full answers for Python 2.7, I'll outline the two important steps and an optional step that is quite useful.

  1. You need a font with Unicode support. Windows comes with Lucida Console which may be selected by right-clicking the title bar of command prompt and clicking the Defaults option. This also gives access to colours. Note that you can also change settings for command windows invoked in certain ways (e.g, open here, Visual Studio) by choosing Properties instead.
  2. You need to set the code page to cp65001, which appears to be Microsoft's attempt to offer UTF-7 and UTF-8 support to command prompt. Do this by running chcp 65001 in command prompt. Once set, it remains this way until the window is closed. You'll need to redo this every time you launch cmd.exe.

For a more permanent solution, refer to this answer on Super User. In short, create a REG_SZ (String) entry using regedit at HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor and name it AutoRun. Change the value of it to chcp 65001. If you don't want to see the output message from the command, use @chcp 65001>nul instead.

Some programs have trouble interacting with this encoding, MinGW being a notable one that fails while compiling with a nonsensical error message. Nonetheless, this works very well and doesn't cause bugs with the majority of programs.

How to change a nullable column to not nullable in a Rails migration?

You can't use add_timestamps and null:false if you have existing records, so here is the solution :

def change
  add_timestamps(:buttons, null: true)

  Button.find_each { |b| b.update(created_at: Time.zone.now, updated_at: Time.zone.now) }

  change_column_null(:buttons, :created_at, false)
  change_column_null(:buttons, :updated_at, false)
end

jQuery Set Cursor Position in Text Area

I have two functions:

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos (input, pos) {
  setSelectionRange(input, pos, pos);
}

Then you can use setCaretToPos like this:

setCaretToPos(document.getElementById("YOURINPUT"), 4);

Live example with both a textarea and an input, showing use from jQuery:

_x000D_
_x000D_
function setSelectionRange(input, selectionStart, selectionEnd) {_x000D_
  if (input.setSelectionRange) {_x000D_
    input.focus();_x000D_
    input.setSelectionRange(selectionStart, selectionEnd);_x000D_
  } else if (input.createTextRange) {_x000D_
    var range = input.createTextRange();_x000D_
    range.collapse(true);_x000D_
    range.moveEnd('character', selectionEnd);_x000D_
    range.moveStart('character', selectionStart);_x000D_
    range.select();_x000D_
  }_x000D_
}_x000D_
_x000D_
function setCaretToPos(input, pos) {_x000D_
  setSelectionRange(input, pos, pos);_x000D_
}_x000D_
_x000D_
$("#set-textarea").click(function() {_x000D_
  setCaretToPos($("#the-textarea")[0], 10)_x000D_
});_x000D_
$("#set-input").click(function() {_x000D_
  setCaretToPos($("#the-input")[0], 10);_x000D_
});
_x000D_
<textarea id="the-textarea" cols="40" rows="4">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
<br><input type="button" id="set-textarea" value="Set in textarea">_x000D_
<br><input id="the-input" type="text" size="40" value="Lorem ipsum dolor sit amet, consectetur adipiscing elit">_x000D_
<br><input type="button" id="set-input" value="Set in input">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

As of 2016, tested and working on Chrome, Firefox, IE11, even IE8 (see that last here; Stack Snippets don't support IE8).

Correct way of looping through C++ arrays

You can do it as follow:

#include < iostream >

using namespace std;

int main () {

   string texts[] = {"Apple", "Banana", "Orange"};

   for( unsigned int a = 0; a < sizeof(texts) / 32; a++ ) { // 32 is the size of string data type

       cout << "value of a: " << texts[a] << endl;

   }


   return 0;

}

Solving a "communications link failure" with JDBC and MySQL

In case you are having problem with a set of Docker containers, then make sure that you do not only EXPOSE the port 3306, but as well map the port from outside the container -p 3306:3306. For docker-compose.yml:

version: '2'

services:
    mdb:
        image: mariadb:10.1
        ports:
            - "3306:3306"
        …

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

You can run your .bat file through a .vbs file
Copy the following code into your .vbs file :

Dim WshShell
Dim obj
Set WshShell = WScript.CreateObject("WScript.Shell") 
obj = WshShell.Run("C:\Users\file1.bat", 0) 
obj = WshShell.Run("C:\Users\file2.bat", 0)  and so on
set WshShell = Nothing 

UILabel - auto-size label to fit text?

@implementation UILabel (UILabel_Auto)

- (void)adjustHeight {

    if (self.text == nil) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
        return;
    }

    CGSize aSize = self.bounds.size;
    CGSize tmpSize = CGRectInfinite.size;
    tmpSize.width = aSize.width;

    tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}

@end

This is category method. You must set text first, than call this method to adjust UILabel's height.

Update statement with inner join on Oracle

UPDATE (SELECT T.FIELD A, S.FIELD B
FROM TABLE_T T INNER JOIN TABLE_S S
ON T.ID = S.ID)
SET B = A;

A and B are alias fields, you do not need to point the table.

Frontend tool to manage H2 database

If you are running it as an embedded database in spring I use the following configuration to enable the built in web client when the main app is running:

<!-- Run H2 web server within application that will access the same in-memory database -->
<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,9092"/>
</bean>
<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg value="-web,-webAllowOthers,-webPort,8082"/>
</bean>

How to set up devices for VS Code for a Flutter emulator

You do not need Android Studio to create or run a Virtual Device. Just use sdkmanager and avdmanager from the android sdk tools.

Use the sdkmanager to download a system image of Android for x86 system.
e.g. sdkmanager "system-images;android-21;default;x86_64"

Then create a new virtual device using avdmanager.
e.g. avdmanager create avd --name AndroidDevice01 --package "system-images;android-21;default;x86_64"

Then run the new virtual device using emulator. If you don't have it just install it using the sdkmanager.
e.g. emulator -avd AndroidDevice01

If you restart VSCode and load your Flutter project. The new device should show up at the bottom right of the footer.

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

int a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

Parsing Json rest api response in C#

  1. Create classes that match your data,
  2. then use JSON.NET to convert the JSON data to regular C# objects.

Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below

Step 2: JToken.Parse(...).ToObject<RootObject>().

public class Meta
{
    public int code { get; set; }
    public string status { get; set; }
    public string method_name { get; set; }
}

public class Photos
{
    public int total_count { get; set; }
}

public class Storage
{
    public int used { get; set; }
}

public class Stats
{
    public Photos photos { get; set; }
    public Storage storage { get; set; }
}

public class From
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ParticipateUser
{
    public string id { get; set; }
    public string first_name { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public List<object> external_accounts { get; set; }
    public string email { get; set; }
    public string confirmed_at { get; set; }
    public string username { get; set; }
    public string admin { get; set; }
    public Stats stats { get; set; }
}

public class ChatGroup
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public List<ParticipateUser> participate_users { get; set; }
}

public class Chat
{
    public string id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public string message { get; set; }
    public From from { get; set; }
    public ChatGroup chat_group { get; set; }
}

public class Response
{
    public List<Chat> chats { get; set; }
}

public class RootObject
{
    public Meta meta { get; set; }
    public Response response { get; set; }
}

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

Reverse ip, find domain names on ip address

You can use ping -a <ip> or nbtstat -A <ip>

Round double in two decimal places in C#?

This works:

inputValue = Math.Round(inputValue, 2);

python how to pad numpy array with zeros

Tensorflow also implemented functions for resizing/padding images tf.image.pad tf.pad.

padded_image = tf.image.pad_to_bounding_box(image, top_padding, left_padding, target_height, target_width)

padded_image = tf.pad(image, paddings, "CONSTANT")

These functions work just like other input-pipeline features of tensorflow and will work much better for machine learning applications.

How to restore/reset npm configuration to default values?

npm config edit

Opens the config file in an editor. Use the --global flag to edit the global config. now you can delete what ever the registry's you don't want and save file.

npm config list will display the list of available now.

Input placeholders for Internet Explorer

Best one in my experience is https://github.com/mathiasbynens/jquery-placeholder (recommended by html5please.com). http://afarkas.github.com/webshim/demos/index.html also has a good solution among its much more extensive library of polyfills.

How to view data saved in android database(SQLite)?

Try this..

  1. Download the Sqlite Manager jar file here.

  2. Add it to your eclipse > dropins Directory.

  3. Restart eclipse.

  4. Launch the compatible emulator or device

  5. Run your application.

  6. Go to Window > Open Perspective > DDMS >

  7. Choose the running device.

  8. Go to File Explorer tab.

  9. Select the directory called databases under your application's package.

  10. Select the .db file under the database directory.

  11. Then click Sqlite manager icon like this Sqlite manager icon.

  12. Now you're able to see the .db file.

Happy coding.....

The right way of setting <a href=""> when it's a local file

../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.

How to redirect both stdout and stderr to a file

Use:

command >>log_file 2>>log_file

Aborting a shell script if any command returns a non-zero value

To add to the accepted answer:

Bear in mind that set -e sometimes is not enough, specially if you have pipes.

For example, suppose you have this script

#!/bin/bash
set -e 
./configure  > configure.log
make

... which works as expected: an error in configure aborts the execution.

Tomorrow you make a seemingly trivial change:

#!/bin/bash
set -e 
./configure  | tee configure.log
make

... and now it does not work. This is explained here, and a workaround (Bash only) is provided:

#!/bin/bash
set -e 
set -o pipefail

./configure  | tee configure.log
make

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Before importing the project, it should be converted into eclipse project mvn eclipse: eclipse Then i found the following error. An internal error occurred during: "Importing Maven projects".Unsupported IClasspathEntry kind=4

Where is the value kind = "var" that M2E does not recognize and therefore throws the error.

Now type this. mvn eclipse: clean

Now refresh the project in eclipse or re-import.

WaitAll vs WhenAll

What do they do:

  • Internally both do the same thing.

What's the difference:

  • WaitAll is a blocking call
  • WhenAll - not - code will continue executing

Use which when:

  • WaitAll when cannot continue without having the result
  • WhenAll when what just to be notified, not blocked

The project cannot be built until the build path errors are resolved.

1-Right CLick on your project folder, Choose Build Path > Configure Build Path
2-Select Libraries Tab and delete any arbitrary library present there.
3-Click on Add Library option, Select JRE System Library and click Next.
4-Choose last Radiobutton option Workspace default JRE and click Finish.
5-press f5 for refresh.
6-run ur program .

Maven project.build.directory

Aside from @Verhás István answer (which I like), I was expecting a one-liner for the question:

${project.reporting.outputDirectory} resolves to target/site in your project.

Call Activity method from adapter

One more way is::

Write a method in your adapter lets say public void callBack(){}.

Now while creating an object for adapter in activity override this method. Override method will be called when you call the method in adapter.

Myadapter adapter = new Myadapter() {
  @Override
  public void callBack() {
    // dosomething
  }
};

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

How to get file URL using Storage facade in laravel 5?

Store method:

public function upload($img){
   $filename = Carbon::now() . '-' .  $img->getClientOriginalName();
   return Storage::put($filename, File::get($img)) ? $filename : '';
}

Route:

 Route::get('image/{filename}', [
        'as'   => 'product.image',
        'uses' => 'ProductController@getImage',
    ]);

Controller:

 public function getImage($filename)
    {
        $file = Storage::get($filename);

        return new Response($file, 200);
    }

View:

 <img src="{{ route('product.image', ['filename' => $yourImageName]) }}" alt="your image"/>

Classes vs. Functions

Before answering your question:

If you do not have a Person class, first you must consider whether you want to create a Person class. Do you plan to reuse the concept of a Person very often? If so, you should create a Person class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)

To answer your question:

You have access to their birthyear, so in that case you likely have a Person class with a someperson.birthdate field. In that case, you have to ask yourself, is someperson.age a value that is reusable?

The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale or someperson.positionToDisplayInGrid or other irrelevant values, we would not extend the Person class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData or something).)

How to make connection to Postgres via Node.js

Connection String

The connection string is a string of the form:

postgres://[user[:password]@][host][:port][/dbname]

(where the parts in [...] can optionally be included or excluded)

Some examples of valid connection strings include:

postgres://localhost
postgres://localhost:5432
postgres://localhost/mydb
postgres://user@localhost
postgres://user:secret_password@localhost

If you've just started a database on your local machine, the connection string postgres://localhost will typically work, as that uses the default port number, username, and no password. If the database was started with a specific account, you might find you need to use postgres://pg@localhost or postgres://postgres@localhost

If none of these work, and you have installed docker, another option is to run npx @databases/pg-test start. This will start a postgres server in a docker container and then print out the connection string for you. The pg-test databases are only intended for testing though, so you will loose all your data if your computer restarts.

Connecting in node.js

You can connect to the database and issue queries using @databases/pg:

const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');

// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:

// import createPool, {sql} from '@databases/pg';

// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');

// wrap code in an `async` function so we can use `await`
async function run() {

  // we can run sql by tagging it as "sql" and then passing it to db.query
  await db.query(sql`
    CREATE TABLE IF NOT EXISTS beatles (
      name TEXT NOT NULL,
      height INT NOT NULL,
      birthday DATE NOT NULL
    );
  `);

  const beatle = {
    name: 'George',
    height: 70,
    birthday: new Date(1946, 02, 14),
  };

  // If we need to pass values, we can use ${...} and they will
  // be safely & securely escaped for us
  await db.query(sql`
    INSERT INTO beatles (name, height, birthday)
    VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
  `);

  console.log(
    await db.query(sql`SELECT * FROM beatles;`)
  );
}

run().catch(ex => {
  // It's a good idea to always report errors using
  // `console.error` and set the process.exitCode if
  // you're calling an async function at the top level
  console.error(ex);
  process.exitCode = 1;
}).then(() => {
  // For this little demonstration, we'll dispose of the
  // connection pool when we're done, so that the process
  // exists. If you're building a web server/backend API
  // you probably never need to call this.
  return db.dispose();
});

You can find a more complete guide to querying Postgres using node.js at https://www.atdatabases.org/docs/pg

How do I set the eclipse.ini -vm option?

The JDK you're pointing to in your eclipse.ini has to match the Eclipse installation.

If you are running a 32- or 64-bit Eclipse, use a 32 or 64-bit Java JDK, respectively.

Open the terminal in visual studio?

To open the terminal:

  • Use the Ctrl` keyboard shortcut with the backtick character. This command works for both Linux and macOS.
  • Use the View > Terminal menu command.
  • From the Command Palette (??P), use the View: Toggle Integrated Terminal command.

Please find more about integrated terminal here https://code.visualstudio.com/docs/editor/integrated-terminal

Double precision floating values in Python?

Decimal datatype

  • Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem.

If you are pressed by performance issuses, have a look at GMPY

How to read all rows from huge table?

I did it like below. Not the best way i think, but it works :)

    Connection c = DriverManager.getConnection("jdbc:postgresql://....");
    PreparedStatement s = c.prepareStatement("select * from " + tabName + " where id > ? order by id");
    s.setMaxRows(100);
    int lastId = 0;
    for (;;) {
        s.setInt(1, lastId);
        ResultSet rs = s.executeQuery();

        int lastIdBefore = lastId;
        while (rs.next()) {
            lastId = Integer.parseInt(rs.getObject(1).toString());
            // ...
        }

        if (lastIdBefore == lastId) {
            break;
        }
    }

Best TCP port number range for internal applications

Short answer: use an unassigned user port

Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.

The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.

You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.

The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.

The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.

How to make Twitter Bootstrap tooltips have multiple lines?

If you are using Angular UI Bootstrap, you can use tooltip with html syntax: tooltip-html-unsafe

e.g. update to angular 1.2.10 & angular-ui-bootstrap 0.11: http://jsfiddle.net/aX2vR/1/

old one: http://jsfiddle.net/8LMwz/1/

Inverse of matrix in R

Note that if you care about speed and do not need to worry about singularities, solve() should be preferred to ginv() because it is much faster, as you can check:

require(MASS)
mat <- matrix(rnorm(1e6),nrow=1e3,ncol=1e3)

t0 <- proc.time()
inv0 <- ginv(mat)
proc.time() - t0 

t1 <- proc.time()
inv1 <- solve(mat)
proc.time() - t1 

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

Python unexpected EOF while parsing

After the first if statement instead of typing "if" type "elif" and then it should work.

Ex.

`    while 1:
    date=input("Example: March 21 | What is the date? ")
if date=="June 21":
    sd="23.5° North Latitude
elif date=="March 21" | date=="September 21":
    sd="0° Latitude"
elif date=="December 21":
    sd="23.5° South Latitude"
elif sd:
    print sd `

How to add a “readonly” attribute to an <input>?

I think "disabled" excludes the input from being sent on the POST

Mockito How to mock and assert a thrown exception?

I think this should do it for you.

assertThrows(someException.class, ()-> mockedServiceReference.someMethod(param1,parme2,..));

How to request a random row in SQL?

I don't know how efficient this is, but I've used it before:

SELECT TOP 1 * FROM MyTable ORDER BY newid()

Because GUIDs are pretty random, the ordering means you get a random row.

How to get the file name from a full path using JavaScript?

The complete answer is:

<html>
    <head>
        <title>Testing File Upload Inputs</title>
        <script type="text/javascript">

        function replaceAll(txt, replace, with_this) {
            return txt.replace(new RegExp(replace, 'g'),with_this);
        }

        function showSrc() {
            document.getElementById("myframe").href = document.getElementById("myfile").value;
            var theexa = document.getElementById("myframe").href.replace("file:///","");
            var path = document.getElementById("myframe").href.replace("file:///","");
            var correctPath = replaceAll(path,"%20"," ");
            alert(correctPath);
        }
        </script>
    </head>
    <body>
        <form method="get" action="#"  >
            <input type="file"
                   id="myfile"
                   onChange="javascript:showSrc();"
                   size="30">
            <br>
            <a href="#" id="myframe"></a>
        </form>
    </body>
</html>

Undo working copy modifications of one file in Git?

If you want to just undo the previous commit's changes to that one file, you can try this:

git checkout branchname^ filename

This will checkout the file as it was before the last commit. If you want to go a few more commits back, use the branchname~n notation.

Microsoft.ACE.OLEDB.12.0 provider is not registered

Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.

Generating a random hex color code with PHP

Valid hex colors can contain 0 to 9 and A to F so if we create a string with those characters and then shuffle it, we can grab the first 6 characters to create a random hex color code. An example is below!

code

echo '#' . substr(str_shuffle('ABCDEF0123456789'), 0, 6);

I tested this in a while loop and generated 10,000 unique colors.

code I used to generate 10,000 unique colors:

$colors = array();
while (true) {
   $color          = substr(str_shuffle('ABCDEF0123456789'), 0, 6);
   $colors[$color] = '#' . $color;
   if ( count($colors) == 10000 ) {
      echo implode(PHP_EOL, $colors);
      break;
   }
}

Which gave me these random colors as the result.


outis pointed out that my first example couldn't generate hexadecimals such as '4488CC' so I created a function which would be able to generate hexadecimals like that.

code

function randomHex() {
   $chars = 'ABCDEF0123456789';
   $color = '#';
   for ( $i = 0; $i < 6; $i++ ) {
      $color .= $chars[rand(0, strlen($chars) - 1)];
   }
   return $color;
}

echo randomHex();

The second example would be better to use because it can return a lot more different results than the first example, but if you aren't going to generate a lot of color codes then the first example would work just fine.

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

How to disable or enable viewpager swiping in android

In your custom view pager adapter, override those methods in ViewPager.

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    // Never allow swiping to switch between pages
    return false;
}

And to enable, just return each super method:

super.onInterceptTouchEvent(event) and super.onTouchEvent(event).

Check if a string within a list contains a specific string with Linq

If yoou use Contains, you could get false positives. Suppose you have a string that contains such text: "My text data Mdd LH" Using Contains method, this method will return true for call. The approach is use equals operator:

bool exists = myStringList.Any(c=>c == "Mdd LH")

Is there a constraint that restricts my generic method to numeric types?

If all you want is use one numeric type, you could consider creating something similar to an alias in C++ with using.

So instead of having the very generic

T ComputeSomething<T>(T value1, T value2) where T : INumeric { ... }

you could have

using MyNumType = System.Double;
T ComputeSomething<MyNumType>(MyNumType value1, MyNumType value2) { ... }

That might allow you to easily go from double to int or others if needed, but you wouldn't be able to use ComputeSomething with double and int in the same program.

But why not replace all double to int then? Because your method may want to use a double whether the input is double or int. The alias allows you to know exactly which variable uses the dynamic type.

What's the difference between emulation and simulation?

An "emulator" is a term for a software-based hardware-simulator, but in general the two are synonyms.

Xml serialization - Hide null values

It exists a property called XmlElementAttribute.IsNullable

If the IsNullable property is set to true, the xsi:nil attribute is generated for class members that have been set to a null reference.

The following example shows a field with the XmlElementAttribute applied to it, and the IsNullable property set to false.

public class MyClass
{
   [XmlElement(IsNullable = false)]
   public string Group;
}

You can have a look to other XmlElementAttribute for changing names in serialization etc.

How to call multiple functions with @click in vue?

First of all you can use the short notation @click instead of v-on:click for readability purposes.

Second You can use a click event handler that calls other functions/methods as @Tushar mentioned in his comment above, so you end up with something like this :

<div id="app">
   <div @click="handler('foo','bar')">
       Hi, click me!
   </div>
</div>

<!-- link to vue.js !--> 
<script src="vue.js"></script>

<script>
   (function(){
        var vm = new Vue({
            el:'#app',
            methods:{
                method1:function(arg){
                    console.log('method1: ',arg);
                },
                method2:function(arg){
                    console.log('method2: ',arg);
                },
                handler:function(arg1,arg2){
                    this.method1(arg1);
                    this.method2(arg2);
                }
            }
        })
    }()); 
</script>

"cannot resolve symbol R" in Android Studio

I see this problem may cause a lot of things. In my case, I had some textView in one of the activities *.xml files. I put inside it text in the editor (to change it later via code) this way: "NAME: <here will be name>". Apparently, "<" and ">" chars broke importing R in my project from every place. I changed it and it started to work. I just forgot I can't use those characters in *.xml files, because they build its structure. It is worth having this in mind.

How do you create a daemon in Python?

An alternative -- create a normal, non-daemonized Python program then externally daemonize it using supervisord. This can save a lot of headaches, and is *nix- and language-portable.

New to MongoDB Can not run command mongo

Specify the database path explicitly like so, and see if that resolves the issue.

mongod --dbpath data/db

tsconfig.json: Build:No inputs were found in config file

I ran into this issue constantly while packing my projects into nugets via Visual Studio 2019. After looking for a solution for ages I seem to have solved this by following advice in this article

MSBuild & Typescript

especially part about <TypeScriptCompile /> where I included all my .ts resources with the Include operator and excluded others such as node_modules with the Remove operator. I then deleted the tsconfig.json file in each offending project and the nuget packages were generated and no more errors

What is Type-safe?

Type-safe means that programmatically, the type of data for a variable, return value, or argument must fit within a certain criteria.

In practice, this means that 7 (an integer type) is different from "7" (a quoted character of string type).

PHP, Javascript and other dynamic scripting languages are usually weakly-typed, in that they will convert a (string) "7" to an (integer) 7 if you try to add "7" + 3, although sometimes you have to do this explicitly (and Javascript uses the "+" character for concatenation).

C/C++/Java will not understand that, or will concatenate the result into "73" instead. Type-safety prevents these types of bugs in code by making the type requirement explicit.

Type-safety is very useful. The solution to the above "7" + 3 would be to type cast (int) "7" + 3 (equals 10).

How to handle configuration in Go

I have started using Gcfg which uses Ini-like files. It's simple - if you want something simple, this is a good choice.

Here's the loading code I am using currently, which has default settings and allows command line flags (not shown) that override some of my config:

package util

import (
    "code.google.com/p/gcfg"
)

type Config struct {
    Port int
    Verbose bool
    AccessLog string
    ErrorLog string
    DbDriver string
    DbConnection string
    DbTblPrefix string
}

type configFile struct {
    Server Config
}

const defaultConfig = `
    [server]
    port = 8000
    verbose = false
    accessLog = -
    errorLog  = -
    dbDriver     = mysql
    dbConnection = testuser:TestPasswd9@/test
    dbTblPrefix  =
`

func LoadConfiguration(cfgFile string, port int, verbose bool) Config {
    var err error
    var cfg configFile

    if cfgFile != "" {
        err = gcfg.ReadFileInto(&cfg, cfgFile)
    } else {
        err = gcfg.ReadStringInto(&cfg, defaultConfig)
    }

    PanicOnError(err)

    if port != 0 {
        cfg.Server.Port = port
    }
    if verbose {
        cfg.Server.Verbose = true
    }

    return cfg.Server
}

How to collapse blocks of code in Eclipse?

I assume you are using Java, but look under the settings for your particular language.

Under the Window menu, select Preferences.

Under Java->Editor->Folding. Select "Enable Folding".

Remove Duplicate objects from JSON Array

Use Map to remove the duplicates. (For new readers)

_x000D_
_x000D_
var standardsList = [
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Counting & Cardinality"},
    {"Grade": "Math K", "Domain": "Geometry"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Counting & Cardinality"},
    {"Grade": "Math 1", "Domain": "Orders of Operation"},
    {"Grade": "Math 2", "Domain": "Geometry"},
    {"Grade": "Math 2", "Domain": "Geometry"}
];

var grades = new Map();
standardsList.forEach( function( item ) {
    grades.set(JSON.stringify(item), item);
});

console.log( [...grades.values()]);

/*
[
  { Grade: 'Math K', Domain: 'Counting & Cardinality' },
  { Grade: 'Math K', Domain: 'Geometry' },
  { Grade: 'Math 1', Domain: 'Counting & Cardinality' },
  { Grade: 'Math 1', Domain: 'Orders of Operation' },
  { Grade: 'Math 2', Domain: 'Geometry' }
]
*/
_x000D_
_x000D_
_x000D_

How to delete file from public folder in laravel 5.1

the easiest way for you to delete the image of the news is using the model event like below and the model delete the image if the news deleted

at first you should import this in top of the model class use Illuminate\Support\Facades\Storage after that in the model class News you should do this

public static function boot(){
    parent::boot();

    static::deleting(function ($news) {
          Storage::disk('public')->delete("{$news->image}");
    })
}

or you can delete the image in your controller with this command

Storage::disk('public')->delete("images/news/{$news->file_name}");

but you should know that the default disk is public but if you create folder in the public folder and put the image on that you should set the folder name before $news->file_name

error: ‘NULL’ was not declared in this scope

NULL can also be found in:

#include <string.h>

String.h will pull in the NULL from somewhere else.

DD/MM/YYYY Date format in Moment.js

for anyone who's using react-moment:

simply use format prop to your needed format:

const now = new Date()
<Moment format="DD/MM/YYYY">{now}</Moment>

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Field 'id' doesn't have a default value?

I had an issue on AWS with mariadb - This is how I solved the STRICT_TRANS_TABLES issue

SSH into server and chanege to the ect directory

[ec2-user]$ cd /etc

Make a back up of my.cnf

[ec2-user etc]$ sudo cp -a my.cnf{,.strict.bak}

I use nano to edit but there are others

[ec2-user etc]$ sudo nano my.cnf

Add this line in the the my.cnf file

#
#This removes STRICT_TRANS_TABLES
#
sql_mode=""

Then exit and save

OR if sql_mode is there something like this:

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

Change to

sql_mode=""

exit and save

then restart the database

[ec2-user etc]$ sudo systemctl restart mariadb

error: cast from 'void*' to 'int' loses precision

A function pointer is incompatible to void* (and any other non function pointer)

Remove empty strings from a list of strings

Depending on the size of your list, it may be most efficient if you use list.remove() rather than create a new list:

l = ["1", "", "3", ""]

while True:
  try:
    l.remove("")
  except ValueError:
    break

This has the advantage of not creating a new list, but the disadvantage of having to search from the beginning each time, although unlike using while '' in l as proposed above, it only requires searching once per occurrence of '' (there is certainly a way to keep the best of both methods, but it is more complicated).

How can I check if a string is null or empty in PowerShell?

You can use the IsNullOrEmpty static method:

[string]::IsNullOrEmpty(...)