text:
var clip = require('../');
var app = new clip();

app.config('.appconf',{
  flags: ['c', 'conf']
});
app.use(function(req,res,next){
  if(req.config.get('v') || req.config.get('verbose')) {
    req.verbose = true;
  }
  if(req.config.get('s') || req.config.get('silent')) {
    req.silent = true;
    res.remove(res.transports.Console);
  }
  if(req.verbose) {
    res.info('Using config file '+req.config.store.file);
  }
  next();
});

app.usage(function usage(req,res) {
  res.info('')
  res.info('app')
  res.info('  example CLI app for configuration files.')
  res.info('  Please refer to documentation of commands using `-h` or `--help`.')
  res.info('')
  res.info('commands')
  res.info('  app config')
  res.info('')
})

app.usage('/config',function config(req,res) {
  res.info('')
  res.info('app config')
  res.info('  Actions related to the app configuration file.')
  res.info('')
  res.info('notes')
  res.info('  The configuration will be found recursively up the file system.')
  res.info('  If no configuration file is found the HOME folder will be used.')
  res.info('  A default configuration file will be created if none exist.')
  res.info('')
  res.info('commands')
  res.info('  app config get' + ' <id>')
  res.info('  app config set' + ' <id> <value>')
  res.info('')
  res.info('options')
  res.info('  -c --conf [.appconf]     The file to use as our configuration')
  res.info('')
})

app.cli('/config/get/:id',function configGet(req,res) {
  res.info(req.params.id + ' = ' + (''+req.config.get(req.params.id)));
});
app.usage(['/config/get','/config/get/:id'],function configGetUsage(req,res) {
  res.help('')
  res.help('app config get' + ' <id>')
  res.help('  Gets the value of a property in the app configuration')
  res.help('  See `app config -h` for more details')
  res.help('')
  res.help('params')
  res.help('  id - nconf compatible name of the property')
  res.help('')
  if(!req.params.id) res.error('missing id');
});

app.cli('/config/set/:id/:value',function configSet(req,res) {
  req.config.set(req.params.id,req.params.value);
  req.config.save();
});
app.usage(['/config/set','/config/set/:id','/config/set/:id/:value'],function configSetUsage(req,res) {
  res.help('')
  res.help('app config set' + ' <id> <value>')
  res.help('  Sets the value of a property in the app configuration')
  res.help('  See `app config -h` for more details')
  res.help('')
  res.help('params')
  res.help('  id - nconf compatible name of the property')
  res.help('  value - json compatible value of the property')
  if(!req.params.id) res.error('Missing id');
  if(!req.params.value) res.error('Missing value');
});

if(require.main) {
  app.run();
}
module.exports = app;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Tricholoma subluteum Peck

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
local sys = require "luci.sys"
local util = require "luci.util"
local fs = require "nixio.fs"
local dispatcher = require "luci.dispatcher"
local i18n = require "luci.i18n"
local uci = require("luci.model.uci").cursor()

local packageName = "https-dns-proxy"
local providers_dir = "/usr/lib/lua/luci/" .. packageName .. "/providers/"
local helperText = ""

function create_helper_text()
	local initText = "
