text:
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) ![Built With C#](https://img.shields.io/badge/Built_with-C%23-green.svg)

# ChilliSource.Mobile.Location #

This project is part of the ChilliSource framework developed by [BlueChilli](https://github.com/BlueChilli).

## Summary ##

```ChilliSource.Mobile.Location``` provides location monitoring functionality and wrappers for the Google Roads, Directions, and Places APIs.

## Usage ##

### Location Monitoring ###

**Initialization**

To monitor the device's location first initialize the dependency service:

```csharp
var locationService = DependencyService.Get<ILocationService>();
locationService.Initialize(LocationAuthorizationType.Always, allowBackgroundLocationUpdates:false);
```

**Continuous Monitoring**

For continuous location monitoring subscribe to the ```PositionChanged``` event:

```csharp
locationService.PositionChanged += (sender, args) =>
{
    Console.WriteLine("Position changed to: " + args.Position.Latitude + " " + args.Position.Longitude);
};
```

Then tell the service to start listening for location changes by specifying the minimum
distance and time interval that should trigger the ```PositionChanged``` event to fire:
```csharp
locationService.StartListening(minTime: 1000, minDistance:10, includeHeading:false);
```

You can stop listening for location changes by calling ```StopListening```:
```csharp
locationService.StopListening();
```

**Once-Off Monitoring**

Alternatively if you would only like to retrieve the device's location once or at specific times, you can do so by calling ```GetPositionAsync``` instead of using the ```PositionChanged``` event:

```csharp
var position = await locationService.GetPositionAsync(timeout: 10, includeHeading: false);
Console.WriteLine("Current position: " + e.Position.Latitude + " " + e.Position.Longitude);
```

**Position Information**

You can retrieve additional information about the position from the returned ```Position``` object, including Accuracy, Altitude, Heading, Speed, Course, and Timestamp. Please note that some of these properties may not be available or the values may not be accurate depending on the platform and type of device used, GPS availability, etc.

### Google Places ###

With Google Places you can retrieve a list of addresses that match a search text that you specify:

```csharp
var placesService = new PlacesService(googlePlacesApiKey);

var result = await placesService.AutocompleteAsync(searchString, new AutocompleteRequest());
if (result.IsSuccessful)
{
    var predictions = result.Result.Predictions.ToList();
    if (predictions.Count > 0)
    {
        foreach (var prediction in predictions)
        {
            Console.WriteLine(prediction.Description + " - " + prediction.PlaceId);
        }
    }
}
```

### Logging within ChilliSource.Mobile ###
### Google Directions ###

To request directions, first construct a ```DirectionsRequest``` object with the start and end destination info. You can specify coordinates, addresses, or placeIds for the origin and destination:

```csharp
var request = new DirectionsRequest()
    {
        OriginCoordinates = new Tuple<string, string>("-33.865143", "151.209900"),
        DestinationCoordinates = new Tuple<string, string>("-34.123143", "147.998900")
    };
```

Then invoke the service and retrieve the directions:
```csharp
var directionsService = new DirectionsService(GoogleDirectionsApiKey);

var result = await directionsService.RequestDirections(request);
if (result.IsSuccessful)
{
    var response = result.Result;
    Console.WriteLine("Journey distance: " + response.GetJourneyDistanceInMeters() + "m");
    Console.WriteLine("Journey duration: " + response.GetJourneyDurationInSeconds() + "s");
    Console.WriteLine("Journey duration in traffic: " + response.GetJourneyDurationInSecondsInTraffic() + "s");

    var route = response.Routes.FirstOrDefault();
    var leg = route.Legs.FirstOrDefault();
    foreach (var step in legs.Steps)
    {
        Console.WriteLine(step.Instructions);
    }
}
```

### Google Roads ###

The roads service provides functionality to snap a set of points to fit the roads that
are the closest match to the points in order to create a navigation journey.

Simply provide the coordiantes of the original points and receive the snapped version of the points:

```csharp
var roadsService = new RoadsService(GoogleRoadsApiKey)

var positions = new List<Position>();
positions.Add(new Position(){Latitude=-33.86, Longitude=151.20});
positions.Add(new Position(){Latitude=-34.79, Longitude=151.23});
positions.Add(new Position(){Latitude=-34.80, Longitude=151.45});

var result = await roadsService.RequestSnappedLocations(positions, shouldInterpolate:false);

if (result.IsSuccessful)
{
    foreach (var point in result.Result.SnappedPoints)
    {
        Console.WriteLine("Lat: " + point.Location.Latitude + " Lng: " + point.Location.Longitude);
    }
}
```

## Installation ##

The library is available via NuGet [here](https://www.nuget.org/packages/ChilliSource.Mobile.Location).

## Releases ##

See the [releases](https://github.com/BlueChilli/ChilliSource.Mobile.Location/releases).

## Contribution ##

Please see the [Contribution Guide](.github/CONTRIBUTING.md).

## License ##

ChilliSource.Mobile is licensed under the [MIT license](LICENSE).

## Feedback and Contact ##

For questions or feedback, please contact [chillisource@bluechilli.com](mailto:chillisource@bluechilli.com).


text:
package br.mil.mar.casnav.mclm.action;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.StrutsStatics;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionContext;

import br.mil.mar.casnav.mclm.persistence.services.SceneryService;

@Action (value = "updateSceneryData", results = {
	    @Result(name="ok", type="httpheader", params={"status", "200"}) },
		interceptorRefs= { @InterceptorRef("seguranca")	 }
)

@ParentPackage("default")
public class UpdateCenarioDataAction extends BasicActionClass {
	private String mapCenter;
	private Integer idScenery;
	private Integer mapZoom;
	private String mapaBase;
	private String servidorBase;
	private String mapBbox;
	private Boolean mapaBaseAtivo;
	private Boolean gradeAtiva;

	public String execute () {
		String resp;

		try {
			SceneryService sns = new SceneryService();
			resp = sns.updateScenery( idScenery, mapCenter, mapZoom, mapaBase, servidorBase, mapBbox, mapaBaseAtivo, gradeAtiva );

			HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json");
			response.getWriter().write( resp );
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return "ok";
	}

	public void setMapCenter(String mapCenter) {
		this.mapCenter = mapCenter;
	}

	public void setIdScenery(Integer idScenery) {
		this.idScenery = idScenery;
	}

	public void setMapZoom(Integer mapZoom) {
		this.mapZoom = mapZoom;
	}

	public void setMapaBase(String mapaBase) {
		this.mapaBase = mapaBase;
	}

	public void setServidorBase(String servidorBase) {
		this.servidorBase = servidorBase;
	}

	public void setMapBbox(String mapBbox) {
		this.mapBbox = mapBbox;
	}

	public void setMapaBaseAtivo(Boolean mapaBaseAtivo) {
		this.mapaBaseAtivo = mapaBaseAtivo;
	}

	public void setGradeAtiva(Boolean gradeAtiva) {
		this.gradeAtiva = gradeAtiva;
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template local</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../xpressive/reference.html#header.boost.xpressive.xpressive_fwd_hpp" title="Header <boost/xpressive/xpressive_fwd.hpp>">
<link rel="prev" href="reference.html" title="Struct template reference">
<link rel="next" href="placeholder.html" title="Struct template placeholder">

Home
Libraries
People
FAQ
More

Struct template local

boost::xpressive::local — local<> is a lazy wrapper for a reference to a value that is stored within the local itself. It is for use within xpressive semantic actions.

Synopsis

// In header: <boost/xpressive/xpressive_fwd.hpp>

template<typename T>
struct local : public proto::terminal::type< reference_wrapper< T > > {
  // construct/copy/destruct
  local();
  explicit local(T const &);

  // public member functions
  T & get();
  T const & get() const;
};

Description

Below is an example of how to use local<> in semantic actions.

using namespace boost::xpressive;
local<int> i(0);
std::string str("1!2!3?");
// count the exciting digits, but not the
// questionable ones.
sregex rex = +( _d [ ++i ] >> '!' );
regex_search(str, rex);
assert( i.get() == 2 );

Note

As the name "local" suggests, local<> objects and the regexes that refer to them should never leave the local scope. The value stored within the local object will be destroyed at the end of the local<>'s lifetime, and any regex objects still holding the local<> will be left with a dangling reference.

Template Parameters

typename T

The type of the local variable.

local
        public
       construct/copy/destruct

local();
Store a default-constructed value of type T.

explicit local(T const & t);
Store a default-constructed value of type T.

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

t

The initial value.

local public member functions

T & get();
Fetch the wrapped value.

T const & get() const;

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Copyright © 2007 Eric Niebler

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package azkaban.viewer.hdfs.utils;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.hadoop.hive.serde2.SerDeUtils;
import org.apache.hadoop.hive.serde2.objectinspector.ListObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.MapObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.StructField;
import org.apache.hadoop.hive.serde2.objectinspector.StructObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.UnionObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.BinaryObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.BooleanObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.ByteObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.DateObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.DoubleObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.FloatObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveDecimalObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.HiveVarcharObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.IntObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.ShortObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;

/**
 * Adapted from @see org.apache.hadoop.hive.serde2.SerDeUtils to escape binary
 * string and have a valid JSON String
 */
public final class SerDeUtilsWrapper {

    /**
     * Get serialized json using an orc object and corresponding object
     * inspector Adapted from
     * {@link org.apache.hadoop.hive.serde2.SerDeUtils#getJSONString(Object, ObjectInspector)}
     *
     * @param obj
     * @param objIns
     * @return
     */
    public static String getJSON(Object obj, ObjectInspector objIns) {
        StringBuilder sb = new StringBuilder();
        buildJSONString(sb, obj, objIns);
        return sb.toString();
    }

    private static void buildJSONString(StringBuilder sb, Object obj,
        ObjectInspector objIns) {
        String nullStr = "null";
        switch (objIns.getCategory()) {
        case PRIMITIVE: {
            PrimitiveObjectInspector poi = (PrimitiveObjectInspector) objIns;
            if (obj == null) {
                sb.append(nullStr);
            } else {
                switch (poi.getPrimitiveCategory()) {
                case BOOLEAN: {
                    boolean b = ((BooleanObjectInspector) poi).get(obj);
                    sb.append(b ? "true" : "false");
                    break;
                }
                case BYTE: {
                    sb.append(((ByteObjectInspector) poi).get(obj));
                    break;
                }
                case SHORT: {
                    sb.append(((ShortObjectInspector) poi).get(obj));
                    break;
                }
                case INT: {
                    sb.append(((IntObjectInspector) poi).get(obj));
                    break;
                }
                case LONG: {
                    sb.append(((LongObjectInspector) poi).get(obj));
                    break;
                }
                case FLOAT: {
                    sb.append(((FloatObjectInspector) poi).get(obj));
                    break;
                }
                case DOUBLE: {
                    sb.append(((DoubleObjectInspector) poi).get(obj));
                    break;
                }
                case STRING: {
                    sb.append('"');
                    sb.append(SerDeUtils
                        .escapeString(((StringObjectInspector) poi)
                            .getPrimitiveJavaObject(obj)));
                    sb.append('"');
                    break;
                }
                case VARCHAR: {
                    sb.append('"');
                    sb.append(SerDeUtils
                        .escapeString(((HiveVarcharObjectInspector) poi)
                            .getPrimitiveJavaObject(obj).toString()));
                    sb.append('"');
                    break;
                }
                case DATE: {
                    sb.append('"');
                    sb.append(((DateObjectInspector) poi)
                        .getPrimitiveWritableObject(obj));
                    sb.append('"');
                    break;
                }
                case TIMESTAMP: {
                    sb.append('"');
                    sb.append(((TimestampObjectInspector) poi)
                        .getPrimitiveWritableObject(obj));
                    sb.append('"');
                    break;
                }
                case BINARY: {
                    BytesWritable bw =
                        ((BinaryObjectInspector) objIns)
                            .getPrimitiveWritableObject(obj);
                    Text txt = new Text();
                    txt.set(bw.getBytes(), 0, bw.getLength());
                    // Fix to serialize binary type
                    sb.append('"');
                    sb.append(StringEscapeUtils.escapeJava(txt.toString()));
                    sb.append('"');
                    break;
                }
                case DECIMAL: {
                    sb.append(((HiveDecimalObjectInspector) objIns)
                        .getPrimitiveJavaObject(obj));
                    break;
                }
                default:
                    throw new RuntimeException("Unknown primitive type: "
                        + poi.getPrimitiveCategory());
                }
            }
            break;
        }
        case LIST: {
            ListObjectInspector loi = (ListObjectInspector) objIns;
            ObjectInspector listElementObjectInspector =
                loi.getListElementObjectInspector();
            List<?> olist = loi.getList(obj);
            if (olist == null) {
                sb.append(nullStr);
            } else {
                sb.append(SerDeUtils.LBRACKET);
                for (int i = 0; i < olist.size(); i++) {
                    if (i > 0) {
                        sb.append(SerDeUtils.COMMA);
                    }
                    buildJSONString(sb, olist.get(i),
                        listElementObjectInspector);
                }
                sb.append(SerDeUtils.RBRACKET);
            }
            break;
        }
        case MAP: {
            MapObjectInspector moi = (MapObjectInspector) objIns;
            ObjectInspector mapKeyObjectInspector =
                moi.getMapKeyObjectInspector();
            ObjectInspector mapValueObjectInspector =
                moi.getMapValueObjectInspector();
            Map<?, ?> omap = moi.getMap(obj);
            if (omap == null) {
                sb.append(nullStr);
            } else {
                sb.append(SerDeUtils.LBRACE);
                boolean first = true;
                for (Object entry : omap.entrySet()) {
                    if (first) {
                        first = false;
                    } else {
                        sb.append(SerDeUtils.COMMA);
                    }
                    Map.Entry<?, ?> e = (Map.Entry<?, ?>) entry;
                    buildJSONString(sb, e.getKey(), mapKeyObjectInspector);
                    sb.append(SerDeUtils.COLON);
                    buildJSONString(sb, e.getValue(), mapValueObjectInspector);
                }
                sb.append(SerDeUtils.RBRACE);
            }
            break;
        }
        case STRUCT: {
            StructObjectInspector soi = (StructObjectInspector) objIns;
            List<? extends StructField> structFields =
                soi.getAllStructFieldRefs();
            if (obj == null) {
                sb.append(nullStr);
            } else {
                sb.append(SerDeUtils.LBRACE);
                for (int i = 0; i < structFields.size(); i++) {
                    if (i > 0) {
                        sb.append(SerDeUtils.COMMA);
                    }
                    sb.append(SerDeUtils.QUOTE);
                    sb.append(structFields.get(i).getFieldName());
                    sb.append(SerDeUtils.QUOTE);
                    sb.append(SerDeUtils.COLON);
                    buildJSONString(sb,
                        soi.getStructFieldData(obj, structFields.get(i)),
                        structFields.get(i).getFieldObjectInspector());
                }
                sb.append(SerDeUtils.RBRACE);
            }
            break;
        }
        case UNION: {
            UnionObjectInspector uoi = (UnionObjectInspector) objIns;
            if (obj == null) {
                sb.append(nullStr);
            } else {
                sb.append(SerDeUtils.LBRACE);
                sb.append(uoi.getTag(obj));
                sb.append(SerDeUtils.COLON);
                buildJSONString(sb, uoi.getField(obj), uoi
                    .getObjectInspectors().get(uoi.getTag(obj)));
                sb.append(SerDeUtils.RBRACE);
            }
            break;
        }
        default:
            throw new RuntimeException("Unknown type in ObjectInspector!");
        }
    }

}


text:
board_runner_args(stm32flash "--baud-rate=115200" "--start-addr=0x08000000")
board_runner_args(jlink "--device=STM32F103RB" "--speed=4000")

include(${ZEPHYR_BASE}/boards/common/stm32flash.board.cmake)
include(${ZEPHYR_BASE}/boards/common/openocd.board.cmake)
include(${ZEPHYR_BASE}/boards/common/jlink.board.cmake)


text:
// Copyright (c) Dyoub Applications. All rights reserved.
// Licensed under MIT (https://github.com/dyoub/app/blob/master/LICENSE).

using Dyoub.App.Models.EntityModel.Account.Tenants;
using Dyoub.App.Models.EntityModel.Account.Users;
using Dyoub.App.Infrastructure.Security;
using System;

namespace Dyoub.Test.Factories.Account
{
    public class UserFactory
    {
        public static User User()
        {
            User user = new User();
            user.Name = "User Test";
            user.Email = "user@test.com";
            user.Password = "12345678";

            return user;
        }

        public static User User(Tenant tenant)
        {
            User user = User();
            user.Salt = Guid.NewGuid().ToString("N");
            user.Password = new Sha256Hash(user.Password, user.Salt).ToString();
            user.LastChangePassword = DateTime.UtcNow.Date.AddDays(-1);
            user.Tenant = tenant;

            return user;
        }

        public static User AuthenticatedUser(Tenant tenant)
        {
            User user = User(tenant);
            user.Token = new AccessToken().ToString();

            return user;
        }
    }
}


text:
package poly1305 // import "golang.org/x/crypto/poly1305"

import "crypto/subtle"

// TagSize is the size, in bytes, of a poly1305 authenticator.
const TagSize = 16

// Verify returns true if mac is a valid authenticator for m with the given
// key.
func Verify(mac *[16]byte, m []byte, key *[32]byte) bool {
	var tmp [16]byte
	Sum(&tmp, m, key)
	return subtle.ConstantTimeCompare(tmp[:], mac[:]) == 1
}

// New returns a new MAC computing an authentication
// tag of all data written to it with the given key.
// This allows writing the message progressively instead
// of passing it as a single slice. Common users should use
// the Sum function instead.
//
// The key must be unique for each message, as authenticating
// two different messages with the same key allows an attacker
// to forge messages at will.
func New(key *[32]byte) *MAC {
	return &MAC{
		mac:       newMAC(key),
		finalized: false,
	}
}

// MAC is an io.Writer computing an authentication tag
// of the data written to it.
//
// MAC cannot be used like common hash.Hash implementations,
// because using a poly1305 key twice breaks its security.
// Therefore writing data to a running MAC after calling
// Sum causes it to panic.
type MAC struct {
	mac // platform-dependent implementation

	finalized bool
}

// Size returns the number of bytes Sum will return.
func (h *MAC) Size() int { return TagSize }

// Write adds more data to the running message authentication code.
// It never returns an error.
//
// It must not be called after the first call of Sum.
func (h *MAC) Write(p []byte) (n int, err error) {
	if h.finalized {
		panic("poly1305: write to MAC after Sum")
	}
	return h.mac.Write(p)
}

// Sum computes the authenticator of all data written to the
// message authentication code.
func (h *MAC) Sum(b []byte) []byte {
	var mac [TagSize]byte
	h.mac.Sum(&mac)
	h.finalized = true
	return append(b, mac[:]...)
}


text:
require 'iis_object'
require 'application'

module IISConfig

  class Site < IISObject

    def initialize
      @bindings = []
      @applications = []
      @virtual_directories = []
      @path = '/'
    end

    def name(name = nil)
      @name = name unless name.nil?
      @name
    end

    def binding(binding)
      @bindings << binding
    end

    def path(path)
      @path = path
    end

    def app_pool(pool)
      @app_pool = pool
    end

    def physical_path(path)
      @physical_path = path
    end

    def application(&block)
      add_instance(@applications, IISConfig::Application, block)
    end

    def virtual_directory(&block)
      add_instance(@virtual_directories, IISConfig::VirtualDirectory, block)
    end

    def delete
      %W{DELETE SITE #{@name}}
    end

    def add
      args = []
      args << 'ADD'
      args << 'SITE'
      args << "/name:#{@name}"
      args << "/bindings:\"#{@bindings.join('","')}\""
      args << "/physicalPath:#{@physical_path.gsub(/\//, '\\')}"

      args
    end

    def required_paths
      paths = []
      paths << @physical_path
      paths
    end

    def build_commands()
      commands = []
      commands << delete if exist? :site, @name
      commands << add
      commands << %W{SET SITE /site.name:#{@name} /[path='#{@path}'].applicationPool:#{@app_pool}} unless @app_pool.nil?
      commands << %W{SET SITE /site.name:#{@name} /[path='#{@path}']} if @app_pool.nil?

      @applications.each do |s|
        commands += s.build_commands @name, @app_pool
      end

      @virtual_directories.each do |s|
        commands += s.build_commands "#{name}/"
      end

      commands
    end

  end

end


text:
rain princess 雨公主

```
$ sudo pip install -U floyd-cli
$ floyd login
// Copy and paste your authentication token
$ git clone https://github.com/floydhub/fast-style-transfer
$ cd fast-style-transfer
$ floyd init fast-style-transfer
Project "fast-style-transfer" initialized in current directory
$ floyd run --gpu --env keras:py2 --data jq4ZXUCSVer4t65rWeyieG "python style.py --style examples/style/la_muse.jpg --base-model-path /input/pre-trained-tf/la_muse.ckpt --epoch 1 --total-iterations 10 --checkpoint-dir /output"

Creating project run. Total upload size: 22.2MiB
Syncing code ...

RUN ID                  NAME                                 VERSION
----------------------  ---------------------------------  ---------
GNc3QbAtsj6U8yCsNizPgN  y12floydhub/fast-style-transfer:1          1

To view logs enter:
    floyd logs GNc3QbAtsj6U8yCsNizPgN

$ floyd logs GNc3QbAtsj6U8yCsNizPgN
2017-03-21 21:27:49,697 INFO - Preparing to run TaskInstance <TaskInstance: y12floydhub/fast-style-transfer:1 (id: wYnoL4qQv8Z7KiGJpDq8wY) (checksum: ec051eca5364a2503281cb57b1702565) (last update: 2017-03-21 21:27:49.549554) [queued]>
2017-03-21 21:27:49,712 INFO - Starting attempt 1 at 2017-03-21 21:27:49.702845
2017-03-21 21:27:54,030 INFO - adding pip install -r floyd_requirements
2017-03-21 21:27:54,045 INFO - Executing command in container: stdbuf -o0 sh command.sh
2017-03-21 21:27:54,045 INFO - Pulling Docker image: floydhub/tensorflow:latest-gpu-py2
2017-03-21 21:27:58,216 INFO - Starting container...
2017-03-21 21:27:59,334 INFO -
################################################################################

2017-03-21 21:27:59,334 INFO - Run Output:

$ floyd status GNc3QbAtsj6U8yCsNizPgN
RUN ID                  CREATED       STATUS      DURATION(s)  NAME                               INSTANCE      VERSION
----------------------  ------------  --------  -------------  ---------------------------------  ----------  ---------
GNc3QbAtsj6U8yCsNizPgN  a minute ago  running               0  y12floydhub/fast-style-transfer:1  gpu                 1

$ floyd info GNc3QbAtsj6U8yCsNizPgN
-----------  ---------------------------------
Run ID       GNc3QbAtsj6U8yCsNizPgN
Name         y12floydhub/fast-style-transfer:1
Created      2 minutes ago
Status       running
Duration(s)  0
Output ID    wYnoL4qQv8Z7KiGJpDq8wY
Instance     gpu
Version      1
-----------  ---------------------------------

$ floyd run --env keras:py2 --data wYnoL4qQv8Z7KiGJpDq8wY "python evaluate.py --allow-different-dimensions  --checkpoint /input/fns.ckpt --in-path ./images/ --out-path /output/"

Syncing code ...
RUN ID                  NAME                                 VERSION
----------------------  ---------------------------------  ---------
YJYN67ZyKsa2dppa92eaEF  y12floydhub/fast-style-transfer:2          2

To view logs enter:
    floyd logs YJYN67ZyKsa2dppa92eaEF

$ floyd info YJYN67ZyKsa2dppa92eaEF
-----------  ---------------------------------
Run ID       YJYN67ZyKsa2dppa92eaEF
Name         y12floydhub/fast-style-transfer:2
Created      12 minutes ago
Status       queued
Duration(s)  0
Output ID
Instance     cpu
Version      2

// queued ?

$ floyd run --gpu --env keras:py2 --data Js534T344XYBPMvWqhxJNj "python evaluate.py --allow-different-dimensions --checkpoint /input/rain_princess.ckpt --in-path ./images/ --out-path /output/"

// After 4 hours ....
$ floyd info LW79dH4BjucodwSUKLjTi5
-----------  ---------------------------------
Run ID       LW79dH4BjucodwSUKLjTi5
Name         y12floydhub/fast-style-transfer:3
Created      4 hours ago
Status       running
Duration(s)  0
Output ID    DcjKXUaGDEHsESXEKj6SbS
Instance     gpu
Version      3
-----------  ---------------------------------
```

### References
* Style Transfer - FloydHub  http://docs.floydhub.com/guides/style_transfer/
* Floyd Zero Setup Deep Learning https://www.floydhub.com/
* floydhub/fast-style-transfer: Fast Style Transfer in TensorFlow! ⚡🖥🎨🖼  https://github.com/floydhub/fast-style-transfer
* floydhub/dl-setup: Instructions for setting up the software on your deep learning machine  https://github.com/floydhub/dl-setup
* 被稱為心理治療效用的藝術,Leonid Afremov撼動人心的油畫世界! | 時尚華爾滋  http://www.fashionwaltz.com/?p=3693


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInitf7aaf7b3b6722ecce22a2a6d7f3970c7::getLoader();


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Tylophoron nidulans Stirt.

### Remarks
null


text:
title: Expanding into New Frontiers - Smart DNS Proxying in Istio
subtitle: Use workload-local DNS resolution to simplify VM integration, multicluster, and more
description: Workload Local DNS resolution to simplify VM integration, multicluster, and more.
publishdate: 2020-11-12
attribution: "Shriram Rajagopalan (Tetrate.io) on behalf of Istio Networking WG"
keywords: [dns,sidecar,multicluster,vm,external services]
---

DNS resolution is a vital component of any application infrastructure
on Kubernetes. When your application code attempts to access another
service in the Kubernetes cluster or even a service on the internet,
it has to first lookup the IP address corresponding to the hostname of
the service, before initiating a connection to the service. This name
lookup process is often referred to as **service discovery**. In
Kubernetes, the cluster DNS server, be it `kube-dns` or CoreDNS,
resolves the service's hostname to a unique non-routable virtual IP (VIP),
if it is a service of type `clusterIP`. The `kube-proxy` on each node
maps this VIP to a set of pods of the service, and forwards the traffic
to one of them selected at random. When using a service mesh, the
sidecar works similarly to the `kube-proxy` as far as traffic forwarding
is concerned.

The following diagram depicts the role of DNS today:

{{< image width="75%"
    link="./role-of-dns-today.png"
    alt="Role of DNS in Istio, today"
    caption="Role of DNS in Istio, today"
>}}

## Problems posed by DNS

While the role of DNS within the service mesh may seem insignificant,
it has consistently stood in the way of expanding the mesh to VMs and
enabling seamless multicluster access.

### VM access to Kubernetes services

Consider the case of a VM with a sidecar. As shown in the illustration
below, applications on the VM look up the IP addresses of services
inside the Kubernetes cluster as they typically have no access to the
cluster's DNS server.

{{< image width="75%"
    link="./vm-dns-resolution-issues.png"
    alt="DNS resolution issues on VMs accessing Kubernetes services"
    caption="DNS resolution issues on VMs accessing Kubernetes services"
>}}

It is technically possible to use `kube-dns` as a name server on the VM if one is
willing to engage in some convoluted workarounds involving `dnsmasq` and
external exposure of `kube-dns` using `NodePort` services: assuming you
manage to convince your cluster administrator to do so. Even so, you are
opening the door to a host of [security
issues](https://blog.aquasec.com/dns-spoofing-kubernetes-clusters). At
the end of the day, these are point solutions that are typically out
of scope for those with limited organizational capability and domain
expertise.

### External TCP services without VIPs

It is not just the VMs in the mesh that suffer from the DNS issue. For
the sidecar to accurately distinguish traffic between two different
TCP services that are outside the mesh, the services must be on
different ports or they need to have a globally unique VIP, much like
the `clusterIP` assigned to Kubernetes services. But what if there is
no VIP? Cloud hosted services like hosted databases, typically do not
have a VIP. Instead, the provider's DNS server returns one of the
instance IPs that can then be directly accessed by the
application. For example, consider the two service entries below,
pointing to two different AWS RDS services:

{{< text yaml >}}
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: db1
  namespace: ns1
spec:
  hosts:
  - mysql-instance1.us-east-1.rds.amazonaws.com
  ports:
  - name: mysql
    number: 3306
    protocol: TCP
  resolution: DNS
---
apiVersion: networking.istio.io/v1alpha3
kind: ServiceEntry
metadata:
  name: db2
  namespace: ns1
spec:
  hosts:
  - mysql-instance2.us-east-1.rds.amazonaws.com
  ports:
  - name: mysql
    number: 3306
    protocol: TCP
  resolution: DNS
{{< /text >}}

The sidecar has a single listener on `0.0.0.0:3306` that looks up the
IP address of `mysql-instance1.us-east1.rds.amazonaws.com` from public
DNS servers and forwards traffic to it. It cannot route traffic to
`db2` as it has no way of distinguishing whether traffic arriving at
`0.0.0.0:3306` is bound for `db1` or `db2`. The only way to accomplish
this is to set the resolution to `NONE` causing the sidecar to
_blindly forward any traffic_ on port `3306` to the original IP
requested by the application. This is akin to punching a hole in the
firewall allowing all traffic to port `3306` irrespective of the
destination IP. To get traffic flowing, you are now forced to
compromise on the security posture of your system.

### Resolving DNS for services in remote clusters

The DNS limitations of a multicluster mesh are well known. Services in
one cluster cannot lookup the IP addresses of services in other
clusters, without clunky workarounds such as creating stub services in
the caller namespace.

## Taking control of DNS

All in all, DNS has been a thorny issue in Istio for a while. It was
time to slay the beast. We (the Istio networking team) decided to
tackle the problem once and for all in a way that is completely
transparent to you, the end user. Our first attempt involved utilizing
Envoy's DNS proxy. It turned out to be very unreliable, and
disappointing overall due to the general lack of sophistication in
the c-ares DNS library used by Envoy. Determined to solve the
problem, we decided to implement the DNS proxy in the Istio sidecar
agent, written in Go. We were able to optimize the implementation to
handle all the scenarios that we wanted to tackle without compromising
on scale and stability. The Go DNS library we use is the same one
used by scalable DNS implementations such as CoreDNS, Consul,
Mesos, etc. It has been battle tested in production for scale and stability.

Starting with Istio 1.8, the Istio agent on the sidecar will ship with
a caching DNS proxy, programmed dynamically by Istiod. Istiod pushes
the hostname-to-IP-address mappings for all the services that the
application may access based on the Kubernetes services and service
entries in the cluster. DNS lookup queries from the application are
transparently intercepted and served by the Istio agent in the pod or
VM. If the query is for a service within the mesh, _irrespective of
the cluster that the service is in_, the agent responds directly to the
application. If not, it forwards the query to the upstream name
servers defined in `/etc/resolv.conf`. The following diagram depicts
the interactions that occur when an application tries to access a
service using its hostname.

{{< image width="75%"
    link="./dns-interception-in-istio.png"
    alt="Smart DNS proxying in Istio sidecar agent"
    caption="Smart DNS proxying in Istio sidecar agent"
>}}

As you will see in the following sections, _the DNS proxying feature
has had an enormous impact across many aspects of Istio._

### Reduced load on your DNS servers w/ faster resolution

The load on your cluster's Kubernetes DNS server drops drastically as
almost all DNS queries are resolved within the pod by Istio. The
bigger the footprint of mesh on a cluster, the lesser the load on your
DNS servers. Implementing our own DNS proxy in the Istio agent has
allowed us to implement cool optimizations such as [CoreDNS
auto-path](https://coredns.io/plugins/autopath/) without the
correctness issues that CoreDNS currently faces.

To understand the impact of this optimization, lets take a simple DNS
lookup scenario, in a standard Kubernetes cluster without any custom
DNS setup for pods - i.e., with the default setting of `ndots:5` in `/etc/resolv.conf`.
When your application starts a DNS lookup for
`productpage.ns1.svc.cluster.local`, it appends the DNS search
namespaces in `/etc/resolv.conf` (e.g., `ns1.svc.cluster.local`) as part
of the DNS query, before querying the host as-is. As a result, the
first DNS query that is actually sent out will look like
`productpage.ns1.svc.cluster.local.ns1.svc.cluster.local`, which will
inevitably fail DNS resolution when Istio is not involved. If your
`/etc/resolv.conf` has 5 search namespaces, the application will send
two DNS queries for each search namespace, one for the IPv4 `A` record
and another for the IPv6 `AAAA` record, and then a final pair of
queries with the exact hostname used in the code. _Before establishing the
connection, the application performs 12 DNS lookup queries for each host!_

With Istio's implementation of the CoreDNS style auto-path technique,
the sidecar agent will detect the real hostname being queried within
the first query and return a `cname` record to
`productpage.ns1.svc.cluster.local` as part of this DNS response, as
well as the `A/AAAA` record for
`productpage.ns1.svc.cluster.local`. The application receiving this
response can now extract the IP address immediately and proceed to
establishing a TCP connection to that IP. _The smart DNS proxy in the
Istio agent dramatically cuts down the number of DNS queries from 12
to just 2!_

### VMs to Kubernetes integration

Since the Istio agent performs local DNS resolution for services
within the mesh, DNS lookup queries for Kubernetes services from VMs will now
succeed without requiring clunky workarounds for exposing `kube-dns`
outside the cluster. The ability to seamlessly resolve internal
services in a cluster will now simplify your monolith to microservice
journey, as the monolith on VMs can now access microservices on
Kubernetes without additional levels of indirection via API gateways.

### Automatic VIP allocation where possible

You may ask, how does this DNS functionality in the agent solve the
problem of distinguishing between multiple external TCP services
without VIPs on the same port?

Taking inspiration from Kubernetes, Istio will now automatically
allocate non-routable VIPs (from the Class E subnet) to such services
as long as they do not use a wildcard host. The Istio agent on the
sidecar will use the VIPs as responses to the DNS lookup queries from
the application. Envoy can now clearly distinguish traffic bound for
each external TCP service and forward it to the right target. With the
introduction of the DNS proxying, you will no longer need to use
`resolution: NONE` for non-wildcard TCP services, improving your
overall security posture. Istio cannot help much with wildcard
external services (e.g., `*.us-east1.rds.amazonaws.com`). You will
have to resort to NONE resolution mode to handle such services.

### Multicluster DNS lookup

For the adventurous lot, attempting to weave a multicluster mesh where
applications directly call internal services of a namespace in a
remote cluster, the DNS proxy functionality comes in quite handy. Your
applications can _resolve Kubernetes services on any cluster in any
namespace_, without the need to create stub Kubernetes services in
every cluster.

The benefits of the DNS proxy extend beyond the multicluster models
that are currently described in Istio today.  At Tetrate, we use this
mechanism extensively in our customers' multicluster deployments to
enable sidecars to resolve DNS for hosts exposed at ingress gateways
of all the clusters in a mesh, and access them over mutual TLS.

## Concluding thoughts

The problems caused by lack of control over DNS have often been
overlooked and ignored in its entirety when it comes to weaving a mesh
across many clusters, different environments, and integrating external
services. The introduction of a caching DNS proxy in the Istio sidecar
agent solves these issues. Exercising control over the
application's DNS resolution allows Istio to accurately identify the
target service to which traffic is bound, and enhance the overall
security, routing, and telemetry posture in Istio within and across
clusters.

Smart DNS proxying is enabled in the `preview`
profile in Istio 1.8. Please try it out!


text:
module NetGSM
	class SMS
		def self.send_sms(recipient, message_text, opts={})
			valid_options = opts.only(:from, :start_date, :stop_date, :turkish)
			valid_options.merge!(:start_date => NetGSM::DATE.now) unless valid_options[:start_date]
			valid_options.merge!(:stop_date => NetGSM::DATE.n_hour_from_now(1)) unless valid_options[:stop_date]

			body = NetGSM::XmlBody.send_sms_body(recipient, message_text, valid_options)

			response = send_request(body)

			result = parse_response(response)
			return {code: result[0], sms_id: result[1]}
		end

		# message_array format [[phone_number, 'sms message body']]
		def self.send_mass_sms(message_array = [], opts={})
			valid_options = opts.only(:from, :start_date, :stop_date, :turkish)
			valid_options.merge!(:start_date => NetGSM::DATE.now) unless valid_options[:start_date]
			valid_options.merge!(:stop_date => NetGSM::DATE.n_hour_from_now(1)) unless valid_options[:stop_date]

			body = NetGSM::XmlBody.send_mass_sms_body(message_array, valid_options)

			response = send_request(body)

			result = parse_response(response)
			return {code: result[0], sms_id: result[1]}
		end

		def sms_status
			'OK status'
		end

		def check_balance
			'OK Balance'
		end

		def initialize(auth_options={})
			@auth_options = auth_options
		end

		def self.send_request(body)
		    header = {
		      "Content-Type" => "text/xml; charset=utf-8",
		      "Content-Length" => body.bytesize.to_s,
		      "Accept" => "*/*"
		    }

		    request = Net::HTTP::Post.new('/xmlbulkhttppost.asp', header)
		    request.body = body
		    #puts  "Request #{@header} #{request.body} "
		    response = Net::HTTP.new(NetGSM.configuration.host, NetGSM.configuration.port).start {|http| http.request(request) }
		    #puts "Response #{response.code} #{response.message}: #{response.body}"

		    # parser = XMLRPC::XMLParser::REXMLStreamParser::StreamListener.new
		    # parser.parse(response.body)

		    return response.body
		end

		def self.parse_response(body)
			body.split(" ")
		end
	end
end


text:
alias pgStart="brew services start postgresql"
alias pgStop="brew services stop postgresql"
alias mysqlStart="brew services start mysql@5.7"
alias mysqlStop="brew services stop mysql@5.7"
alias mongoStart="brew services start mongodb-community"
alias mongoStop="brew services stop mongodb-community"
alias dbStop="pgStop && mysqlStop && mongoStop"


text:
package org.bubblecloud.zigbee.api.cluster.impl.core;

import org.bubblecloud.zigbee.network.ClusterMessage;
import org.bubblecloud.zigbee.util.ByteUtils;

import org.bubblecloud.zigbee.api.cluster.impl.api.core.Command;

/**
 * @author Stefano "Kismet" Lenzi
 * @author Francesco Furfari
 * @version $LastChangedRevision: 799 $ ($LastChangedDate: 2013-08-06 19:00:05 +0300 (Tue, 06 Aug 2013) $)
 */
public class ZCLFrame {

    private ZCLHeaderImpl header;
    private byte[] payload;
    private byte[] frame;

    public ZCLFrame(ClusterMessage clusterMessage) {
        byte[] frame = clusterMessage.getClusterMsg();
        header = new ZCLHeaderImpl(frame);

        int srcPos = header.size();
        int lenght = frame.length - header.size();
        payload = new byte[lenght];
        System.arraycopy(frame, srcPos, payload, 0, lenght);
    }

    public ZCLFrame(Command cmd, boolean isEnableddefaultResponse) {
        header = new ZCLHeaderImpl(cmd, isEnableddefaultResponse);
        payload = cmd.getPayload();
        frame = createFrame();
    }

    public ZCLHeaderImpl getHeader() {
        return header;
    }

    public byte[] getPayload() {
        return payload;
    }

    private byte[] createFrame() {
        byte[] frame = new byte[header.size() + payload.length];
        System.arraycopy(header.toByte(), 0, frame, 0, header.size());
        System.arraycopy(payload, 0, frame, header.size(), payload.length);
        return frame;
    }

    public byte[] toByte() {
        return frame;
    }

    public int size() {
        return toByte().length;
    }

    public String toString() {
        return
                "[ ZCL Header: " + ByteUtils.toBase16(getHeader().toByte())
                        + ", ZCL Payload: " + ByteUtils.toBase16(getPayload())
                        + "]";
    }
}


text:
import {
  TEXT_BUTTON_PRIORITY,
  TextButton,
  TextButtonProps,
} from '../../TextButton';
import * as React from 'react';

export class AvatarGroupTextButton extends TextButton {
  static defaultProps: TextButtonProps = {
    priority: TEXT_BUTTON_PRIORITY.secondary,
  };
}


text:
using System.Data.Entity;
using Chamber.Domain.Constants;
using Chamber.Domain.Interfaces;
using Chamber.Domain.Interfaces.UnitOfWork;
using Chamber.Services.Data.Context;
using Chamber.Services.Migrations;

namespace Chamber.Services.Data.UnitOfWork
{
    public class UnitOfWorkManager : IUnitOfWorkManager
    {
        private bool _isDisposed;
        private readonly ChamberContext _context;

        public UnitOfWorkManager(IChamberContext context)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<ChamberContext, Configuration>(SiteConstants.Instance.ChamberContext));
            _context = context as ChamberContext;
        }

        /// <summary>
        /// Provides an instance of a unit of work. This wrapping in the manager
        /// class helps keep concerns separated
        /// </summary>
        /// <returns></returns>
        public IUnitOfWork NewUnitOfWork()
        {
            return new UnitOfWork(_context);
        }

        /// <summary>
        /// Make sure there are no open sessions.
        /// In the web app this will be called when the injected UnitOfWork manager
        /// is disposed at the end of a request.
        /// </summary>
        public void Dispose()
        {
            if (!_isDisposed)
            {
                _context.Dispose();
                _isDisposed = true;
            }
        }
    }
}


text:
package jp.upft.content_trigger.core;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;

import jp.upft.content_trigger.BuildConfig;
import jp.upft.content_trigger.ContentTriggerEntry;
import jp.upft.content_trigger.ContentTriggerEntry.TermParams;
import jp.upft.content_trigger.ObserveResult;
import jp.upft.location_observer.LocationObserver;
import jp.upft.location_observer.access_point_observer.AccessPointObserver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Toast;

import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Logger;
import com.google.android.gms.analytics.Tracker;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 通信や Alarm、トリガを監視するサービス
 */
public final class ContentTriggerService extends Service {

    /**
     * コールバックの Intent に設定される Action。
     *
     * @see android.content.Intent#setAction(String)
     * @see android.content.Intent#getAction()
     */
    public static final String ACTION_CONTENT_TRIGGER = "content_trigger_service.ACTION_TRIGGER";

    /**
     * コールバックの Intent に付加される検出結果情報のキー。
     *
     * @see android.content.Intent#putExtra(String, android.os.Parcelable)
     * @see android.content.Intent#getParcelableExtra(String)
     * @see jp.upft.location_observer.LocationObserver.ObserveResult
     */
    public static final String INTENT_EXTRA_TRIGGER = "content_trigger_service.extra_trigger";

    /**
     * 初期化時の Intent に付加される、KiiGroup の ID
     *
     * @see android.content.Intent#putExtra(String, String)
     * @see android.content.Intent#getStringExtra(String)
     */
    public static final String INTENT_EXTRA_GROUPID = "content_trigger_service.extra_groupid";

    // constants.
    private static final String INTENT_ACTION_ALARM = "content_trigger_service.action_alarm";
    private static final String INTENT_EXTRA_ALARM = "content_trigger_service.extra_alarm";
    private static final String ENTRIES_PREFERENCE_NAME = "jp.upft.content_trigger.core.ContentTriggerService#entries";
    private static final String KEY_ENTRIES = "entries";

    private final ConcurrentHashMap<String, ContentTriggerEntry> mEntries = new ConcurrentHashMap<>();
    private ContentTriggerObserver mContentTriggerObserver;
    private ContentTriggerAlarmManager mContentTriggerAlarmManager;
    private final IContentTriggerService.Stub mStub = new IContentTriggerService.Stub() {
        @Override
        public void queryQRString(String qrStr) throws RemoteException {
            ContentTriggerService.this.queryQRString(qrStr);
        }

        @Override
        public void setEnabled(String type, boolean enabled) throws RemoteException {
            ContentTriggerService.this.setEnabled(type, enabled);
        }

        @Override
        public void updateEntries(List<ContentTriggerEntry> entries) throws RemoteException {
            ContentTriggerService.this.updateEntries(entries);
        }
    };
    private BroadcastReceiver mBroadcastReceiver;

    // instance methods.
    private static List<ContentTriggerEntry> entriesFromSharedPreference(Context context) {
        int mode;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mode = Context.MODE_MULTI_PROCESS;
        } else {
            mode = Context.MODE_PRIVATE;
        }

        String json = context.getSharedPreferences(ENTRIES_PREFERENCE_NAME, mode).getString(
                KEY_ENTRIES, "");
        if (json.length() > 2) {
            return new Gson().fromJson(json, new TypeToken<ArrayList<ContentTriggerEntry>>() {
            }.getType());
        } else {
            return new ArrayList<>();
        }
    }

    private static Date nextStartDateTime(TermParams params) {
        return searchDateTime(params, true, true);
    }

    private static Date prevStartDateTime(TermParams params) {
        return searchDateTime(params, false, true);
    }

    private static Date nextEndDateTime(TermParams params) {
        return searchDateTime(params, true, false);
    }

    private static Date prevEndDateTime(TermParams params) {
        return searchDateTime(params, false, false);
    }

    private static Date searchDateTime(TermParams params, boolean inFuture, boolean isStartTime) {
        Date startDateTime = params.getStartDateTime();
        Date endDateTime = params.getEndDateTime();
        String startTime = params.getStartTime();
        String endTime = params.getEndTime();
        int dayOfMonth = params.getDayOfMonth();
        int dayOfWeekFlags = params.getDayOfWeekFlags();

        Calendar now = Calendar.getInstance();
        now.set(Calendar.MILLISECOND, 0);
        now.set(Calendar.SECOND, 0);
        Calendar startDate;
        Calendar endDate;

        if (startDateTime != null) {
            startDate = Calendar.getInstance();
            startDate.setTime(startDateTime);

            if (endDateTime != null) {
                endDate = Calendar.getInstance();
                endDate.setTime(endDateTime);

                if (isSplittedTerm(params)) {
                    startDate.set(Calendar.HOUR, 0);
                    startDate.set(Calendar.MINUTE, 0);
                    startDate.set(Calendar.SECOND, 0);
                    endDate.set(Calendar.HOUR, 23);
                    endDate.set(Calendar.MINUTE, 59);
                    endDate.set(Calendar.SECOND, 59);

                    DateConverter converter = new DateConverter();
                    Calendar queryCalendar = converter.timeToCalendar(now, isStartTime ? startTime
                            : endTime, inFuture);
                    if (queryCalendar == null) {
                        return null;
                    }

                    final int SEARCH_LIMIT = 1000; // 一定日数以上のサーチは行わない
                    for (int i = 0; i < SEARCH_LIMIT; i++) {
                        boolean isSoFar = inFuture ?
                                queryCalendar.after(endDate) :
                                queryCalendar.before(startDate);
                        if (isSoFar) {
                            return null;
                        }

                        if (!queryCalendar.after(endDate) && !queryCalendar.before(startDate)
                                && isEqualDayOfMonth(queryCalendar, dayOfMonth)
                                && isEqualDayOfWeek(queryCalendar, dayOfWeekFlags)) {
                            return queryCalendar.getTime(); // 全ての条件に合致した日時を返却
                        }

                        // 条件に合致しなかったので前の日
                        queryCalendar.add(Calendar.DATE, inFuture ? 1 : -1);
                    }

                    return null;

                } else {
                    Calendar tmpDate = isStartTime ? startDate : endDate;
                    boolean isAlreadyOver = inFuture ? now.before(tmpDate) : now.after(tmpDate);
                    if (isAlreadyOver) {
                        return tmpDate.getTime();
                    } else {
                        return null;
                    }
                }
            }
        }

        return null; // startDateTime は設定されていなければならない
    }

    private static boolean isSplittedTerm(TermParams params) {
        String startTime = params.getStartTime();
        String endTime = params.getEndTime();
        return startTime != null && startTime.length() > 0 && endTime != null
                && endTime.length() > 0;
    }

    private static boolean isEqualDayOfMonth(Calendar calendar, int dayOfMonth) {
        // dayOfMonth の設定がされていないか、条件をクリア
        return dayOfMonth == 0 || calendar.get(Calendar.DAY_OF_MONTH) == dayOfMonth;
    }

    private static boolean isEqualDayOfWeek(Calendar calendar, int dayOfWeekFlags) {
        int nowDayOfWeek = 1 << (calendar.get(Calendar.DAY_OF_WEEK) - 1);
        // 曜日の条件をクリア
        return (nowDayOfWeek & dayOfWeekFlags) != 0;
    }

    @Override
    public void onCreate() {
        mContentTriggerObserver = new ContentTriggerObserver(this, getClass());
        mContentTriggerAlarmManager = new ContentTriggerAlarmManager(this, getClass(),
                INTENT_ACTION_ALARM, INTENT_EXTRA_ALARM);
        loadEntriesPreference(this);
        if (BuildConfig.DEBUG) {
            Toast.makeText(this, "ContentTriggerサービス 起動", Toast.LENGTH_SHORT).show();
        }

        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                AccessPointObserver.postScanResultAvailableAction();
            }
        };

        registerReceiver(mBroadcastReceiver, new IntentFilter(
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

        if (BuildConfig.DEBUG) {
            //For develop.
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
            analytics.setLocalDispatchPeriod(0);
            analytics.getLogger().setLogLevel(Logger.LogLevel.VERBOSE);
            Tracker tracker = analytics.newTracker("UA-36307655-2");
            tracker.enableExceptionReporting(true);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            action:
            {
                List<LocationObserver.ObserveResult> observeResults = mContentTriggerObserver
                        .getObserveResult(intent);

                if (observeResults.size() > 0) {
                    synchronized (mEntries) {
                        for (LocationObserver.ObserveResult result : observeResults) {
                            ContentTriggerEntry entry = mEntries.get(result.getObserveEntry().get(
                                    LocationObserver.KEY_ENTRY_ID));
                            ObserveResult observeResult = new ObserveResult(result,
                                    entry.getMasterId(), entry.getTitle(), entry.getDescription());
                            sendBroadcast(observeResult);
                        }
                    }
                    break action;
                }

                if (intent.getAction() != null) {
                    switch (intent.getAction()) {
                        case Intent.ACTION_APPLICATION_RESTRICTIONS_CHANGED:
                        case Intent.ACTION_BOOT_COMPLETED:
                            break action;
                        case INTENT_ACTION_ALARM:
                            ContentTriggerAlarmManager.AlarmEntry alarmEntry = mContentTriggerAlarmManager.extractAlarmEntry(intent);
                            String entryId = alarmEntry.getEntryId();
                            switch (alarmEntry.getAlarmType()) {
                                case End: {
                                    mContentTriggerObserver.removeTriggers(Collections
                                            .singletonList(entryId));
                                    ContentTriggerEntry entry = mEntries.get(entryId);
                                    if (entry != null) {
                                        TermParams params = entry.getTermParams();
                                        Date nextEndTime = nextEndDateTime(params);
                                        if (nextEndTime != null) {
                                            mContentTriggerAlarmManager
                                                    .addAlarm(new ContentTriggerAlarmManager.AlarmEntry(
                                                            entryId,
                                                            ContentTriggerAlarmManager.AlarmEntry.AlarmType.End,
                                                            nextEndTime));
                                        }
                                    }
                                }
                                    break;
                                case Start: {
                                    mContentTriggerObserver.addTriggers(Collections
                                            .singletonList(mEntries
                                                    .get(entryId)));
                                    ContentTriggerEntry entry = mEntries.get(entryId);
                                    if (entry != null) {
                                        TermParams params = entry.getTermParams();
                                        Date nextStartTime = nextStartDateTime(params);
                                        if (nextStartTime != null) {
                                            mContentTriggerAlarmManager
                                                    .addAlarm(new ContentTriggerAlarmManager.AlarmEntry(
                                                            entryId,
                                                            ContentTriggerAlarmManager.AlarmEntry.AlarmType.Start,
                                                            nextStartTime));
                                        }
                                    }
                                }
                                    break;
                            }
                            break;
                    }
                }
            }
        }
        return START_STICKY;
    }

    // region Calculation for TermParams.

    @Override
    public IBinder onBind(Intent intent) {
        return mStub;
    }

    private void sendBroadcast(ObserveResult result) {
        Intent broadcastIntent = new Intent(ACTION_CONTENT_TRIGGER);
        broadcastIntent.putExtra(INTENT_EXTRA_TRIGGER, (Serializable) result);
        broadcastIntent.addCategory(getPackageName());
        sendBroadcast(broadcastIntent);
    }

    public void queryQRString(String qrStr) {
        mContentTriggerObserver.queryQRString(qrStr);
    }

    public void setEnabled(String type, boolean enabled) {
        mContentTriggerObserver.setEnabled(type, enabled);
    }

    public void updateEntries(List<ContentTriggerEntry> entries) {
        updateEntries(ContentTriggerService.this, entries);
    }

    private synchronized void updateEntries(Context context, List<ContentTriggerEntry> entries) {
        synchronized (mEntries) {
            mEntries.clear();
            for (ContentTriggerEntry entry : entries) {
                mEntries.put(entry.getEntry().get(LocationObserver.KEY_ENTRY_ID), entry);
            }
        }

        // Reset entries.
        mContentTriggerAlarmManager.removeAllAlarm();
        mContentTriggerObserver.removeAllTriggersAndWaitStop();

        // Update preferences.
        saveEntriesPreference(context, entries);

        for (ContentTriggerEntry entry : entries) {
            String entryId = entry.getEntry().get(LocationObserver.KEY_ENTRY_ID);

            TermParams params = entry.getTermParams();
            Date nextStartDateTime = nextStartDateTime(params);
            Date nextEndDateTime = nextEndDateTime(params);
            Date prevStartDateTime = prevStartDateTime(params);
            Date prevEndDateTime = prevEndDateTime(params);

            if (prevStartDateTime != null) {
                if (prevEndDateTime != null && prevEndDateTime.after(prevStartDateTime)) {
                    // 1つ前のエントリは完了している
                    if (nextStartDateTime != null) {
                        // 次のエントリが存在する
                        mContentTriggerAlarmManager
                                .addAlarm(new ContentTriggerAlarmManager.AlarmEntry(entryId,
                                        ContentTriggerAlarmManager.AlarmEntry.AlarmType.Start,
                                        nextStartDateTime));
                        if (nextEndDateTime != null) {
                            mContentTriggerAlarmManager
                                    .addAlarm(new ContentTriggerAlarmManager.AlarmEntry(entryId,
                                            ContentTriggerAlarmManager.AlarmEntry.AlarmType.End,
                                            nextEndDateTime));
                        }
                    }
                } else {
                    // 1つ前のエントリが続いている
                    mContentTriggerAlarmManager.addAlarm(new ContentTriggerAlarmManager.AlarmEntry(
                            entryId, ContentTriggerAlarmManager.AlarmEntry.AlarmType.Start,
                            prevStartDateTime));
                    if (nextEndDateTime != null) {
                        mContentTriggerAlarmManager
                                .addAlarm(new ContentTriggerAlarmManager.AlarmEntry(entryId,
                                        ContentTriggerAlarmManager.AlarmEntry.AlarmType.End,
                                        nextEndDateTime));
                    }
                }
            } else {
                // まだ始まっていない
                if (nextStartDateTime != null) {
                    // 次のエントリが存在する
                    mContentTriggerAlarmManager.addAlarm(new ContentTriggerAlarmManager.AlarmEntry(
                            entryId, ContentTriggerAlarmManager.AlarmEntry.AlarmType.Start,
                            nextStartDateTime));
                    if (nextEndDateTime != null) {
                        mContentTriggerAlarmManager
                                .addAlarm(new ContentTriggerAlarmManager.AlarmEntry(entryId,
                                        ContentTriggerAlarmManager.AlarmEntry.AlarmType.End,
                                        nextEndDateTime));
                    }
                }
            }
        }
    }

    private void saveEntriesPreference(Context context, List<ContentTriggerEntry> entries) {
        int mode;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mode = Context.MODE_MULTI_PROCESS;
        } else {
            mode = Context.MODE_PRIVATE;
        }

        context.getSharedPreferences(ENTRIES_PREFERENCE_NAME, mode).edit()
                .putString(KEY_ENTRIES, new Gson().toJson(entries)).commit();
    }

    private void loadEntriesPreference(Context context) {
        updateEntries(context, entriesFromSharedPreference(context));
    }

    private static class DateConverter {
        Calendar timeToCalendar(Calendar baseDate, String str, boolean inFuture) {
            try {
                Date date = new SimpleDateFormat("kk:mm", Locale.JAPAN).parse(str);

                Calendar parsedDateCalendar = Calendar.getInstance();
                parsedDateCalendar.setTime(date);

                Calendar todayCalendar = (Calendar) baseDate.clone();
                todayCalendar.set(Calendar.HOUR_OF_DAY,
                        parsedDateCalendar.get(Calendar.HOUR_OF_DAY));
                todayCalendar.set(Calendar.MINUTE, parsedDateCalendar.get(Calendar.MINUTE));
                todayCalendar.set(Calendar.SECOND, parsedDateCalendar.get(Calendar.SECOND));

                int aDay = 0;
                if (inFuture && baseDate.after(todayCalendar)) {
                    aDay = 1;
                } else if (!inFuture && baseDate.before(todayCalendar)) {
                    aDay = -1;
                }
                if (aDay != 0) {
                    todayCalendar.add(Calendar.DATE, aDay);
                }

                return todayCalendar;
            } catch (ParseException e) {
                if (BuildConfig.DEBUG) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }
    // end region
}


text:
<#
    .SYNOPSIS
        If the group named GroupName1 does not exist, creates a group named GroupName1 and adds the
        users with the usernames Username1 and Username2 to the group.

        If the group named GroupName1 already exists, removes any users that do not have the
        usernames Username1 or Username2 from the group and adds the users that have the usernames
        Username1 and Username2 to the group.
#>
Configuration Sample_xGroup_SetMembers
{
    [CmdletBinding()]
    param ()

    Import-DscResource -ModuleName 'xPSDesiredStateConfiguration'

    xGroup Group1
    {
        GroupName = 'GroupName1'
        Ensure = 'Present'
        Members = @( 'Username1', 'Username2' )
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.client;

import io.airlift.json.JsonCodec;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

import javax.annotation.Nullable;

import java.io.IOException;
import java.io.UncheckedIOException;

import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.net.HttpHeaders.LOCATION;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

public final class JsonResponse<T>
{
    private final int statusCode;
    private final String statusMessage;
    private final Headers headers;
    private final String responseBody;
    private final boolean hasValue;
    private final T value;
    private final IllegalArgumentException exception;

    private JsonResponse(int statusCode, String statusMessage, Headers headers, String responseBody)
    {
        this.statusCode = statusCode;
        this.statusMessage = statusMessage;
        this.headers = requireNonNull(headers, "headers is null");
        this.responseBody = requireNonNull(responseBody, "responseBody is null");

        this.hasValue = false;
        this.value = null;
        this.exception = null;
    }

    private JsonResponse(int statusCode, String statusMessage, Headers headers, String responseBody, JsonCodec<T> jsonCodec)
    {
        this.statusCode = statusCode;
        this.statusMessage = statusMessage;
        this.headers = requireNonNull(headers, "headers is null");
        this.responseBody = requireNonNull(responseBody, "responseBody is null");

        T value = null;
        IllegalArgumentException exception = null;
        try {
            value = jsonCodec.fromJson(responseBody);
        }
        catch (IllegalArgumentException e) {
            exception = new IllegalArgumentException(format("Unable to create %s from JSON response:\n[%s]", jsonCodec.getType(), responseBody), e);
        }
        this.hasValue = (exception == null);
        this.value = value;
        this.exception = exception;
    }

    public int getStatusCode()
    {
        return statusCode;
    }

    public String getStatusMessage()
    {
        return statusMessage;
    }

    public Headers getHeaders()
    {
        return headers;
    }

    public boolean hasValue()
    {
        return hasValue;
    }

    public T getValue()
    {
        if (!hasValue) {
            throw new IllegalStateException("Response does not contain a JSON value", exception);
        }
        return value;
    }

    public String getResponseBody()
    {
        return responseBody;
    }

    @Nullable
    public IllegalArgumentException getException()
    {
        return exception;
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .add("statusCode", statusCode)
                .add("statusMessage", statusMessage)
                .add("headers", headers.toMultimap())
                .add("hasValue", hasValue)
                .add("value", value)
                .omitNullValues()
                .toString();
    }

    public static <T> JsonResponse<T> execute(JsonCodec<T> codec, OkHttpClient client, Request request)
    {
        try (Response response = client.newCall(request).execute()) {
            // TODO: fix in OkHttp: https://github.com/square/okhttp/issues/3111
            if ((response.code() == 307) || (response.code() == 308)) {
                String location = response.header(LOCATION);
                if (location != null) {
                    request = request.newBuilder().url(location).build();
                    return execute(codec, client, request);
                }
            }

            ResponseBody responseBody = requireNonNull(response.body());
            String body = responseBody.string();
            if (isJson(responseBody.contentType())) {
                return new JsonResponse<>(response.code(), response.message(), response.headers(), body, codec);
            }
            return new JsonResponse<>(response.code(), response.message(), response.headers(), body);
        }
        catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static boolean isJson(MediaType type)
    {
        return (type != null) && "application".equals(type.type()) && "json".equals(type.subtype());
    }
}


text:
#ifndef _SAMPLE_DIR_MANAGER_H
#define	_SAMPLE_DIR_MANAGER_H

namespace SampleFramework
{
	class SampleDirManager
	{
	public:
		SampleDirManager(const char* relativePathRoot, bool isReadOnly = true, int maxRecursion = 20);

	public:
		const char*	getPathRoot() const	{ return mPathRoot; }
		const char*	getFilePath(const char* relativeFilePath, char* pathBuffer, bool testFileValidity = true);

	private:
		char	mPathRoot[256];
		bool	mIsReadOnly;
	};
}

#endif


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Shell;

using BuildVision.Common;
using BuildVision.UI.Settings.Models;
using BuildVision.UI.Models;
using BuildVision.UI.Settings.Models.BuildProgress;

namespace BuildVision.UI.ViewModels
{
    public class BuildProgressViewModel : BindableBase
    {
        private readonly ControlSettings _settings;

        private CancellationTokenSource _resetTaskBarInfoCts;

        private int _projectsCount;

        private double _incProgressValue;

        private double _actionProgressValue;

        private bool _actionProgressIsMarquee;

        private bool _actionProgressIsError;

        private readonly Lazy<TaskbarItemInfo> _taskbarItemInfo = new Lazy<TaskbarItemInfo>(() =>
        {
            var window = Application.Current.MainWindow;
            return window.TaskbarItemInfo ?? (window.TaskbarItemInfo = new TaskbarItemInfo());
        });
        private TaskbarItemInfo TaskbarItemInfo => _taskbarItemInfo.Value;

        private int _currentQueuePosOfBuildingProject;
        public int CurrentQueuePosOfBuildingProject => _currentQueuePosOfBuildingProject;

        private bool _actionProgressIsVisible;
        public bool ActionProgressIsVisible
        {
            get => _actionProgressIsVisible;
            set => SetProperty(ref _actionProgressIsVisible, value);
        }

        private bool _actionProgressIsPaused;
        public bool ActionProgressIsPaused
        {
            get => _actionProgressIsPaused;
            set => SetProperty(ref _actionProgressIsPaused, value);
        }

        public BuildProgressViewModel(ControlSettings settings)
        {
            _settings = settings;
        }

        private void UpdateTaskBarInfo()
        {
            if (!_settings.GeneralSettings.BuildProgressSettings.TaskBarProgressEnabled)
                return;

            TaskbarItemProgressState state;

            if (!_actionProgressIsVisible)
                state = TaskbarItemProgressState.None;
            else if (_actionProgressIsPaused)
                state = TaskbarItemProgressState.Paused;
            else if (_actionProgressIsMarquee)
                state = TaskbarItemProgressState.Indeterminate;
            else if (_actionProgressIsError)
                state = TaskbarItemProgressState.Error;
            else
                state = TaskbarItemProgressState.Normal;

            TaskbarItemInfo.ProgressState = state;
            TaskbarItemInfo.ProgressValue = _actionProgressValue;
        }

        public void ResetTaskBarInfo(bool ifTaskBarProgressEnabled = true)
        {
            if (_taskbarItemInfo.IsValueCreated
                && _settings.GeneralSettings.BuildProgressSettings.TaskBarProgressEnabled == ifTaskBarProgressEnabled)
            {
                TaskbarItemInfo.ProgressState = TaskbarItemProgressState.None;
                TaskbarItemInfo.ProgressValue = 0;
            }
        }

        public void OnBuildBegin(int projectsCount)
        {
            if (_resetTaskBarInfoCts != null)
                _resetTaskBarInfoCts.Cancel();

            if (projectsCount > 0)
            {
                _projectsCount = projectsCount;
                _incProgressValue = 1.0 / (projectsCount * 2.0);
            }
            else
            {
                _projectsCount = 0;
                _incProgressValue = 0;
            }

            _currentQueuePosOfBuildingProject = 0;
            _actionProgressValue = 0;
            _actionProgressIsError = false;
            _actionProgressIsMarquee = true;
            ActionProgressIsPaused = false;
            ActionProgressIsVisible = true;

            UpdateTaskBarInfo();
        }

        public void OnBuildProjectBegin()
        {
            if (_projectsCount > 0)
            {
                _actionProgressIsMarquee = false;
                _actionProgressValue += _incProgressValue;
            }
            else
            {
                _actionProgressIsMarquee = true;
            }

            _currentQueuePosOfBuildingProject += 1;
            UpdateTaskBarInfo();
        }

        public void OnBuildProjectDone(bool success)
        {
            if (!success)
                _actionProgressIsError = true;

            if (_projectsCount > 0)
            {
                _actionProgressIsMarquee = false;
                _actionProgressValue += _incProgressValue;
            }
            else
            {
                _actionProgressIsMarquee = true;
            }

            UpdateTaskBarInfo();
        }

        public void OnBuildDone()
        {
            _actionProgressValue = 1;
            _actionProgressIsMarquee = false;
            UpdateTaskBarInfo();

            ActionProgressIsVisible = false;
            _actionProgressValue = 0;

            ResetTaskBarInfoOnBuildDone();
        }

        private void ResetTaskBarInfoOnBuildDone()
        {
            BuildProgressSettings buildProgressSettings = _settings.GeneralSettings.BuildProgressSettings;
            if (!buildProgressSettings.TaskBarProgressEnabled)
                return;

            switch (buildProgressSettings.ResetTaskBarProgressAfterBuildDone)
            {
                case ResetTaskBarItemInfoCondition.Never:
                    break;

                case ResetTaskBarItemInfoCondition.Immediately:
                    ResetTaskBarInfo();
                    break;

                case ResetTaskBarItemInfoCondition.AfterDelay:
                    {
                        int delay = buildProgressSettings.ResetTaskBarProgressDelay;
                        if (delay > 0)
                        {
                            _resetTaskBarInfoCts = new CancellationTokenSource();
                            var resetTask = new Task(() => Thread.Sleep(delay), _resetTaskBarInfoCts.Token);
                            resetTask.ContinueWith((tsk, cancelToken) =>
                                {
                                    if (!((CancellationToken)cancelToken).IsCancellationRequested)
                                        ResetTaskBarInfo();
                                },
                                _resetTaskBarInfoCts.Token,
                                TaskScheduler.FromCurrentSynchronizationContext());
                            resetTask.Start();
                        }
                        else
                        {
                            ResetTaskBarInfo();
                        }
                    }
                    break;

                case ResetTaskBarItemInfoCondition.ByMouseClick:
                    Window window = Application.Current.MainWindow;
                    window.PreviewMouseDown += OnMainWindowTouched;
                    window.LocationChanged += OnMainWindowTouched;
                    window.SizeChanged += OnMainWindowTouched;
                    break;

                default:
                    throw new ArgumentOutOfRangeException(nameof(buildProgressSettings.ResetTaskBarProgressAfterBuildDone));
            }
        }

        private void OnMainWindowTouched(object sender, EventArgs e)
        {
            ResetTaskBarInfo();

            var window = (Window)sender;
            window.PreviewMouseDown -= OnMainWindowTouched;
            window.LocationChanged -= OnMainWindowTouched;
            window.SizeChanged -= OnMainWindowTouched;
        }

        public void OnBuildCancelled()
        {
            ActionProgressIsPaused = true;
            UpdateTaskBarInfo();
        }
    }
}


text:
package seava.j4e.commons.descriptor;

import seava.j4e.api.descriptor.IAsgnContext;

public class AsgnContext implements IAsgnContext {

	protected String leftTable;
	protected String leftPkField = "id";

	protected String rightTable;
	protected String rightObjectIdField;
	protected String rightItemIdField;

	public String getLeftTable() {
		return leftTable;
	}

	public void setLeftTable(String leftTable) {
		this.leftTable = leftTable;
	}

	public String getLeftPkField() {
		return leftPkField;
	}

	public void setLeftPkField(String leftPkField) {
		this.leftPkField = leftPkField;
	}

	public String getRightTable() {
		return rightTable;
	}

	public void setRightTable(String rightTable) {
		this.rightTable = rightTable;
	}

	public String getRightObjectIdField() {
		return rightObjectIdField;
	}

	public void setRightObjectIdField(String rightObjectIdField) {
		this.rightObjectIdField = rightObjectIdField;
	}

	public String getRightItemIdField() {
		return rightItemIdField;
	}

	public void setRightItemIdField(String rightItemIdField) {
		this.rightItemIdField = rightItemIdField;
	}

}


text:
package com.signavio.platform.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class FileUtil {

	public static StringBuffer readFile(File file) throws IOException {
		FileInputStream fin =  new FileInputStream(file);
		StringBuffer result = new StringBuffer();

		String thisLine = "";
		BufferedReader myInput = new BufferedReader(new InputStreamReader(fin));

		while ((thisLine = myInput.readLine()) != null) {
			result.append(thisLine);
			result.append("\n");
		}

		myInput.close();
		fin.close();

		return result;
	}
}


text:
/* =================================================================================================

(c - MIT) T.W.J. de Geus (Tom) | tom@geus.me | www.geus.me | github.com/tdegeus/cppmat

================================================================================================= */

#ifndef CPPMAT_VAR_DIAGONAL_MATRIX_H
#define CPPMAT_VAR_DIAGONAL_MATRIX_H

// -------------------------------------------------------------------------------------------------

#include "cppmat.h"

// -------------------------------------------------------------------------------------------------

namespace cppmat {
namespace diagonal {

// =================================================================================================
// cppmat::diagonal::matrix
// =================================================================================================

template<typename X>
class matrix
{
protected:

  size_t              mSize=0;          // total size == data.size()
  static const size_t mRank=2;          // rank (number of axes)
  size_t              N=0;              // number of rows/columns
  std::vector<X>      mData;            // data container
  X                   mZero[1];         // pointer to a zero entry
  bool                mPeriodic=false;  // if true: disable bounds-check where possible

public:

  // constructor: default
  matrix();

  // constructor: allocate, don't initialize
  matrix(size_t m, size_t n);

  // constructor: copy from own class (with different type)
  template<typename U, typename=typename std::enable_if<std::is_convertible<U,X>::value>::type>
  matrix(const cppmat::diagonal::matrix<U> &A);

  // constructor: copy from fixed size
  template<size_t m, size_t n> matrix(const cppmat::tiny::diagonal::matrix<X,m,n> &A);

  // constructor: copy from view
  template<size_t m, size_t n> matrix(const cppmat::view::diagonal::matrix<X,m,n> &A);

  // named constructor: initialize
  static matrix<X> Random  (size_t m, size_t n, X lower=(X)0, X upper=(X)1);
  static matrix<X> Arange  (size_t m, size_t n);
  static matrix<X> Zero    (size_t m, size_t n);
  static matrix<X> Ones    (size_t m, size_t n);
  static matrix<X> Constant(size_t m, size_t n, X D);
  static matrix<X> Copy    (size_t m, size_t n, const std::vector<X> &D);

  // named constructor: copy
  template<typename Itr> static matrix<X> Copy     (size_t m, size_t n, Itr first);
  template<typename Itr> static matrix<X> Copy     (size_t m, size_t n, Itr first, Itr last);
  template<typename Itr> static matrix<X> CopyDense(size_t m, size_t n, Itr first);
  template<typename Itr> static matrix<X> CopyDense(size_t m, size_t n, Itr first, Itr last);

  // return plain storage as vector
  template<typename U, typename=typename std::enable_if<std::is_convertible<U,X>::value>::type>
  operator std::vector<U> () const;

  // resize
  void resize(size_t m, size_t n);
  void resize(size_t m, size_t n, const X &D);

  // modify bounds-checks
  void setPeriodic(bool periodic);

  // get dimensions
  size_t size() const;
  size_t rank() const;
  size_t shape(int    i) const;
  size_t shape(size_t i) const;
  std::vector<size_t> shape() const;

  // get using a different return type
  template<typename U> U size() const;
  template<typename U> U rank() const;
  template<typename U> U shape(int    i) const;
  template<typename U> U shape(size_t i) const;
  template<typename U> std::vector<U> shape() const;

  // index operators: access plain storage
  X&       operator[](size_t i);
  const X& operator[](size_t i) const;

  // index operators: access using matrix-indices
  X&       operator()(int a, int b);
  const X& operator()(int a, int b) const;

  // index operators: access using matrix-indices
  template<typename T, typename=typename std::enable_if<std::is_unsigned<T>::value,void>::type>
  X&       operator()(T a, T b);

  template<typename T, typename=typename std::enable_if<std::is_unsigned<T>::value,void>::type>
  const X& operator()(T a, T b) const;

  // index operators: matrix-indices -> plain storage (a,b -> i)
  size_t compress(int a, int b) const;

  // index operators: matrix-indices -> plain storage (a,b -> i)
  template<typename T, typename=typename std::enable_if<std::is_unsigned<T>::value,void>::type>
  size_t compress(T a, T b) const;

  // index operators: plain storage -> matrix-indices (i -> a,b)
  std::vector<size_t> decompress(size_t i) const;

  // get index of the midpoint (along a certain axis)
  std::vector<size_t> midpoint() const;
  size_t              midpoint(size_t axis) const;

  // pointer to data
  X*       data();
  const X* data() const;

  // iterator to first and last entry
  auto begin();
  auto begin() const;
  auto end();
  auto end() const;

  // iterator to specific entry: access plain storage
  auto index(size_t i);
  auto index(size_t i) const;

  // iterator to specific entry: access using matrix-indices
  auto item(int a, int b);
  auto item(int a, int b) const;

  // iterator to specific entry: access using matrix-indices
  template<typename T, typename=typename std::enable_if<std::is_unsigned<T>::value,void>::type>
  auto item(T a, T b);

  template<typename T, typename=typename std::enable_if<std::is_unsigned<T>::value,void>::type>
  auto item(T a, T b) const;

  // initialization
  void setRandom(X lower=(X)0, X upper=(X)1);
  void setArange();
  void setZero();
  void setOnes();
  void setConstant(X D);
  template<typename Iterator> void setCopy     (Iterator first);
  template<typename Iterator> void setCopy     (Iterator first, Iterator last);
  template<typename Iterator> void setCopyDense(Iterator first);
  template<typename Iterator> void setCopyDense(Iterator first, Iterator last);

  // copy to target
  template<typename Iterator> void copyTo     (Iterator first) const;
  template<typename Iterator> void copyTo     (Iterator first, Iterator last) const;
  template<typename Iterator> void copyToDense(Iterator first) const;
  template<typename Iterator> void copyToDense(Iterator first, Iterator last) const;

  // check in an index in within the matrix bound:
  // ( a >= 0 and a < shape[0] ) or ( periodic )
  template<typename T> bool inBounds(T a) const;
  template<typename T> bool inBounds(T a, T b) const;

  // sign change
  matrix<X> operator- () const;
  matrix<X> operator+ () const;

  // arithmetic operators
  matrix<X>& operator*= (const cppmat::diagonal ::matrix<X> &B);
  matrix<X>& operator+= (const cppmat::diagonal ::matrix<X> &B);
  matrix<X>& operator-= (const cppmat::diagonal ::matrix<X> &B);
  matrix<X>& operator*= (X B);
  matrix<X>& operator/= (X B);

  // extra arithmetic operators
  matrix<X>& operator*= (const cppmat::           matrix<X> &B);
  matrix<X>& operator/= (const cppmat::           matrix<X> &B);
  matrix<X>& operator*= (const cppmat::symmetric::matrix<X> &B);
  matrix<X>& operator/= (const cppmat::symmetric::matrix<X> &B);

  // absolute value
  matrix<X> abs() const;

  // norm (sum of absolute values)
  X norm() const;

  // return the indices that would sort the matrix
  matrix<size_t> argsort(bool ascending=true) const;

  // location of the minimum/maximum: plain storage (use decompress to convert to indices)
  size_t argmin() const;
  size_t argmax() const;

  // minimum
  X min() const;

  // maximum
  X max() const;

  // sum
  X sum() const;

  // mean
  double mean() const;

  // weighted average
  double average(const matrix<X> &weights, bool norm=true) const;

  // return matrix of booleans, based on condition
  matrix<int> equal        (const        X  &D) const;
  matrix<int> not_equal    (const        X  &D) const;
  matrix<int> greater      (const        X  &D) const;
  matrix<int> greater_equal(const        X  &D) const;
  matrix<int> less         (const        X  &D) const;
  matrix<int> less_equal   (const        X  &D) const;
  matrix<int> equal        (const matrix<X> &D) const;
  matrix<int> not_equal    (const matrix<X> &D) const;
  matrix<int> greater      (const matrix<X> &D) const;
  matrix<int> greater_equal(const matrix<X> &D) const;
  matrix<int> less         (const matrix<X> &D) const;
  matrix<int> less_equal   (const matrix<X> &D) const;

  // find the plain storage indices of all non-zero entries
  std::vector<size_t> where() const;
  size_t              where(int    index) const;
  size_t              where(size_t index) const;

};

// equality operators
template<typename X> bool operator!= (const matrix<X> &A, const matrix<X> &B);
template<typename X> bool operator== (const matrix<X> &A, const matrix<X> &B);

// external arithmetic operators (cppmat::diagonal)
template<typename X> matrix<X> operator* (const matrix<X> &A, const matrix<X> &B);
template<typename X> matrix<X> operator+ (const matrix<X> &A, const matrix<X> &B);
template<typename X> matrix<X> operator- (const matrix<X> &A, const matrix<X> &B);
template<typename X> matrix<X> operator* (const matrix<X> &A, const        X  &B);
template<typename X> matrix<X> operator/ (const matrix<X> &A, const        X  &B);
template<typename X> matrix<X> operator* (const        X  &A, const matrix<X> &B);

// print operator
template<typename X> std::ostream& operator<<(std::ostream& out, const matrix<X>& src);

// =================================================================================================

}} // namespace ...

// -------------------------------------------------------------------------------------------------

#endif


text:
#include <node.h>
#include <windows.h>

namespace win {
	using v8::Exception;
	using v8::FunctionCallbackInfo;
	using v8::Isolate;
	using v8::Local;
	using v8::Object;
	using v8::String;
	using v8::Value;

	void _keybd_event(const FunctionCallbackInfo<Value>& args) {
		Isolate* isolate = args.GetIsolate();

		// Check the number of arguments passed.
		if (args.Length() < 4) {
			// Throw an Error that is passed back to JavaScript
			isolate->ThrowException(Exception::TypeError(
				String::NewFromUtf8(isolate, "Wrong number of arguments. Should be 4.")));
			return;
		}

		// Check the argument types
		if (!args[0]->IsUint32() || !args[1]->IsUint32() || !args[2]->IsUint32() || !args[3]->IsUint32()) {
			isolate->ThrowException(Exception::TypeError(
				String::NewFromUtf8(isolate, "Wrong arguments")));
			return;
		}
		//A virtual - key code.The code must be a value in the range 1 to 254. For a complete list, see Virtual Key Codes.
		BYTE bVk = args[0]->Uint32Value();
		//A hardware scan code for the key.
		BYTE bScan = args[1]->Uint32Value();
		//Controls various aspects of function operation.This parameter can be one or more of the following values.
		DWORD dwFlags = args[2]->Uint32Value();
		//An additional value associated with the key stroke.
		ULONG_PTR dwExtraInfo = args[2]->Uint32Value();

		keybd_event(bVk, bScan, dwFlags, dwExtraInfo);
	}

	void init(Local<Object> exports) {
		NODE_SET_METHOD(exports, "keybd_event", _keybd_event);
	}

	NODE_MODULE(addon, init)

}  // namespace win


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.damienfremont.codingame</groupId>
	<artifactId>codingame-training-medium-don_t_panic_episode_1</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<java.version>8</java.version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>org.assertj</groupId>
			<artifactId>assertj-core</artifactId>
			<version>3.6.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.${java.version}</source>
					<target>1.${java.version}</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
var fs = require("fs");
var path = require("path");

/**
 * @type {import('../../lib/interfaces').DockerLanguageDef}
 */
module.exports = {
  setup: function (work_dir, file_content, cb) {
    var filePath = path.resolve(work_dir, 'main.coffee');
    fs.writeFileSync(filePath, file_content);
    cb(filePath);
  },
  getExecuteArgs: function (file_path) {
    return {
      path: 'coffee',
      args: [file_path],
      opts: {}
    }
  }
}


text:
'use strict';
angular.module('ngQuantum.pageable.results')
.run(['$templateCache', function ($templateCache) {
    $templateCache.put('pageable/pageableResults.tpl.html',
    '
'
        +'
'
            + ' : '
            + ' :  '
        +'
'
        + ' :  '
    + '
'
   );
}])


text:
apt-get -y install gcc make;
apt-get -y purge xauth;
apt-get -y autoremove;


text:
http://christopher5106.github.io/mobile/2015/04/09/create-mobile-app-with-html-css-cordova.html

## Preferred Cordova Plugins ##

https://github.com/EddyVerbruggen/Custom-URL-scheme

```
cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=myfleet
```

## Obtain iOS Development certificate ##

- Go to: https://developer.apple.com/account/
- Create/Verify if needed
- Once logged in, go to the bottom "Join the Apple Developer Program"
- Redirected to: https://developer.apple.com/programs/  click "Enroll"
- https://developer.apple.com/programs/enroll/  "Start Your Enrollment"

## Documentation/Guides ##

Maintaining Your Signing Identities and Certificates
https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/MaintainingCertificates/MaintainingCertificates.html

Hiding Status Bar
https://github.com/apache/cordova-plugin-statusbar#hiding-at-startup

## Install App from Web App ##

```html
<a href="itms-services://?action=download-manifest&url=https://path.to.host/manifest.plist">Install the App!</a>
```

*plist file contents*
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>https://path.to.host/AppFileName.IPA</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>com.domain.myappname</string>
                <key>bundle-version</key>
                <string>0.1</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>My App Title</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>
```

Verify/Trust the developer of the app:
```
Settings -> General -> Device Management
```

### Hiding the Status Bar ###

```xml
<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
```

### Create Downloadable/Install App (.ipa) ###

1. Build (cmd+B)
2. Product > Archive > Export...

## Troubleshooting ##

- Xcode does not support opening folders without a project or workspace.

Solution: Select the folder with the .xproj file in it.