" .. translate("For more information on different options check") .. " "
	for filename in fs.dir(providers_dir) do
		local p_func = loadfile(providers_dir .. filename)
		setfenv(p_func, { _ = i18n.translate })
		local p = p_func()
		if p.help_link then
			local url, domain
			url = p.help_link
			domain = p.help_link_text or url:match('^%w+://([^/]+)')
			if not helperText:find(domain) then
				if helperText == "" then
					helperText = initText
				else
					helperText = helperText .. ", "
				end
				helperText = helperText .. [[]] .. domain .. [[]]
			end
		end
	end
	if helperText ~= "" then
		local a = helperText:gsub('(.*),%s.*$', '%1')
		helperText = a .. " " .. translate("and") .. helperText:sub(#a + 2) .. "."
	end
end

function get_provider_name(value)
	for filename in fs.dir(providers_dir) do
		local p_func = loadfile(providers_dir .. filename)
		setfenv(p_func, { _ = i18n.translate })
		local p = p_func()
		value = value:gsub('[%p%c%s]', '')
		p.url_match = p.resolver_url:gsub('[%p%c%s]', '')
		if value:match(p.url_match) then
			return p.label
		end
	end
	return translate("Unknown Provider")
end

local packageStatus, packageStatusCode
local ubusStatus = util.ubus("service", "list", { name = packageName })
local packageVersion = tostring(util.trim(sys.exec("opkg list-installed " .. packageName .. " | awk '{print $3}'"))) or ""

if packageVersion == "" then
	packageStatusCode = -1
	packageStatus = translatef("%s is not installed or not found", packageName)
else
	if not ubusStatus or not ubusStatus[packageName] then
		packageStatusCode = 0
		packageStatus = translate("Stopped")
		if not sys.init.enabled(packageName) then
			packageStatus = packageStatus .. " (" .. translate("disabled") .. ")"
		end
	else
		packageStatusCode, packageStatus = 1, ""
		for n = 1,1000 do
			if ubusStatus and ubusStatus[packageName] and
				 ubusStatus[packageName]["instances"] and
				 ubusStatus[packageName]["instances"]["instance" .. n] and
				 ubusStatus[packageName]["instances"]["instance" .. n]["running"] then
				local value, k, v, url, url_flag, la, la_flag, lp, lp_flag
				for k, v in pairs(ubusStatus[packageName]["instances"]["instance" .. n]["command"]) do
					if la_flag then la, la_flag = v, false end
					if lp_flag then lp, lp_flag = v, false end
					if url_flag then url, url_flag = v, false end
					if v == "-a" then la_flag = true end
					if v == "-p" then lp_flag = true end
					if v == "-r" then url_flag = true end
				end
				la = la or "127.0.0.1"
				lp = lp or n + 5053
				packageStatus = packageStatus .. translatef("Running: %s DoH at %s:%s", get_provider_name(url), la, lp) .. "\n"
			else
				break
			end
		end
	end
end

m = Map("https-dns-proxy", translate("DNS Over HTTPS Proxy Settings"))

h = m:section(TypedSection, "_dummy", translatef("Service Status [%s %s]", packageName, packageVersion))
h.template = "cbi/nullsection"
ss = h:option(DummyValue, "_dummy", translate("Service Status"))
if packageStatusCode == -1 then
	ss.template = packageName .. "/status"
	ss.value = packageStatus
else
		if packageStatusCode == 0 then
			ss.template = packageName .. "/status"
		else
			ss.template = packageName .. "/status-textarea"
		end
	ss.value = packageStatus
	buttons = h:option(DummyValue, "_dummy")
	buttons.template = packageName .. "/buttons"
end

create_helper_text()
s3 = m:section(TypedSection, "https-dns-proxy", translate("Instances"),
	translatef("When you add/remove any instances below, they will be used to override the 'DNS forwardings' section of DHCP and DNS.", dispatcher.build_url("admin/network/dhcp")) .. helperText)
s3.template = "cbi/tblsection"
s3.sortable  = false
s3.anonymous = true
s3.addremove = true

prov = s3:option(ListValue, "resolver_url", translate("Resolver"))
for filename in fs.dir(providers_dir) do
	local p_func = loadfile(providers_dir .. filename)
	setfenv(p_func, { _ = i18n.translate })
	local p = p_func()
	prov:value(p.resolver_url, p.label)
	if p.default then
		prov.default = p.resolver_url
	end
end
prov.forcewrite = true
prov.write = function(self, section, value)
	if not value then return end
	for filename in fs.dir(providers_dir) do
		local p_func = loadfile(providers_dir .. filename)
		setfenv(p_func, { _ = i18n.translate })
		local p = p_func()
		value = value:gsub('[%p%c%s]', '')
		p.url_match = p.resolver_url:gsub('[%p%c%s]', '')
		if value:match(p.url_match) then
			uci:set(packageName, section, "bootstrap_dns", p.bootstrap_dns)
			uci:set(packageName, section, "resolver_url", p.resolver_url)
		end
	end
	uci:save(packageName)
end

la = s3:option(Value, "listen_addr", translate("Listen address"))
la.datatype    = "host"
la.placeholder = "127.0.0.1"
la.rmempty     = true

local n = 0
uci:foreach(packageName, packageName, function(s)
		if s[".name"] == section then
				return false
		end
		n = n + 1
end)

lp = s3:option(Value, "listen_port", translate("Listen port"))
lp.datatype = "port"
lp.value    = n + 5053

sa = s3:option(Value, "edns_subnet", translate("EDNS client subnet"))
sa.rmempty  = true

ps = s3:option(Value, "proxy_server", translate("Proxy server"))
ps.rmempty  = true

return m


text:
interface AnswersUpdateRequest {
    token:string,
    stageId:string;
    answers?:QuestAnswer[]
    teamBonuses?:QuestAnswer[]
}

interface AnswersUpdateResponse {
    success:boolean,
    stage?:Stage
}


text:
package com.josericardojunior.arch;

public class Cell {
	public int row;
	public int col;
	public float value;

	public Cell(){

	}

	public Cell(int row, int col, float value){
		this.row = row;
		this.col = col;
		this.value = value;
	}
}


text:
//
//  ICPclService.h
//  PCLService Library
//
//  Created by Stephane RABILLER on 04/12/14.
//  Copyright (c) 2014 Ingenico. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "ICAdministration.h"
#import "ICAdministration+StandAlone.h"
#import "ICAdministration+iBP.h"
#import "ICPPP.h"

@interface ICSSLParameters : NSObject

@property(nonatomic, assign) BOOL isSSL;

@property(nonatomic, retain) NSMutableString *sslCertificateName;

@property(nonatomic, retain) NSMutableString *sslCertificatePassword;

@end

@interface ICTerminal : NSObject

@property(nonatomic, retain) NSMutableString *terminalName;

@property(nonatomic, retain) NSMutableString *terminalMacAddress;

@property(nonatomic, assign) BOOL isBluetooth;

@property(nonatomic, retain) NSMutableString *terminalIPAddress;

@end

@interface NSString (NSStringHexToBytes)

-(NSData*) hexToBytes;

@end

@protocol ICPclServiceDelegate;

typedef enum {
    PCL_SERVICE_STOPPED = 0,                        /**< The service is stopped */
    PCL_SERVICE_STARTED,                            /**< The service is started but not connected to the Telium device */
    PCL_SERVICE_CONNECTED,                          /**< The service is started and an iDevice is connected to Telium device */
    PCL_SERVICE_FAILED_NO_CNX,                      /**< The service can't start due to no Wi-Fi or local hotspot available */
    PCL_SERVICE_FAILED_INTERNAL                     /**< The service can't start due to internal error */
} pclServiceState;

@interface ICPclService : NSObject <ICAdministrationDelegate, ICISMPDeviceDelegate>

+(id) sharedICPclService;

@property (nonatomic, assign) id<ICPclServiceDelegate> delegate;

-(pclServiceState)startPclServiceWith:(ICTerminal*) terminal andSecurity:(ICSSLParameters *) sslParams;

-(pclServiceState)getPclServiceState;

-(void)stopPclService;

+(void)selectTerminal:(ICTerminal *)wantedDevice;

+(ICTerminal*) getSelectedTerminal;

-(NSMutableArray *)getAvailableTerminals;

-(BOOL)setTerminalTime;

-(NSDate *)getTerminalTime;

-(ICDeviceInformation)getTerminalInfo;

-(NSString*)getFullSerialNumber;

-(void)resetTerminal:(NSUInteger)resetInfo;

-(BOOL)inputSimul:(NSUInteger)key;

-(NSArray *)getTerminalComponents;

-(NSString *)getSpmciVersion;

-(NSString*)getAddonVersion;

-(BOOL)doUpdate;

-(iSMPResult)setTmsInformation:(ICTmsInformation*)tmsInfos;

-(ICTmsInformation*)getTmsInformation;

-(iSMPResult)setLockBacklight:(NSUInteger)lockValue;

-(BOOL)launchM2OSshorcut:(NSString*)shortcutManager;

-(BOOL)sendMessage:(NSData *)data;

-(void)doTransaction:(ICTransactionRequest)request;

-(void)doTransactionEx:(ICTransactionRequest)request withData:(NSData *)extendedData andApplicationNumber:(NSUInteger)appNum;

-(void)setDoTransactionTimeout:(NSUInteger)timeout;

-(NSUInteger)getDoTransactionTimeout;

-(BOOL)submitSignatureWithImage:(UIImage *)image;

-(iBPResult)openPrinter;

-(iBPResult)closePrinter;

/**
 @anchor     printText
 @brief      Request to print the text provided as parameter

 The length of the string to be printed should not exceed 512 characters otherwise the call will fail.

 This call is blocking and has a timeout of 15 seconds. Before print text you should choose the font using @ref iBPSetFont. If @ref setPrinterFont is not used the default font is ISO8859-15.

 @param      text NSString object of the text to be printed. The  length of this string must be 512 characters at most.
 @result     One of the enumerations of @ref eiBPResult. It is iBPResult_OK when the call succeeds.
 */
-(iBPResult)printText:(NSString *)text;

-(iBPResult)printBitmap:(UIImage *)image;

-(iBPResult)printBitmap:(UIImage *)image lastBitmap:(BOOL)isLastBitmap;

-(iBPResult)printBitmap:(UIImage *)image size:(CGSize)bitmapSize alignment:(UITextAlignment)alignment;

-(iBPResult)printBitmap:(UIImage *)image size:(CGSize)bitmapSize alignment:(UITextAlignment)alignment lastBitmap:(BOOL)isLastBitmap;

-(iBPResult)storeLogoWithName:(NSString *)name andImage:(UIImage *)logo;

-(iBPResult)printLogoWithName:(NSString *)name;

-(iBPResult)getPrinterStatus;

/**
 @anchor     setPrinterFont
 @brief      Request to set the font provided as parameter

 This call permits to select the font used to print text using @ref printText.

 @param      selectedFontToTelium @ref eiBPFont enum encoding format ISO8859 supported by Telium.
 @result     One of the enumerations of @ref eiBPResult. It is iBPResult_OK when the call succeeds.
 */
-(iBPResult)setPrinterFont:(iBPFont *) selectedFontToTelium;

@property (nonatomic, readonly, getter = iBPMaxBitmapWidth) NSUInteger iBPMaxBitmapWidth;

@property (nonatomic, readonly, getter = iBPMaxBitmapHeight) NSUInteger iBPMaxBitmapHeight;

+(NSString*) severityLevelString:(int)level;

-(BOOL)setBacklightTimeout:(NSUInteger)backlightTimeout;

-(BOOL)setSuspendTimeout:(NSUInteger)suspendTimeout;

-(NSInteger)getBacklightTimeout;

-(NSInteger)getSuspendTimeout;

-(NSInteger)getBatteryLevel;

-(void)addDynamicBridge:(NSInteger)port :(int)redirection;

-(void)addDynamicBridgeLocal:(NSInteger)port :(int)redirection;

-(BOOL)setServerConnectionState:(BOOL)connectionState;

-(iSMPResult)setKeepAliveDelay:(int)keepAliveDelay Interval:(int)keepAliveInterVal andCount:(int)keepAliveCount;

@end

@protocol ICPclServiceDelegate

@optional

-(void)notifyConnection:(ICPclService *)sender;

-(void)notifyDisconnection:(ICPclService *)sender;

-(void)pclLogEntry:(NSString*)message withSeverity:(int)severity;

-(void)pclLogSerialData:(NSData*)data incoming:(BOOL)isIncoming;

-(void)shouldDoSignatureCapture:(ICSignatureData)signatureData;

-(void)signatureTimeoutExceeded;

-(void)transactionDidEndWithTimeoutFlag:(BOOL)replyReceived result:(ICTransactionReply)transactionReply andData:(NSData *)extendedData;

-(void)receiveMessage:(NSData *)data;

-(void)shouldPrintText:(NSString *)text withFont:(UIFont *)font alignment:(UITextAlignment)alignment XScaling:(NSInteger)xFactor YScaling:(NSInteger)yFactor underline:(BOOL)underline bold:(BOOL)bold;

-(void)shouldPrintRawText:(char *)text withCharset:(NSInteger)charset withFont:(UIFont *)font alignment:(UITextAlignment)alignment XScaling:(NSInteger)xFactor YScaling:(NSInteger)yFactor underline:(BOOL)underline bold:(BOOL)bold;

-(void)shouldPrintImage:(UIImage *)image;

-(void)shouldFeedPaperWithLines:(NSUInteger)lines;

-(void)shouldCutPaper;

-(NSInteger)shouldStartReceipt:(NSInteger)type;

-(NSInteger)shouldEndReceipt;

-(NSInteger)shouldAddSignature;

@end


text:
<!doctype html>

	<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
	<meta content="utf-8" http-equiv="encoding">
    <title>Siderite's Bookmark Explorer - manage bookmarks</title>

	<link rel="stylesheet" type="text/css" href="manage.css" media="all">

			Stay in this folder
			<input type="checkbox" id="chkHoldFolder"/>

Filter:<input id="txtFilter" />

Actions

Delete selected

Move selected to end of folder

Move selected to start of folder

Pages

Restore deleted bookmarks

Settings

Import/Export

Copy URLs to clipboard

Import URLs

		<textarea></textarea>

			<button id="btnClose">Close</button>
			<button id="btnOK">OK</button>


text:
#pragma once

namespace WebCore {

enum FrameState {
    FrameStateProvisional,
    // This state indicates we are ready to commit to a page,
    // which means the view will transition to use the new data source.
    FrameStateCommittedPage,
    FrameStateComplete
};

enum class PolicyAction {
    Use,
    Download,
    Ignore
};

enum class ReloadOption {
    ExpiredOnly = 1 << 0,
    FromOrigin  = 1 << 1,
    DisableContentBlockers = 1 << 2,
};

enum class FrameLoadType {
    Standard,
    Back,
    Forward,
    IndexedBackForward, // a multi-item hop in the backforward list
    Reload,
    Same, // user loads same URL again (but not reload button)
    RedirectWithLockedBackForwardList, // FIXME: Merge "lockBackForwardList", "lockHistory", "quickRedirect" and "clientRedirect" into a single concept of redirect.
    Replace,
    ReloadFromOrigin,
    ReloadExpiredOnly
};

enum class NewFrameOpenerPolicy {
    Suppress,
    Allow
};

enum class NavigationType {
    LinkClicked,
    FormSubmitted,
    BackForward,
    Reload,
    FormResubmitted,
    Other
};

enum class ShouldOpenExternalURLsPolicy {
    ShouldNotAllow,
    ShouldAllowExternalSchemes,
    ShouldAllow,
};

enum class InitiatedByMainFrame {
    Yes,
    Unknown,
};

enum ClearProvisionalItemPolicy {
    ShouldClearProvisionalItem,
    ShouldNotClearProvisionalItem
};

enum class ObjectContentType {
    None,
    Image,
    Frame,
    PlugIn,
};

enum UnloadEventPolicy {
    UnloadEventPolicyNone,
    UnloadEventPolicyUnloadOnly,
    UnloadEventPolicyUnloadAndPageHide
};

enum ShouldSendReferrer {
    MaybeSendReferrer,
    NeverSendReferrer
};

// Passed to FrameLoader::urlSelected() and ScriptController::executeIfJavaScriptURL()
// to control whether, in the case of a JavaScript URL, executeIfJavaScriptURL() should
// replace the document. It is a FIXME to eliminate this extra parameter from
// executeIfJavaScriptURL(), in which case this enum can go away.
enum ShouldReplaceDocumentIfJavaScriptURL {
    ReplaceDocumentIfJavaScriptURL,
    DoNotReplaceDocumentIfJavaScriptURL
};

enum WebGLLoadPolicy {
    WebGLBlockCreation,
    WebGLAllowCreation,
    WebGLPendingCreation
};

enum class LockHistory {
    Yes,
    No
};

enum class LockBackForwardList {
    Yes,
    No
};

enum class AllowNavigationToInvalidURL {
    Yes,
    No
};

enum class HasInsecureContent {
    Yes,
    No,
};

} // namespace WebCore

namespace WTF {

template<typename> struct EnumTraits;
template<typename E, E...> struct EnumValues;

template<> struct EnumTraits<WebCore::PolicyAction> {
    using values = EnumValues<
        WebCore::PolicyAction,
        WebCore::PolicyAction::Use,
        WebCore::PolicyAction::Download,
        WebCore::PolicyAction::Ignore
    >;
};

} // namespace WTF


text:
package com.hotels.plunger;

import static org.junit.Assert.assertEquals;

import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.RecordReader;
import org.junit.Test;

import cascading.scheme.Scheme;
import cascading.tap.partition.DelimitedPartition;
import cascading.tuple.Fields;

public class TapTypeUtilTest {

  @Test
  public void localFileTap() {
    Class<?> tapType = TapTypeUtil.getTapConfigClass(new cascading.tap.local.FileTap(
        new cascading.scheme.local.TextDelimited(), ""));
    assertEquals(Properties.class, tapType);
  }

  @Test
  public void localPartitionTap() {
    Class<?> tapType = TapTypeUtil.getTapConfigClass(new cascading.tap.local.PartitionTap(
        new cascading.tap.local.FileTap(new cascading.scheme.local.TextDelimited(), ""), new DelimitedPartition(
            new Fields("A"))));
    assertEquals(Properties.class, tapType);
  }

  @Test
  public void hadoopHfsTap() {
    Class<?> tapType = TapTypeUtil.getTapConfigClass(new cascading.tap.hadoop.Hfs(
        new cascading.scheme.hadoop.TextDelimited(), ""));
    assertEquals(Configuration.class, tapType);
  }

  @Test
  public void multiLevelHierarchy() {
    Class<?> tapType = TapTypeUtil.getTapConfigClass(new TestHfs(new cascading.scheme.hadoop.TextDelimited(), ""));
    assertEquals(Configuration.class, tapType);
  }

  @Test
  public void hadoopPartitionTap() {
    Class<?> tapType = TapTypeUtil.getTapConfigClass(new cascading.tap.hadoop.PartitionTap(
        new cascading.tap.hadoop.Hfs(new cascading.scheme.hadoop.TextDelimited(), ""), new DelimitedPartition(
            new Fields("A"))));
    assertEquals(Configuration.class, tapType);
  }

  @SuppressWarnings({ "rawtypes", "unchecked" })
  @Test
  public void compositeHadoopTap() {
    Class<?> tapType = TapTypeUtil.getTapConfigClass(new cascading.tap.MultiSourceTap(new cascading.tap.hadoop.Hfs(
        new cascading.scheme.hadoop.TextDelimited(), "")));
    assertEquals(Configuration.class, tapType);
  }

  @SuppressWarnings({ "rawtypes", "unchecked" })
  @Test
  public void compositeLocalTap() {
    Class<?> tapType = TapTypeUtil.getTapConfigClass(new cascading.tap.MultiSourceTap(new cascading.tap.local.FileTap(
        new cascading.scheme.local.TextDelimited(), "")));
    assertEquals(Properties.class, tapType);
  }

  private static class TestHfs extends cascading.tap.hadoop.Hfs {

    private static final long serialVersionUID = 1L;

    private TestHfs(@SuppressWarnings("rawtypes") Scheme<Configuration, RecordReader, OutputCollector, ?, ?> scheme,
        String stringPath) {
      super(scheme, stringPath);
    }
  }

}


text:
package com.aboutcoder.packease.snippet.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;

public class MainMenuAction extends AnAction {
    @Override
    public void actionPerformed(AnActionEvent anActionEvent) {
        System.out.println("anActionEvent = [" + anActionEvent + "]");
    }

    @Override
    public void update(AnActionEvent e) {
        e.getPresentation().setVisible(true);
    }
}


text:
"""Support for August buttons."""
from yalexs.lock import Lock

from homeassistant.components.button import ButtonEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from . import AugustData
from .const import DOMAIN
from .entity import AugustEntityMixin

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Set up August lock wake buttons."""
    data: AugustData = hass.data[DOMAIN][config_entry.entry_id]
    async_add_entities(AugustWakeLockButton(data, lock) for lock in data.locks)

class AugustWakeLockButton(AugustEntityMixin, ButtonEntity):
    """Representation of an August lock wake button."""

    def __init__(self, data: AugustData, device: Lock) -> None:
        """Initialize the lock wake button."""
        super().__init__(data, device)
        self._attr_name = f"{device.device_name} Wake"
        self._attr_unique_id = f"{self._device_id}_wake"

    async def async_press(self, **kwargs):
        """Wake the device."""
        await self._data.async_status_async(self._device_id, self._hyper_bridge)

    @callback
    def _update_from_data(self):
        """Nothing to update as buttons are stateless."""


text:
namespace meta
{
	namespace _private
	{
		namespace _interface
		{
			template <class Check, class ... InterfaceChecker>
			struct interface_datas : public interface_datas<InterfaceChecker...>, public Check::storage_type
			{
			};

			template <class Check>
			struct interface_datas<Check> : public Check::storage_type
			{
				void		*object_pointer;
			};

			template <class T, class Check, class ...InterfaceChecker>
			struct interface_init
			{
				template <class M>
				static inline void init(T *data, M *idatas) {
					Check::init(data, idatas);
					interface_init<T, InterfaceChecker...>::template init<M>(data, idatas);
				}
			};
			template <class T, class Check>
			struct interface_init<T, Check>
			{
				template <class M>
				static inline void init(T *data, M *idatas) {
					Check::init(data, idatas);
					idatas->object_pointer = (void *)data;
				}
			};
		}

	}

	template <class ... InterfaceChecker>
	class interface
	{
	private:
		_private::_interface::interface_datas<InterfaceChecker...>		_datas;
		interface() = delete;

	public:
		template <class T>
		inline interface(T* data) {
			meta::rules::interface_validator<InterfaceChecker...>::template static_validate<T>();
			_private::_interface::interface_init<T, InterfaceChecker...>::init(data, &this->_datas);
		}
		virtual ~interface() = default;
		inline bool	operator==(const interface& i) const {
			return (this->_datas.object_pointer == i._datas.object_pointer);
		}
		template <class T>
		inline bool	operator==(T *data) const {
			return (this->_datas.object_pointer == data);
		}
		inline bool operator!=(const interface& i) const {
			return (this->_datas.object_pointer != i._datas.object_pointer);
		}
		template <class T>
		inline bool	operator!=(T *data) const {
			return (this->_datas.object_pointer != data);
		}
		inline auto operator->() {
			return (&this->_datas);
		}
		inline auto operator->() const {
			return (&this->_datas);
		}
		inline auto operator*() {
			return (this->_datas);
		}
		inline auto operator*() const {
			return (this->_datas);
		}
	};
}

#endif


text:
<!DOCTYPE html>

		<title>three.js webgl - animation - basic</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js webgl - animation - basic use


text:
_.extend(DV.Schema.helpers, {
  resetNavigationState: function(){
    var elements                      = this.elements;
    elements.chaptersContainer[0].id  = '';
    elements.navigation[0].id         = '';
  },
  setActiveChapter: function(chapterId){
    this.elements.chaptersContainer.attr('id','DV-selectedChapter-'+chapterId);
  },
  setActiveAnnotationInNav: function(annotationId){
    if(annotationId){
      this.elements.navigation.attr('id','DV-selectedAnnotation-'+annotationId);
    }else{
      this.elements.navigation.attr('id','');
    }
  }
});


text:
/***********************************************************************************************************************************
Verify Protocol Handler
***********************************************************************************************************************************/
#include "build.auto.h"

#include "command/verify/file.h"
#include "command/verify/protocol.h"
#include "common/debug.h"
#include "common/io/io.h"
#include "common/log.h"
#include "common/memContext.h"
#include "config/config.h"
#include "storage/helper.h"

/**********************************************************************************************************************************/
void
verifyFileProtocol(PackRead *const param, ProtocolServer *const server)
{
    FUNCTION_LOG_BEGIN(logLevelDebug);
        FUNCTION_LOG_PARAM(PACK_READ, param);
        FUNCTION_LOG_PARAM(PROTOCOL_SERVER, server);
    FUNCTION_LOG_END();

    ASSERT(param != NULL);
    ASSERT(server != NULL);

    MEM_CONTEXT_TEMP_BEGIN()
    {
        // Verify file
        const String *const filePathName = pckReadStrP(param);

        uint64_t offset = 0;
        const Variant *limit = NULL;

        if (pckReadBoolP(param))
        {
            offset = pckReadU64P(param);
            limit = varNewUInt64(pckReadU64P(param));
        }

        const CompressType compressType = (CompressType)pckReadU32P(param);
        const String *const fileChecksum = pckReadStrP(param);
        const uint64_t fileSize = pckReadU64P(param);
        const String *const cipherPass = pckReadStrP(param);

        const VerifyResult result = verifyFile(filePathName, offset, limit, compressType, fileChecksum, fileSize, cipherPass);

        // Return result
        protocolServerDataPut(server, pckWriteU32P(protocolPackNew(), result));
        protocolServerDataEndPut(server);
    }
    MEM_CONTEXT_TEMP_END();

    FUNCTION_LOG_RETURN_VOID();
}


text:
<settings 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/settings-1.0.0.xsd">
  <servers>
    <server>
      <id>openconext-releases</id>
      <username>?????</username>
      <password>?????</password>
    </server>
    <server>
      <id>openconext-snapshots</id>
      <username>?????</username>
      <password>?????</password>
    </server>
  </servers>
</settings>


text:
import { generateUtilityClass, generateUtilityClasses } from '@material-ui/unstyled';

export function getCardActionsUtilityClass(slot) {
  return generateUtilityClass('MuiCardActions', slot);
}

const cardActionsClasses = generateUtilityClasses('MuiCardActions', ['root', 'spacing']);

export default cardActionsClasses;


text:
module Application
  class Git < Base
    def install
      FileUtils.chdir(base_directory) do
        add_gitconfig
        add_gitignore
      end
    end

    private

    def add_gitconfig
      source = File.expand_path(File.join(base_directory, '.gitconfig'))
      target = File.expand_path(File.join(home_directory, '.gitconfig'))
      Link.new(source, target).create
    end

    def add_gitignore
      source = File.expand_path(File.join(base_directory, '.gitignore'))
      target = File.expand_path(File.join(home_directory, '.gitignore'))
      Link.new(source, target).create
    end
  end
end


text:
require 'test_helper'

class UsersProfileTest < ActionDispatch::IntegrationTest
  include ApplicationHelper

  def setup
    @user = users(:xi)
  end

  test "profile display" do
    #get user_path(@user)
    #assert_template 'users/show'
    # No idea where went wrong
    #assert_select 'title', full_title(@user.name)
    # 不知道抽什么风,明明就有的。
    #assert_select 'p', text: @user.name
    #assert_select 'h1>img.gravatar'
    #assert_match @user.microposts.count.to_s, response.body
    #assert_select 'div.pagination'
    #@user.microposts.paginate(page: 1).each do |micropost|
    #  assert_match micropost.content, response.body
    #end
  end

end


text:
import React, { PropTypes, Component } from 'react';
import ReactDOM from 'react-dom';
import { browserHistory } from 'react-router';
import { observer } from 'mobx-react';

import TrackerStore from './../../stores/TrackerStore';
import { unsetTrackerStore } from './../../utils/PopulateTrackerStore';

@observer
class UserContext extends Component {
  constructor() {
    super();

    this.state = {
      visible: false
    };
  }

  componentDidMount () {
    document.getElementById('app')
      .addEventListener('click', this.handleDocumentClick);
  }

  componentWillUnmount () {
    document.getElementById('app')
      .removeEventListener('click', this.handleDocumentClick);
  }

  toggleVisible(state) {
    this.setState({ visible: typeof state === 'boolean'
        ? state : !this.state.visible });
  }

  logout() {
    this.setState({ visible: false });
    this.context.appState.apiToken = undefined;
    this.context.appState.columnSetup = this.context.appState.defaultColumnSetup;
    this.context.appState.theme = this.context.appState.defaultTheme;
    unsetTrackerStore();
    browserHistory.push('/');
  }

  goToSettings() {
    this.setState({ visible: false });
    browserHistory.push('/settings');
  }

  handleDocumentClick = (evt) => {
    const area = ReactDOM.findDOMNode(this.refs.area);

    if (area && area !== evt.target && !area.contains(evt.target)) {
      this.toggleVisible(false);
    }
  }

  render() {
    if (this.context.appState.isAuthenticated === false || !TrackerStore.me.api_token) {
      return
;
    }

    return (

          {TrackerStore.me.initials} {this.state.visible ? '\u25B8' : '\u25BE'}

        <div className={`header__toolbar__loggedin__context ${this.state.visible ? '' : 'hidden'}`}>

            {TrackerStore.me.name}

          Settings

            Logout

    );
  }
}

UserContext.contextTypes = {
  appState: PropTypes.object
};

export default UserContext;


text:
A simple AI demonstration of the [Negamax algorithm](https://en.wikipedia.org/wiki/Negamax) with alpha/beta pruning.

Game rules are a Mancala variant known as [das Bohnenspiel](https://en.wikipedia.org/wiki/Das_Bohnenspiel).

There are two additional "house" rules to facilitate computer play:

  - A player without stones passes until they have stones to play (instead of the game ending)
  - A position that has been repeated three times results in the game ending with remaining stones divided equally

The first rule is my personal preference to prevent hoarding / starvation strategies. There is also some historical precedent to suggest it has been played this way in the past.

The second rule is not usually used in human play, but is common in computer tournaments for a similar Mancala game, [Oware](https://en.wikipedia.org/wiki/Oware).  I also prefer using this rule in human play since it is quite feasible for a losing player to force an endless cycle with two remaining stones.

## Using the software

Requires Scala 2.11.8 and SBT 0.13.11.  [ScalaTest](http://www.scalatest.org) is required to run tests.  No other libraries are required.

To run unit tests, execute `sbt test` in the project directory.

To play against the computer, execute `sbt run`.

## Implementation notes

The Negamax walk algorithm has been reimplemented to be more functional in style as compared to the usual reference imperative code.  The depth parameter is dynamically scaled to increase as the board simplifies.

The state heuristic uses a probabilistic model of the expected value of the state (+1.0 for player one winning, 0 for draw, and -1.0 for player two winning) under a hypothetical random fair division of the remaining stones.  This has some nice properties, such as automatically detecting when a lead in score is insurmountable, preferring trades when ahead in score, and avoiding trades when behind.

For speed, the heuristic is calculated using a custom `Math` module that provides memoized [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) functions.


text:
package swoop.path;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import org.testng.annotations.Test;

public class VerbMatchersTest {

    private VerbMatcher matcher;

    @Test
    public void fromExpression_empty() {
        matcher = VerbMatchers.fromExpression("");
        for (Verb verb : Verb.values())
            assertThat("Testing " + verb, matcher.matches(verb), is(false));
    }

    @Test
    public void fromExpression_singleVerb() {
        matcher = VerbMatchers.fromExpression("post");
        for (Verb verb : Verb.values())
            assertThat("Testing " + verb, matcher.matches(verb), is(verb==Verb.Post));
    }

    @Test
    public void fromExpression_threeVerbs() {
        matcher = VerbMatchers.fromExpression("post,put,websocketOpen");
        for (Verb verb : Verb.values())
            assertThat("Testing " + verb, matcher.matches(verb), is(verb==Verb.Post || verb==Verb.Put || verb==Verb.WebSocketOpen));
    }

    @Test
    public void fromExpression_any() {
        matcher = VerbMatchers.fromExpression("any");
        for (Verb verb : Verb.values())
            assertThat("Testing " + verb, matcher.matches(verb), is(true));

        matcher = VerbMatchers.fromExpression("*");
        for (Verb verb : Verb.values())
            assertThat("Testing " + verb, matcher.matches(verb), is(true));

        matcher = VerbMatchers.fromExpression("get,any,post");
        for (Verb verb : Verb.values())
            assertThat("Testing " + verb, matcher.matches(verb), is(true));
    }

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Options;

namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common
{
    internal interface IEnumSettingViewModelFactory
    {
        bool IsSupported(OptionKey2 key);
        IEnumSettingViewModel CreateViewModel(WhitespaceSetting setting);
    }
}


text:
<?php

class Global_Model_DbTable_DbOccupation extends Zend_Db_Table_Abstract
{

    protected $_name = 'rms_occupation';
    public function getUserId(){
    	$session_user=new Zend_Session_Namespace('auth');
    	return $session_user->user_id;

    }
	public function addNewOccupation($_data){
		$_arr=array(
				'occu_name'	  => $_data['occu_name'],
				'occu_enname'	  => $_data['occu_enname'],
				'create_date' => Zend_Date::now(),
				'status'   => $_data['status'],
				'user_id'	  => $this->getUserId()
		);
		return  $this->insert($_arr);
	}

	public function addNewOccupationPopup($_data){
		$_arr=array(
				'occu_name'	  => $_data['occu_name'],
				'occu_enname'	  => $_data['occu_enname'],
				'create_date' => Zend_Date::now(),
				'status'   => $_data['status_j'],
				'user_id'	  => $this->getUserId()
		);
		return  $this->insert($_arr);
	}

	public function getOccupationById($id){
		$db = $this->getAdapter();
		$sql = "SELECT * FROM rms_occupation WHERE occupation_id = ".$db->quote($id);
		$sql.=" LIMIT 1 ";
		$row=$db->fetchRow($sql);
		return $row;
	}
	public function updateOccupation($_data){
		$_arr=array(
				'occu_name'	  => $_data['occu_name'],
				'occu_enname'	  => $_data['occu_enname'],
				'create_date' => Zend_Date::now(),
				'status'   => $_data['status'],
				'user_id'	  => $this->getUserId()
		);
		$where=$this->getAdapter()->quoteInto("occupation_id=?", $_data["id"]);
		$this->update($_arr, $where);
	}
	function getAllOccupation($search){
		$db = $this->getAdapter();
		$sql = " SELECT occupation_id AS id,occu_name,occu_enname, create_date,status,(SELECT  CONCAT(first_name,' ', last_name) FROM rms_users WHERE id=user_id )AS user_name
		FROM rms_occupation ";
		$order = ' ORDER BY occu_name ASC ';
		$where = ' WHERE 1 ';
		if(empty($search)){
			return $db->fetchAll($sql.$order);
		}
		if(!empty($search['title'])){
			$s_where = array();
			$s_search = addslashes(trim($search['title']));
			$s_where[] = " occu_name LIKE '%{$s_search}%'";
			$s_where[] = " occu_enname LIKE '%{$s_search}%'";
			$where .=' AND ( '.implode(' OR ',$s_where).')';
		}
		return $db->fetchAll($sql.$where.$order);
	}
	public function addOccupation($_data){//ajax
		$_arr=array(
				'occu_name'	  => $_data['occu_name'],
				'create_date' => Zend_Date::now(),
				'status'   => 1,
				'user_id'	  => $this->getUserId()
		);
		return  $this->insert($_arr);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<changeLogs
        xmlns="http://www.witsml.org/schemas/1series"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.witsml.org/schemas/1series  ../xsd_schemas/obj_changeLog.xsd"
        version="1.4.1.1">
    <changeLog uidWell="" uidWellbore="" uid="" uidObject="">
        <nameWell/>
        <nameWellbore/>
        <nameObject/>
        <objectType/>
        <lastChangeType/>
        <lastChangeInfo/>
        <changeHistory>
            <dTimChange/>
            <changeType/>
            <objectGrowingState/>
            <updatedHeader/>
            <changeInfo/>
            <startDateTimeIndex uom=""/>
            <endDateTimeIndex uom=""/>
            <mnemonics/>
        </changeHistory>
        <commonData>
            <dTimCreation/>
            <dTimLastChange/>
        </commonData>
    </changeLog>
</changeLogs>


text:
<?php
/**
 * Created by PhpStorm.
 * User: am_ry
 * Date: 14.09.2017
 * Time: 12:20
 */

namespace osm2sql\entity;

class Relation implements EntityHaveId, EntityHaveNode
{
    private $id = null;
    private $user = null;
    private $uid = null;
    private $visible = null;
    private $version = null;
    private $changeSet = null;
    private $timestamp = null;
    private $sort = 0;

    /**
     * @param array $array
     */
    public function __construct($array)
    {
        if (isset($array['ID'])) {
            $this->id = $array['ID'];
        }
        if (isset($array['LAT'])) {
            $this->lat = $array['LAT'];
        }
        if (isset($array['LON'])) {
            $this->lon = $array['LON'];
        }
        if (isset($array['USER'])) {
            $this->user = $array['USER'];
        }
        if (isset($array['UID'])) {
            $this->uid = $array['UID'];
        }
        if (isset($array['VISIBLE'])) {
            $this->visible = strtolower($array['VISIBLE']) == 'true';
        }
        if (isset($array['VERSION'])) {
            $this->version = $array['VERSION'];
        }
        if (isset($array['CHANGESET'])) {
            $this->changeSet = $array['CHANGESET'];
        }
        if (isset($array['TIMESTAMP'])) {
            $this->timestamp = $array['TIMESTAMP'];
        }
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * @return mixed
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * @param mixed $user
     */
    public function setUser($user)
    {
        $this->user = $user;
    }

    /**
     * @return mixed
     */
    public function getUid()
    {
        return $this->uid;
    }

    /**
     * @param mixed $uid
     */
    public function setUid($uid)
    {
        $this->uid = $uid;
    }

    /**
     * @return bool
     */
    public function getVisible()
    {
        return $this->visible;
    }

    /**
     * @param bool $visible
     */
    public function setVisible($visible)
    {
        $this->visible = $visible;
    }

    /**
     * @return bool
     */
    public function getVersion()
    {
        return $this->version;
    }

    /**
     * @param mixed $version
     */
    public function setVersion($version)
    {
        $this->version = $version;
    }

    /**
     * @return mixed
     */
    public function getChangeSet()
    {
        return $this->changeSet;
    }

    /**
     * @param mixed $changeSet
     */
    public function setChangeSet($changeSet)
    {
        $this->changeSet = $changeSet;
    }

    /**
     * @return mixed
     */
    public function getTimestamp()
    {
        return $this->timestamp;
    }

    /**
     * @param mixed $timestamp
     */
    public function setTimestamp($timestamp)
    {
        $this->timestamp = $timestamp;
    }

    public function nextSort()
    {
        return $this->sort++;
    }
}


text:
package com.streamsets.datacollector.runner;

import com.google.common.base.Preconditions;
import com.streamsets.datacollector.blobstore.BlobStoreRuntime;
import com.streamsets.datacollector.blobstore.BlobStoreTask;
import com.streamsets.datacollector.config.StageConfiguration;
import com.streamsets.datacollector.config.StageDefinition;
import com.streamsets.datacollector.event.dto.PipelineStartEvent;
import com.streamsets.datacollector.util.Configuration;
import com.streamsets.pipeline.api.BlobStore;
import com.streamsets.pipeline.api.DeliveryGuarantee;
import com.streamsets.pipeline.api.ExecutionMode;
import com.streamsets.pipeline.api.StageBehaviorFlags;
import com.streamsets.pipeline.api.StageDef;
import com.streamsets.pipeline.api.StageType;
import com.streamsets.pipeline.api.interceptor.InterceptorCreator;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Builder for creating interceptor creator context with all that it needs.
 */
public class InterceptorCreatorContextBuilder {

  private static class BaseContextImpl implements InterceptorCreator.BaseContext {
    private final BlobStore blobStore;
    private final Configuration configuration;
    private final Map<String, String> parameters;
    private final ExecutionMode executionMode;
    private final DeliveryGuarantee deliveryGuarantee;

    private BaseContextImpl(
      BlobStore blobStore,
      Configuration configuration,
      Map<String, String> parameters,
      ExecutionMode executionMode,
      DeliveryGuarantee deliveryGuarantee
    ) {
      this.blobStore = blobStore;
      this.configuration = configuration;
      this.parameters = parameters;
      this.executionMode = executionMode;
      this.deliveryGuarantee = deliveryGuarantee;
    }

    @Override
    public String getConfig(String configName) {
      return configuration.get(configName, null);
    }

    @Override
    public BlobStore getBlobStore() {
      return blobStore;
    }

    @Override
    public Map<String, String> getParameters() {
      return parameters;
    }

    @Override
    public ExecutionMode getExecutionMode() {
      return executionMode;
    }

    @Override
    public DeliveryGuarantee getDeliveryGuarantee() {
      return deliveryGuarantee;
    }

  }

  /**
   * Actual Context implementation that will be returned when build.
   */
  private static class ContextImpl extends BaseContextImpl implements InterceptorCreator.Context {
    private final InterceptorCreator.InterceptorType interceptorType;
    private final StageConfiguration stageConfiguration;
    private final StageDefinition stageDefinition;
    private final Set<StageBehaviorFlags> stageBehaviorFlags;

    private ContextImpl(
      BlobStore blobStore,
      Configuration configuration,
      StageConfiguration stageConfiguration,
      StageDefinition stageDefinition,
      InterceptorCreator.InterceptorType interceptorType,
      Map<String, String> parameters,
      ExecutionMode executionMode,
      DeliveryGuarantee deliveryGuarantee
    ) {
      super(blobStore, configuration, parameters, executionMode, deliveryGuarantee);
      this.stageConfiguration = stageConfiguration;
      this.stageDefinition = stageDefinition;
      this.interceptorType = interceptorType;
      if(stageDefinition.getStageDef() == null) {
        this.stageBehaviorFlags = Collections.emptySet();
      } else {
        this.stageBehaviorFlags = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(stageDefinition.getStageDef().flags())));
      }
    }

    @Override
    public StageType getStageType() {
      return stageDefinition.getType();
    }

    @Override
    public InterceptorCreator.InterceptorType getInterceptorType() {
      return interceptorType;
    }

    @Override
    public StageDef getStageDef() {
      return stageDefinition.getStageDef();
    }

    @Override
    public String getStageInstanceName() {
      return stageConfiguration.getInstanceName();
    }

    @Override
    public Set<StageBehaviorFlags> getStageBehaviorFlags() {
      return stageBehaviorFlags;
    }
  }

  private final BlobStore blobStore;
  private final Configuration sdcConf;
  private final Map<String, Map<String, String>> interceptorConf;
  private ExecutionMode executionMode;
  private DeliveryGuarantee deliveryGuarantee;

  public InterceptorCreatorContextBuilder(
    BlobStore blobStore,
    Configuration configuration
  ) {
    this(blobStore, configuration, Collections.emptyList());
  }

  public InterceptorCreatorContextBuilder(
    BlobStore blobStore,
    Configuration configuration,
    List<PipelineStartEvent.InterceptorConfiguration> interceptorConf
  ) {
    this.blobStore = blobStore;
    this.sdcConf = configuration;
    this.interceptorConf = convertToLookUpMap(interceptorConf);
  }

  private Map<String, Map<String, String>> convertToLookUpMap(List<PipelineStartEvent.InterceptorConfiguration> interceptorConf) {
    Map<String, Map<String, String>> output = new HashMap<>();
    if(interceptorConf == null) {
      return output;
    }

    // Convert the list to map while ensuring uniqueness
    for(PipelineStartEvent.InterceptorConfiguration startEvent : interceptorConf) {
      String key = lookupKey(startEvent.getStageLibrary(), startEvent.getInterceptorClassName());
      Preconditions.checkArgument(!output.containsKey(key), "Duplicate interceptor configuration for: " + key);
      output.put(key, startEvent.getParameters());
    }

    return output;
  }

  public InterceptorCreatorContextBuilder withExecutionMode(ExecutionMode executionMode) {
    this.executionMode = executionMode;
    return this;
  }

  public InterceptorCreatorContextBuilder withDeliveryGuarantee(DeliveryGuarantee deliveryGuarantee) {
    this.deliveryGuarantee = deliveryGuarantee;
    return this;
  }

  public InterceptorCreator.BaseContext buildBaseContext(String stageLibrary, String className) {
    return new BaseContextImpl(
      new BlobStoreRuntime(Thread.currentThread().getContextClassLoader(), blobStore),
      sdcConf,
      interceptorConf.get(lookupKey(stageLibrary, className)),
      executionMode,
      deliveryGuarantee
    );
  }

  public InterceptorCreator.Context buildFor(
    String stageLibrary,
    String className,
    StageConfiguration stageConfiguration,
    StageDefinition stageDefinition,
    InterceptorCreator.InterceptorType interceptorType
  ) {
    return new ContextImpl(
        new BlobStoreRuntime(Thread.currentThread().getContextClassLoader(), blobStore),
        sdcConf,
        stageConfiguration,
        stageDefinition,
        interceptorType,
        interceptorConf.get(lookupKey(stageLibrary, className)),
        executionMode,
        deliveryGuarantee
    );
  }

  /**
   * Generate lookup key interceptor configuration. This key is only used within this class.
   */
  private static String lookupKey(String stageLib, String className) {
    return stageLib + "::" + className;
  }

}


text:
def helper
  @helper ||= ApplicationController.helpers
end

@controller = ApplicationController.new


text:
import * as React from 'react';

export const About: React.StatelessComponent<{}> = () => {
  return (

10 Loader Spinner

            This sample takes as starting point sample "10 AsyncCalls_Redux_Thunk".

            Refactor, instead of managing async calls via Redux Thunk, use Redux Saga (Important: we are targeting here ES6).

Highlights

          The most interesting parts worth to take a look

Components:

                  app.tsx: Here we initialize Redux Saga middleware and register our sagas / watchers.

                  membersSaga.tsx: This saga will be watching for fetchMemberRequest action and perform the async call.

                  watchersSaga.tsx: Common entry point to register all sagas.

                  fetMembersRequest.tsx: Naming refactor, instead of LoadMembers / AssignMembers, we have
                       decided to rename it to: fetchMembersRequest, fetchMembersCompleted.

  );
}


text:
class DepartmentsController < ApplicationController
    layout 'administrator'
        def index
        @departments = Department.all

        respond_to do |format|
            format.html do

            end

            format.json do
                render json: @departments
            end

            format.pdf do

            end
        end
    end

    def new

    end

    def create
        @department = Department.new
        @department.id = params[:id]
        @department.name = params[:name]
        @department.code = params[:code]
        if @department.save!

            flash[:info] = "Department record has been updated"
            redirect_to '/departments'
        end
    end

    def show
        @department = Department.find(params[:id])
    end

    def edit
        @department = Department.find(params[:id])
    end

    def update
        @department = Department.find(params[:id])
            @department.name = params[:name]
        @department.code = params[:code]
        if @department.save!

            flash[:info] = "Department record has been updated"
            redirect_to '/departments'
        end
    end

    def destroy
        @department =Department.find(params[:id])
        if @department.destroy

            flash[:info] ="Department record has been destroyed"
            redirect_to '/departments'
        end
    end
end


text:
This document describes the command line tool that comes with gRPC repository. It is desirable to have command line
tools written in other languages roughly follow the same syntax and flags.

At this point, the tool needs to be built from source, and it should be moved out to grpc-tools repository as a stand
alone application once it is mature enough.

## Core functionality

The command line tool can do the following things:

- Send unary rpc.
- Attach metadata and display received metadata.
- Handle common authentication to server.
- Infer request/response types from server reflection result.
- Find the request/response types from a given proto file.
- Read proto request in text form.
- Read request in wire form (for protobuf messages, this means serialized binary form).
- Display proto response in text form.
- Write response in wire form to a file.

The command line tool should support the following things:

- List server services and methods through server reflection.
- Fine-grained auth control (such as, use this oauth token to talk to the server).
- Send streaming rpc.

## Code location

To use the tool, you need to get the grpc repository and make sure your system
has the prerequisites for building grpc from source, given in the [installation
instructions](../BUILDING.md).

In order to build the grpc command line tool from a fresh clone of the grpc
repository, you need to run the following command to update submodules:

```
git submodule update --init
```

Once the prerequisites are satisfied, you can build with cmake:

```
$ mkdir -p cmake/build
$ cd cmake/build
$ cmake -DgRPC_BUILD_TESTS=ON ../..
$ make grpc_cli
```

The main file can be found at
https://github.com/grpc/grpc/blob/master/test/cpp/util/grpc_cli.cc

## Prerequisites

Most `grpc_cli` commands need the server to support server reflection. See
guides for
[Java](https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md#enable-server-reflection)
, [C++](https://github.com/grpc/grpc/blob/master/doc/server_reflection_tutorial.md)
and [Go](https://github.com/grpc/grpc-go/blob/master/Documentation/server-reflection-tutorial.md)

Local proto files can be used as an alternative. See instructions [below](#Call-a-remote-method).

## Usage

### List services

`grpc_cli ls` command lists services and methods exposed at a given port

-   List all the services exposed at a given port

    ```sh
    $ grpc_cli ls localhost:50051
    ```

    output:

    ```none
    helloworld.Greeter
    grpc.reflection.v1alpha.ServerReflection
    ```

    The `localhost:50051` part indicates the server you are connecting to.

-   List one service with details

    `grpc_cli ls` command inspects a service given its full name (in the format
    of \<package\>.\<service\>). It can print information with a long listing
    format when `-l` flag is set. This flag can be used to get more details
    about a service.

    ```sh
    $ grpc_cli ls localhost:50051 helloworld.Greeter -l
    ```

    `helloworld.Greeter` is full name of the service.

    output:

    ```proto
    filename: helloworld.proto
    package: helloworld;
    service Greeter {
      rpc SayHello(helloworld.HelloRequest) returns (helloworld.HelloReply) {}
    }

    ```

### List methods

-   List one method with details

    `grpc_cli ls` command also inspects a method given its full name (in the
    format of \<package\>.\<service\>.\<method\>).

    ```sh
    $ grpc_cli ls localhost:50051 helloworld.Greeter.SayHello -l
    ```

    `helloworld.Greeter.SayHello` is full name of the method.

    output:

    ```proto
    rpc SayHello(helloworld.HelloRequest) returns (helloworld.HelloReply) {}
    ```

### Inspect message types

We can use `grpc_cli type` command to inspect request/response types given the
full name of the type (in the format of \<package\>.\<type\>).

-   Get information about the request type

    ```sh
    $ grpc_cli type localhost:50051 helloworld.HelloRequest
    ```

    `helloworld.HelloRequest` is the full name of the request type.

    output:

    ```proto
    message HelloRequest {
      optional string name = 1;
    }
    ```

### Call a remote method

We can send RPCs to a server and get responses using `grpc_cli call` command.

-   Call a unary method Send a rpc to a helloworld server at `localhost:50051`:

    ```sh
    $ grpc_cli call localhost:50051 SayHello "name: 'gRPC CLI'"
    ```

    output: `sh message: "Hello gRPC CLI"`

    `SayHello` is (part of) the gRPC method string. Then `"name: 'world'"` is
    the text format of the request proto message. For information on more flags,
    look at the comments of `grpc_cli.cc`.

-   Use local proto files

    If the server does not have the server reflection service, you will need to
    provide local proto files containing the service definition. The tool will
    try to find request/response types from them.

    ```sh
    $ grpc_cli call localhost:50051 SayHello "name: 'world'" \
      --protofiles=examples/protos/helloworld.proto
    ```

    If the proto file is not under the current directory, you can use
    `--proto_path` to specify new search roots
    (separated by colon on Mac/Linux/Cygwin or semicolon on Windows).

    Note that the tool will always attempt to use the reflection service first,
    falling back to local proto files if the service is not found. Use
    `--noremotedb` to avoid attempting to use the reflection service.

-   Send non-proto rpc

    For using gRPC with protocols other than protobuf, you will need the exact
    method name string and a file containing the raw bytes to be sent on the
    wire.

    ```bash
    $ grpc_cli call localhost:50051 /helloworld.Greeter/SayHello \
      --input_binary_file=input.bin \
      --output_binary_file=output.bin
    ```

    On success, you will need to read or decode the response from the
    `output.bin` file.


text:
namespace Gdv.NUnit {

        using System;
        using global::NUnit.Framework;
        using Gdv;

        [TestFixture]
        public class FractionTest {

                [Test]
                public void Simplyfying ()
                {
                        Fraction pal = new Fraction (25, 1);
                        Fraction fifty = new Fraction (50, 2);
                        Fraction hundred = new Fraction (100, 4);

                        Assert.AreEqual (pal, fifty, "50/2 should be equal 25/1");
                        Assert.AreEqual (pal, hundred, "100/4 should be equal 25/1");

                        Fraction complex = new Fraction (33, 2);
                        Assert.AreEqual (33, complex.Numerator, "How come this fraction was simplified?");
                        Assert.AreEqual (2, complex.Denominator, "How come this fraction was simplified?");

                        Fraction complex2 = new Fraction (33, 3);
                        Assert.AreEqual (11, complex2.Numerator, "The numerator should be 11 after simplification");
                        Assert.AreEqual (1, complex2.Denominator, "The denominator should be 1 after simplification");
                }

                [Test]
                public void Empty ()
                {
                        Fraction empt = new Fraction (25, 0);
                        Assert.AreEqual (Fraction.Empty, empt, "This fraction should report as empty");
                }

                [Test]
                public void Double ()
                {
                        Fraction pal = new Fraction (25, 1);
                        pal = pal.Invert ();
                        Assert.AreEqual ((double) 1 / 25, (double) pal, "1/25 should equal 0.04");

                        Fraction ntscinv = new Fraction (1, 30);
                        Assert.AreEqual ((double) 1/ 30, (double) ntscinv, "1/30 should equal 0.03333333(3)");
                }

                [Test]
                public void Fps ()
                {
                        Fraction pal = new Fraction (25, 1);
                        Assert.AreEqual (Time.FromNSeconds (40000000), pal.FpsFrameDuration (), "Borked frame duration");
                        Assert.AreEqual (Time.FromNSeconds (40000000), pal.FpsNormalizeTimeRnd (Time.FromNSeconds (21000000)));
                        Assert.AreEqual (Time.FromNSeconds (0), pal.FpsNormalizeTime(Time.FromNSeconds (21000000)));
                        Assert.AreEqual (1, pal.FpsFrameAtTimeRnd (Time.FromNSeconds (41000000)));
                        Assert.AreEqual (1, pal.FpsFrameAtTime (Time.FromNSeconds (41000000)));
                        Assert.AreEqual (1, pal.FpsFrameAtTime (Time.FromNSeconds (61000000)));
                        Assert.AreEqual (2, pal.FpsFrameAtTimeRnd (Time.FromNSeconds (61000000)));
                        Assert.AreEqual (Time.FromNSeconds (40000000), pal.FpsTimeAtFrame (1));
                }

                [Test]
                public void FpsDigitize ()
                {
                         Fraction pal = new Fraction (25, 1);
                         Fraction ntsc = new Fraction (30000, 1001);
                         Fraction some = new Fraction (31, 2);

                         Assert.AreEqual (16, some.FpsDigitize ());
                         Assert.AreEqual (25, pal.FpsDigitize ());
                         Assert.AreEqual (30, ntsc.FpsDigitize ());
                }

        }

}


text:
using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;
using WebAPI.Domain;
using WebAPI.Domain.InputOptions;

namespace WebAPI.API.ModelBindings
{
    public class GeocodeOptionsModelBinding : IModelBinder
    {
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            var keyValueModel = actionContext.Request.RequestUri.ParseQueryString();

            string suggestCount = keyValueModel["suggest"],
                   acceptScore = keyValueModel["acceptScore"],
                   format = keyValueModel["format"],
                   locator = keyValueModel["locators"],
                   spatialReference = keyValueModel["spatialReference"],
                   pobox = keyValueModel["pobox"],
                   scoreDifference = keyValueModel["scoreDifference"];

            var locatorType = LocatorType.All;
            var jsonFormat = JsonFormat.None;

            int.TryParse(string.IsNullOrEmpty(acceptScore) ? "70" : acceptScore, out var score);
            int.TryParse(string.IsNullOrEmpty(suggestCount) ? "0" : suggestCount, out var count);
            int.TryParse(string.IsNullOrEmpty(spatialReference) ? "26912" : spatialReference, out var wkid);
            bool.TryParse(string.IsNullOrEmpty(pobox) ? "false" : pobox, out var geocodePoBox);
            bool.TryParse(string.IsNullOrEmpty(scoreDifference) ? "false" : scoreDifference, out var calculateScoreDifference);

            try
            {
                jsonFormat =
                    (JsonFormat) Enum.Parse(typeof (JsonFormat), string.IsNullOrEmpty(format) ? "none" : format, true);
            } catch (Exception)
            {
                /*ie sometimes sends display value in text box.*/
            }

            try
            {
                locatorType =
                    (LocatorType)
                    Enum.Parse(typeof (LocatorType), string.IsNullOrEmpty(locator) ? "all" : locator, true);
            } catch (Exception)
            {
                /*ie sometimes sends display value in text box.*/
            }

            bindingContext.Model = new GeocodeOptions
            {
                SuggestCount = count,
                AcceptScore = score,
                JsonFormat = jsonFormat,
                Locators = locatorType,
                WkId = wkid,
                PoBox = geocodePoBox,
                ScoreDifference = calculateScoreDifference
            };

            return true;
        }
    }
}


text:
require('babel/register')({
    stage: 0
});

var app   = require('./src/backend/app');
var debug = require('debug')('server');

app.listen(app.get('port'), function() {
    debug('hdo-transcript-counts started on ' + app.get('port'));
});


text:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'signup',
  templateUrl: './signup.page.html',
  styleUrls: ['./signup.page.scss'],
})
export class SignupPage implements OnInit {

  signupForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {
    this.signupForm = this.formBuilder.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    });
  }

  ngOnInit() {

  }

  onSignup() {
    if (this.signupForm.valid) {
      const credential = this.signupForm.getRawValue();
      console.log(credential);
    }
  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RIAppDemo.DAL.EF;
using RIAPP.DataService.DomainService;
using RIAPP.DataService.DomainService.Types;

namespace RIAppDemo.BLL.Validators
{
    public class ProductValidator : BaseValidator<Product>
    {
        public override Task<IEnumerable<ValidationErrorInfo>> ValidateModelAsync(Product product,
            string[] modifiedField)
        {
            var errors = new LinkedList<ValidationErrorInfo>();
            if (Array.IndexOf(modifiedField, "Name") > -1 &&
                product.Name.StartsWith("Ugly", StringComparison.OrdinalIgnoreCase))
                errors.AddLast(new ValidationErrorInfo {fieldName = "Name", message = "Ugly name"});
            if (Array.IndexOf(modifiedField, "Weight") > -1 && product.Weight > 20000)
                errors.AddLast(new ValidationErrorInfo
                {
                    fieldName = "Weight",
                    message = "Weight must be less than 20000"
                });
            if (Array.IndexOf(modifiedField, "SellEndDate") > -1 && product.SellEndDate < product.SellStartDate)
                errors.AddLast(new ValidationErrorInfo
                {
                    fieldName = "SellEndDate",
                    message = "SellEndDate must be after SellStartDate"
                });
            if (Array.IndexOf(modifiedField, "SellStartDate") > -1 && product.SellStartDate > DateTime.Today)
                errors.AddLast(new ValidationErrorInfo
                {
                    fieldName = "SellStartDate",
                    message = "SellStartDate must be prior today"
                });
            if (ChangeType == ChangeType.Updated && Original.ModifiedDate >= product.ModifiedDate)
                errors.AddLast(new ValidationErrorInfo
                {
                    fieldName = "ModifiedDate",
                    message = "ModifiedDate must be greater than the previous ModifiedDate"
                });
            if (Array.IndexOf(modifiedField, "ProductNumber") > -1 && product.ProductNumber.StartsWith("00"))
                errors.AddLast(new ValidationErrorInfo
                {
                    fieldName = "ProductNumber",
                    message = "ProductNumber must not start from 00"
                });
            return Task.FromResult(errors.AsEnumerable());
        }
    }
}


text:
package com.senla.rakickaya.courseplanner.services;

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

import org.apache.log4j.Logger;

import com.senla.rakickaya.courseplanner.api.beans.ICourse;
import com.senla.rakickaya.courseplanner.api.beans.IStudent;
import com.senla.rakickaya.courseplanner.api.repositories.ICoursesRepository;
import com.senla.rakickaya.courseplanner.api.repositories.IStudentsRepository;
import com.senla.rakickaya.courseplanner.api.services.IStudentsService;
import com.senla.rakickaya.courseplanner.beans.Student;
import com.senla.rakickaya.courseplanner.csv.converters.ConverterFromCsv;
import com.senla.rakickaya.courseplanner.csv.converters.ConverterToCsv;
import com.senla.rakickaya.courseplanner.csv.converters.entities.CsvResponse;
import com.senla.rakickaya.courseplanner.exception.EntityNotFoundException;
import com.senla.rakickaya.courseplanner.repositories.CoursesRepository;
import com.senla.rakickaya.courseplanner.repositories.StudentsRepository;
import com.senla.rakickaya.courseplanner.utils.FileWorker;
import com.senla.rakickaya.courseplanner.utils.GeneratorId;
import com.senla.rakickaya.courseplanner.utils.ListWorker;

public class StudentsService implements IStudentsService {
	private static final Logger logger = Logger.getLogger(StudentsService.class.getName());

	private final IStudentsRepository mRepositoryStudents;
	private final ICoursesRepository mRepositoryCourses;

	public StudentsService() {
		super();
		this.mRepositoryStudents = StudentsRepository.getInstance();
		this.mRepositoryCourses = CoursesRepository.getInstance();
	}

	@Override
	public void addStudent(IStudent pStudent) {
		mRepositoryStudents.addStudent(pStudent);

	}

	@Override
	public void removeStudent(long id) throws EntityNotFoundException {
		IStudent removedStudent = mRepositoryStudents.removeStudent(id);
		if (removedStudent == null) {
			throw new EntityNotFoundException();
		}
		List<ICourse> courses = mRepositoryCourses.getCourses();
		for (int i = 0; i < courses.size(); i++) {
			ListWorker.removeItemById(courses.get(i).getStudents(), id);
		}
	}

	@Override
	public void updateStudent(IStudent pStudent) {
		mRepositoryStudents.updateStudent(pStudent);

	}

	@Override
	public IStudent getStudent(long pId) {
		return mRepositoryStudents.getStudent(pId);
	}

	@Override
	public List<IStudent> getStudents() {
		return mRepositoryStudents.getStudents();
	}

	@Override
	public void exportCSV(String path) {
		FileWorker worker = new FileWorker(path);
		List<String> csvEntities = new ArrayList<>();
		List<IStudent> students = mRepositoryStudents.getStudents();
		for (IStudent student : students) {
			try {
				String csvString;
				csvString = ConverterToCsv.convert(student);
				csvEntities.add(csvString);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}

		}
		worker.write(csvEntities);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void importCSV(String path) {
		final String COURSES = "courses";
		List<IStudent> students = new ArrayList<>();
		try {
			FileWorker worker = new FileWorker(path);
			List<String> list = worker.read();
			for (String str : list) {
				CsvResponse response = ConverterFromCsv.convert(str, Student.class);
				IStudent student = (IStudent) response.getEntity();
				Map<String, Object> map = response.getRelation();
				if (map.containsKey(COURSES)) {
					List<Long> idCourses = (List<Long>) map.get(COURSES);
					List<ICourse> courses = new ArrayList<>();
					for (Long idC : idCourses) {
						ICourse course = mRepositoryCourses.getCourse(idC);
						if (course != null) {
							courses.add(course);
						}
					}
					student.setCourses(courses);
				}
				students.add(student);
			}

		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		for (IStudent student : students) {
			if (!mRepositoryStudents.addStudent(student)) {
				mRepositoryStudents.updateStudent(student);
			} else {
				GeneratorId generatorId = GeneratorId.getInstance();
				long id = generatorId.getIdStudent();
				if (student.getId() > id) {
					generatorId.setIdStudent(id);
				}
			}
		}
	}

	@Override
	public int getTotalCountStudents() {
		return mRepositoryStudents.getStudents().size();
	}
}


text:
using namespace glm;

namespace Beans
{
  class Transform : public Component
  {
  public:
    Transform(GameObject* owner);

    REFLECT_CLASS;

    Property<vec3> position;
    Property<vec3> rotation;
    Property<vec3> scale;

    const mat4& GetMatrix();

    void RotateBy(vec3 eulerAngles);

    vec3 GetForwardDirection();

    quat GetRotationQuaternion() const;

  private:
    bool needsUpdate_;;
    mat4 matrix_;
    quat rotation_;
  };
}


text:
(function (beforeEach, module) {
    'use strict';

    beforeEach(module('404'));

}(window.beforeEach, window.module));


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

<title>Dialog</title>
<meta name="date" content="2014-01-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element

org.quickstart.api.annotations.dialog

Annotation Type Dialog

@Target(value=TYPE)
 @Retention(value=RUNTIME)
public @interface Dialog

Defines a managed dialog component, A dialog has a parent component
 accessible by @Ressource annotation, the Dialog should either extend a Node
 or define a viewLocation pointing to fxml.

Author:

Andy Moncsek

Required Element Summary

Required Elements

Modifier and Type
Required Element and Description

java.lang.String
id

The component id.

Optional Element Summary

Optional Elements

Modifier and Type
Optional Element and Description

java.lang.String
localeID

Represents the Locale ID. see:
 http://www.oracle.com/technetwork/java/javase/locales-137662.html

java.lang.String
resourceBundleLocation

Represents the location of your resource bundle file.

Scope
scope

Defines the Scope of the Dialog, default is Singleton.

java.lang.String
viewLocation

Represents the location (URI) of the declarative UI.

Element Detail

id

public abstract java.lang.String id

The component id.

Returns:

The component Id

scope

public abstract Scope scope

Defines the Scope of the Dialog, default is Singleton.

Returns:

The dialog Scope

Default:

org.quickstart.api.fragment.Scope.SINGLETON

viewLocation

public abstract java.lang.String viewLocation

Represents the location (URI) of the declarative UI.

Returns:

The view location (like bundle.messages)

Default:

""

resourceBundleLocation

public abstract java.lang.String resourceBundleLocation

Represents the location of your resource bundle file.

Returns:

The default resource bundle location (like bundle.messages)

Default:

""

localeID

public abstract java.lang.String localeID

Represents the Locale ID. see:
 http://www.oracle.com/technetwork/java/javase/locales-137662.html

Returns:

The default locale Id

Default:

""

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Field |

Required |

Optional

Detail:

Field |

Element


text:
---
collection: workshops
title: 'Lab 18: Get Data Before Loading View'
published: true
type: ionic
layout: workshoppost2
order: 18
lab: ionic
length: 5 minutes
date: 2016-05-18
todo: |
---

{% assign imagedir = "../images/router-resolve/" %}

{:.fake-h2}
Objective

When you are loading a view sometimes you want to have the data loaded immediately when the view is shown instead of switching to the view and then pulling data.

In a mobile application, this can make you application feel sluggish if you are not using a spinner or something to alert the user that something is happen.

With our application, we are showing a spinner for all of the http calls so we have eliminated that concern.

The functionality to pull data before showing a page is called resolve in the Angular UI-Router.

Key Concepts:

* Using UI-Router Resolve

{:.fake-h2}
Table of Contents

* TOC
{:toc}

## 18.0: Updating Projects Route

1. Open the www/js/config/app.config.js file
1. On the `projects` route we need to add the resolve parameter that will call the `ProjectsService.getProjects`

        .state('projects', {
          url: '/projects',
          views: {
            'tab-projects': {
              templateUrl: 'templates/projects.html',
              controller: 'ProjectsController as vm',
              resolve: {
                /* @ngInject */
                projects: function (ProjectsService) {
                   // will default to page 1 and size of 10
                  return ProjectsService.getProjects();
                }
              }
            }
          }
        })

1. If you don't already have ionic serve running, open a command prompt and run the command ionic serve
1. Now when the projects page loads, it will immediately have data instead of showing a blank page for a second as it gets data.

## 18.1: Updating Task Route

1. Open the www/js/config/app.config.js file
1. On the `tasks` route we need to add the resolve parameter that will call the `TasksService.getTasks`

        .state('tasks', {
          url: '/tasks/:projectId',
          params: {
            projectName: ""
          },
          views: {
            'tab-projects': {
              templateUrl: 'templates/tasks.html',
              controller: 'TasksController as vm',
              resolve: {
                /* @ngInject */
                tasks: function ($stateParams, TasksService) {
                  return TasksService.getTasks({ id: $stateParams.projectId });
                }
              }
            }
          }
        })

1. If you don't already have ionic serve running, open a command prompt and run the command ionic serve
1. Now when the tasks page loads, it will immediately have data instead of showing a blank page for a second as it gets data.

## Wrap-up

The resolve functionality can be very handy and give a better user experience when used correctly.  Just becareful not to abuse it.  You don't want to pull long data pulls before the view loads and the user is just waiting for your application to do something.


text:
{% load i18n %}{% autoescape off %}
{% trans "Hi" %} {{ user.first_name }},

{% trans "Click on the link below to create a new password for your account." %}

{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'accounts:password_reset_confirm' uidb64=uid token=token %}
{% endblock %}

{% trans "Thanks for using our site!" %}

{% endautoescape %}


text:
package com.klisly.bookbox.widget.progress;

public interface ProgressCancelListener {
    void onCancelProgress();
}


text:
package com.hp.autonomy.frontend.find.core.configuration;

import org.springframework.beans.factory.FactoryBean;

/**
 * Generates the password for encrypting the PostgresPassword
 */
public class TextEncryptorPasswordFactory implements FactoryBean<String> {

    // exception declared in external interface
    @SuppressWarnings("ProhibitedExceptionDeclared")
    @Override
    public String getObject() throws Exception {
        // don't change this or existing config files with encrypted text will stop working
        return "sdfjnhejsRUHR$uwhr843y5432rjsadfjsehR$HWENFU5y472345792348yJGNEO";
    }

    @Override
    public Class<?> getObjectType() {
        return String.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}


text:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-gwt' project.
// Copyright 2016 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// 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 de.esoco.gwt.shared;

import de.esoco.data.element.DataElement;

import java.io.Serializable;

import java.util.HashMap;
import java.util.Map;

/********************************************************************
 * This class defines a command for a {@link CommandService}. The type parameter
 * T defines the type of the input value for the command and the parameter R
 * stands for the datatype of the command result. New instances are created with
 * the factory method {@link #newInstance(String)} and are must to be defined as
 * static singleton constants which should have the same name as the instance.
 * The factory method enforces this by checking that not two commands have the
 * same name.
 *
 * @author eso
 */
public class Command<T extends DataElement<?>, R extends DataElement<?>>
	implements Serializable
{
	//~ Static fields/initializers ---------------------------------------------

	private static final long serialVersionUID = 1L;

	private static final Map<String, Command<?, ?>> aCommandRegistry =
		new HashMap<>();

	//~ Instance fields --------------------------------------------------------

	private String sName;

	//~ Constructors -----------------------------------------------------------

	/***************************************
	 * Default constructor for GWT serialization.
	 */
	Command()
	{
	}

	/***************************************
	 * Creates a new instance. Private, only used internally by the factory
	 * method {@link #newInstance(String)}.
	 *
	 * @param sName The name of the instance
	 */
	private Command(String sName)
	{
		this.sName = sName;
	}

	//~ Static methods ---------------------------------------------------------

	/***************************************
	 * Factory method that creates a new command instance.
	 *
	 * @param  sName The name of the new instance
	 *
	 * @return A new command instance
	 *
	 * @throws IllegalArgumentException If the given name is invalid or if a
	 *                                  command with the given name exists
	 *                                  already
	 */
	public static <T extends DataElement<?>, R extends DataElement<?>> Command<T, R> newInstance(
		String sName)
	{
		if (sName == null || sName.length() == 0)
		{
			throw new NullPointerException("Name must not be NULL");
		}

		Command<T, R> aCommand;

		if (aCommandRegistry.containsKey(sName))
		{
			throw new IllegalArgumentException("A command type with name " +
											   sName + " exists already");
		}
		else
		{
			aCommand = new Command<T, R>(sName);
			aCommandRegistry.put(sName, aCommand);
		}

		return aCommand;
	}

	//~ Methods ----------------------------------------------------------------

	/***************************************
	 * @see Object#equals(Object)
	 */
	@Override
	public boolean equals(Object rObject)
	{
		if (this == rObject)
		{
			return true;
		}

		if (rObject == null || getClass() != rObject.getClass())
		{
			return false;
		}

		return sName.equals(((Command<?, ?>) rObject).sName);
	}

	/***************************************
	 * Returns the name of this command.
	 *
	 * @return The command name
	 */
	public final String getName()
	{
		return sName;
	}

	/***************************************
	 * @see Object#hashCode()
	 */
	@Override
	public int hashCode()
	{
		return sName.hashCode() * 17;
	}

	/***************************************
	 * @see Object#toString()
	 */
	@Override
	public String toString()
	{
		return "Command[" + sName + "]";
	}

	/***************************************
	 * Returns the singleton command instance for the given name.
	 *
	 * @return The command instance for the given name
	 *
	 * @throws IllegalStateException If no matching command could be found
	 */
	Object readResolve()
	{
		Command<?, ?> rCommand = aCommandRegistry.get(sName);

		if (rCommand == null)
		{
			throw new IllegalStateException("Undefined command: " + sName);
		}

		return rCommand;
	}
}


text:
import {NgModule} from '@angular/core';
import {MatSnackBarModule} from '@angular/material-experimental/mdc-snack-bar';
import {RouterModule} from '@angular/router';
import {MdcSnackBarDemo} from './mdc-snack-bar-demo';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {MatButtonModule} from '@angular/material-experimental/mdc-button';
import {MatCheckboxModule} from '@angular/material-experimental/mdc-checkbox';
import {MatFormFieldModule} from '@angular/material-experimental/mdc-form-field';
import {MatInputModule} from '@angular/material-experimental/mdc-input';
import {MatSelectModule} from '@angular/material-experimental/mdc-select';

@NgModule({
  imports: [
    MatSnackBarModule,
    CommonModule,
    FormsModule,
    MatButtonModule,
    MatCheckboxModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    RouterModule.forChild([{path: '', component: MdcSnackBarDemo}]),
  ],
  declarations: [MdcSnackBarDemo],
})
export class MdcSnackBarDemoModule {
}


text:
class MapOverlaysSerializer

  def initialize(overlays, yml)
    @overlays = overlays
    @yml = yml
  end

  def serialize
    @overlays.map do |overlay|
      overlay_yml = @yml[:overlays][overlay[:id].to_sym]

      overlay.merge({
        title: overlay_yml.nil? ? '' : overlay_yml[:title],
        layers: get_layers(overlay)
      })
    end
  end

  private

  def get_layers(overlay)
    max_index = overlay[:layers].count-1

    (0..max_index).map{ |i| get_layer(overlay, i) }
  end

  def get_layer(overlay, index)
    layer = overlay[:layers][index]

    {
      id: "#{overlay[:id]}_#{index}",
      url: get_url(layer, overlay),
      color: overlay[:color],
      type: overlay[:type],
      isPoint: layer[:isPoint]
    }
  end

  def get_url (layer, overlay)
    overlay[:queryString] ?
      layer[:url] + overlay[:queryString] :
      layer[:url] + TILE_PATH
  end
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Class Auth
 * @property Student $student
 */
class Auth extends BaseController
{
    protected static $cssFile = 'login.css';

    /**
     * 学生登陆
     *
     * @return mixed
     */
    public function login()
    {
        $error = FALSE;

        if ($this->getInput()->method() == 'post') {
            $this->getValidation()->set_rules('name', 'Name', 'required');
            $this->getValidation()->set_rules('mobile', 'Mobile', 'required');

            $name = $this->getInput()->post('name');
            $mobile = $this->getInput()->post('mobile');

            if ($student = $this->student->login($name, $mobile)) {
                $studentCookie = base64_encode($student->name . '-' . $student->mobile);
                $this->getInput()->set_cookie(self::SESSION_STUDENT, $studentCookie, self::SESSION_STUDENT_TIMEOUT);

                redirect('student');
            }

            $error = TRUE;
        }

        return $this->render('登陆 - 学生', 'student/login', ['error' => $error]);
    }

    /**
     * 教师退出
     */
    public function logout()
    {
        if ($studentCookie = $this->getInput()->cookie(self::SESSION_STUDENT)) {
            $this->getInput()->set_cookie(self::SESSION_STUDENT, '', -1);
        }

        redirect('student/login');
    }
}


text:
<!DOCTYPE html>

    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Intervall-Bibliothek

                <input class="search" placeholder="Suche" class="form-control" />

                        Karteinummer
                        Jahr
                        Autoren
                        Beschreibung

                    |SECTIONS|


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="tr">
<context>
    <name>ConfigUI</name>
    <message>
        <location filename="../ConfigUI.ui" line="14"/>
        <source>Search Configuration</source>
        <translation>Arama Yapılandırması</translation>
    </message>
    <message>
        <location filename="../ConfigUI.ui" line="20"/>
        <source>Start Search:</source>
        <translation>Aramayı Başlat:</translation>
    </message>
    <message>
        <location filename="../ConfigUI.ui" line="39"/>
        <source>...</source>
        <translation>...</translation>
    </message>
    <message>
        <location filename="../ConfigUI.ui" line="48"/>
        <source>Excluded Directories</source>
        <translation>Hariç tutulan Dizinler</translation>
    </message>
    <message>
        <location filename="../ConfigUI.ui" line="119"/>
        <source>Save as Defaults</source>
        <translation>Varsayılanlar olarak kaydet</translation>
    </message>
    <message>
        <location filename="../ConfigUI.cpp" line="41"/>
        <source>Select Search Directory</source>
        <translation>Arama Dizinini Seç</translation>
    </message>
    <message>
        <location filename="../ConfigUI.cpp" line="54"/>
        <source>Exclude Directories</source>
        <translation>Dizinleri Hariç Tut</translation>
    </message>
</context>
<context>
    <name>MainUI</name>
    <message>
        <location filename="../MainUI.ui" line="14"/>
        <source>Search For...</source>
        <translation>Ara...</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="23"/>
        <source>Type to search</source>
        <translation>Aramak için yazın</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="30"/>
        <source>Configure search parameters</source>
        <translation>Arama parametrelerini yapılandır</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="40"/>
        <source>Stop Active Search</source>
        <translation>Etkin Aramayı Durdur</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="54"/>
        <source>Applications</source>
        <translation>Uygulamalar</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="64"/>
        <source>Files or Directories</source>
        <translation>Dosyalar ya da Dizinler</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="88"/>
        <source>Close</source>
        <translation>Kapat</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="108"/>
        <source>Launch Item</source>
        <translation>Öğeyi Başlat</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="119"/>
        <source>Save</source>
        <translation>Kaydet</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="122"/>
        <location filename="../MainUI.ui" line="125"/>
        <source>Save Screenshot</source>
        <translation>Ekran Görüntüsünü Kaydet</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="128"/>
        <source>Ctrl+S</source>
        <translation>Ctrl+S</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="133"/>
        <location filename="../MainUI.ui" line="136"/>
        <source>Quit</source>
        <translation>Çık</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="141"/>
        <source>Snap</source>
        <translation>Çek</translation>
    </message>
    <message>
        <location filename="../MainUI.ui" line="144"/>
        <source>Take new snapshot</source>
        <translation>Yeni görüntü al</translation>
    </message>
    <message>
        <location filename="../MainUI.cpp" line="31"/>
        <source>Esc</source>
        <translation>Çık</translation>
    </message>
    <message>
        <location filename="../MainUI.cpp" line="98"/>
        <source>Search: %1 -- Smart: %2</source>
        <translation>Ara: %1 -- Akıllı: %2</translation>
    </message>
    <message>
        <location filename="../MainUI.cpp" line="101"/>
        <source>Off</source>
        <translation>Kapalı</translation>
    </message>
    <message>
        <location filename="../MainUI.cpp" line="101"/>
        <source>On</source>
        <translation>Açık</translation>
    </message>
</context>
<context>
    <name>Worker</name>
    <message>
        <location filename="../Worker.cpp" line="42"/>
        <source>Searching: %1</source>
        <translation>Arıyor: %1</translation>
    </message>
    <message>
        <location filename="../Worker.cpp" line="64"/>
        <source>Starting Search: %1</source>
        <translation>Aramaya Başlıyor: %1</translation>
    </message>
    <message>
        <location filename="../Worker.cpp" line="112"/>
        <source>Search Finished</source>
        <translation>Arama Bitti</translation>
    </message>
</context>
<context>
    <name>XDGDesktopList</name>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="608"/>
        <source>Multimedia</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="609"/>
        <source>Development</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="610"/>
        <source>Education</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="611"/>
        <source>Games</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="612"/>
        <source>Graphics</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="613"/>
        <source>Network</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="614"/>
        <source>Office</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="615"/>
        <source>Science</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="616"/>
        <source>Settings</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="617"/>
        <source>System</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/>
        <source>Utility</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/>
        <source>Wine</source>
        <translation type="unfinished"></translation>
    </message>
    <message>
        <location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/>
        <source>Unsorted</source>
        <translation type="unfinished"></translation>
    </message>
</context>
</TS>


text:
oneview_server_profile_template 'ServerProfileTemplate1' do
  client node['oneview_test']['client']
  action :create
end


text:
package com.qf.android_zhihudaily.activity;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
import com.android.volley.Response.Listener;
import com.qf.android_zhihudaily.cache.BitmapCache;
import com.qf.android_zhihudaily.ndk.API;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.ScaleAnimation;
/**
 * »¶Ó½çÃæ:¶¯».
 * @author uaige
 *
 */
public class WelcomeActivity extends Activity implements AnimationListener{
	private NetworkImageView  imgStart;
	private RequestQueue mQueue;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);
		initView();
		initData();
	}
/**
 * ³õ'»¯½çÃæ
 */
	private void initData() {
		// TODO Auto-generated method stub
		imgStart=(NetworkImageView) findViewById(R.id.img_start);
	}
/**
 * ³õ'»¯Êý¾Ý
 */
	private void initView() {
		// TODO Auto-generated method stub
		mQueue = Volley.newRequestQueue(getApplicationContext());//ʹÓÃthisÐв»ÐÐ?
		mQueue.add(new JsonObjectRequest(Method.GET, API.getStartImgUrl(), null, new Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				try {
					String imgUrl = response.getString("img");
					imgStart.setImageUrl(imgUrl, new ImageLoader(mQueue, new BitmapCache()));

					// ͼƬ¶¯»
					Animation animation = new ScaleAnimation(1.0f, 1.2f, 1.0f, 1.2f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); // ½«Í¼Æ¬·Å´ó1.2±¶£¬´ÓÖÐÐÄ¿ªÊ¼Ëõ·Å
					animation.setDuration(2000); // ¶¯»³ÖÐøʱ¼ä
					animation.setFillAfter(true); // ¶¯»½áÊøºóÍ£ÁôÔÚ½áÊøµÄλÖÃ
					animation.setAnimationListener(WelcomeActivity.this); // Ìí¼Ó¶¯»¼àÌý
					imgStart.startAnimation(animation); // Æô¶¯¶¯»
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}, null));
	}
	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub

	}
	@Override
	public void onAnimationEnd(Animation animation) {
		// TODO Auto-generated method stub
		// ¶¯»½áÊøʱÌøתÖÁÊ×Ò³
				startActivity(new Intent(this, MainActivity.class));
	}
	@Override
	public void onAnimationRepeat(Animation animation) {
		// TODO Auto-generated method stub

	}
}