answer stringlengths 15 1.25M |
|---|
sap.ui.define([
"sap/ui/base/Object",
"sap/ui/model/Sorter"
], function (BaseObject, Sorter) {
"use strict";
return BaseObject.extend("md.flp.unit.line.line.unit.model.GroupSortState", {
/**
* Creates sorters and groupers for the master list.
* Since grouping also means sorting, this class modifies the viewmodel.
* If a user groups by a field, and there is a corresponding sort option, the option will be chosen.
* If a user ungroups, the sorting will be reset to the default sorting.
* @class
* @public
* @param {sap.ui.model.json.JSONModel} oViewModel the model of the current view
* @param {function} fnGroupFunction the grouping function to be applied
* @alias md.flp.unit.line.line.unit.model.GroupSortState
*/
constructor: function (oViewModel, fnGroupFunction) {
this._oViewModel = oViewModel;
this._fnGroupFunction = fnGroupFunction;
},
/**
* Sorts by Description, or by Rating
*
* @param {string} sKey - the key of the field used for grouping
* @returns {sap.ui.model.Sorter[]} an array of sorters
*/
sort: function (sKey) {
var sGroupedBy = this._oViewModel.getProperty("/groupBy");
if (sGroupedBy !== "None") {
// If the list is grouped, remove the grouping since the user wants to sort by something different
// Grouping only works if the list is primary sorted by the grouping - the first sorten contains a grouper function
this._oViewModel.setProperty("/groupBy", "None");
}
return [new Sorter(sKey, false)];
},
/**
* Groups by Rating, or resets the grouping for the key "None"
*
* @param {string} sKey - the key of the field used for grouping
* @returns {sap.ui.model.Sorter[]} an array of sorters
*/
group: function (sKey) {
var aSorters = [];
if (sKey === "Rating") {
// Grouping means sorting so we set the select to the same Entity used for grouping
this._oViewModel.setProperty("/sortBy", "Rating");
aSorters.push(
new Sorter("Rating", false,
this._fnGroupFunction.bind(this))
);
} else if (sKey === "None") {
// select the default sorting again
this._oViewModel.setProperty("/sortBy", "Description");
}
return aSorters;
}
});
}); |
import MutationObserver from "liquid-fire/mutation-observer";
import Ember from "ember";
export default Ember.Component.extend({
didInsertElement: function() {
var self = this;
// This prevents margin collapse
this.$().css({
border: '1px solid transparent',
margin: '-1px'
});
this.didMutate();
this.observer = new MutationObserver(function(mutations) { self.didMutate(mutations); });
this.observer.observe(this.get('element'), {
attributes: true,
subtree: true,
childList: true
});
this.$().bind('webkitTransitionEnd', function() { self.didMutate(); });
window.addEventListener('unload', function(){ self.willDestroyElement(); });
},
willDestroyElement: function() {
if (this.observer) {
this.observer.disconnect();
}
},
didMutate: function() {
Ember.run.next(this, function() { this._didMutate(); });
},
_didMutate: function() {
var elt = this.$();
if (!elt || !elt[0]) { return; }
this.set('measurements', measure(elt));
}
});
export function measure($elt) {
var width, height, literalWidth, literalHeight;
// if jQuery sees a zero dimension, it will temporarily modify the
// element's css to try to make its size measurable. But that's bad
// for us here, because we'll get an infinite recursion of mutation
// events. So we trap the zero case without hitting jQuery.
if ($elt[0].offsetWidth === 0) {
width = 0;
} else {
width = $elt.outerWidth();
}
if ($elt[0].offsetHeight === 0) {
height = 0;
} else {
height = $elt.outerHeight();
}
// We're tracking both jQuery's box-sizing dependent measurements
// and the literal CSS properties, because it's nice to get/set
// dimensions with jQuery and not worry about boz-sizing *but*
// Velocity needs the raw values.
literalWidth = parseInt($elt.css('width'),10);
literalHeight = parseInt($elt.css('height'),10);
return {
width: width,
height: height,
literalWidth: literalWidth,
literalHeight: literalHeight
};
} |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include "header/client.h"
#include "header/writeClientList.h"
#include "header/server.h"
char* buildMessage(Client* head, pid_t pid);
int countClients(Client* head);
/* Scorre la lista dei client individuando tutti i pid dei client connessi.
* Ottiene la stringa rappresentante la lista e la scrive sulla pipe corretta.*/
void writeClientList(Client *head, char* cmd) {
if (head == NULL) {
printf("\n *** NESSUN UTENTE CONNESSO ***");
} else {
pid_t pid;
getPidFromCmd(cmd, &pid); // acquisisco il pid del richiedente
char* list = buildMessage(head, pid);
int fd;
fd = getPipeByPid(pid, head); // trovo il riferimento alla pipe
if (fd != 0)
write(fd, list, strlen(list) + 1);
free(list);
}
}
char* buildMessage(Client* head, pid_t pid) {
int count = countClients(head);
/* alloco 20 caratteri per ogni pid (dovrebbero sempre bastare)
+ 50 caratteri per il messaggio iniziale*/
char* str = malloc(sizeof(char) * ((count * 20) + 50));
if (str == NULL)
exit(EXIT_FAILURE);
if (count == 1) {
sprintf(str, "Sei l'unico utente connesso:\nil tuo id e' %d.", pid);
} else {
sprintf(str, "Sono presenti %d clients:\n", count);
printf("\n*** LISTA UTENTI CONNESSI ***");
do {
printf("\n %d", head->pid);
char temp[40];
if (head->pid == pid)
sprintf(temp, "%d (il tuo id)\n", head->pid); // il tuo pid
else
sprintf(temp, "%d\n", head->pid); // converto il pid in stringa
strcat(str, temp);
head = head->next;
} while (head != NULL);
}
return str;
}
/*
* Conta il numero di clients connessi
*/
int countClients(Client* head) {
int count = 0;
do {
count++;
head = head->next;
} while (head != NULL);
return count;
} |
from core.himesis import Himesis, <API key>
import uuid
class <API key>(<API key>):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model <API key>
"""
# Flag this instance as compiled now
self.is_compiled = True
super(<API key>, self).__init__(name='<API key>', num_nodes=0, edges=[])
# Add the edges
self.add_edges([])
# Set the graph attributes
self["mm__"] = ['<API key>', 'MoTifRule']
self["MT_constraint__"] = """return True"""
self["name"] =
self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'<API key>')
self["equations"] = []
# Set the node attributes
# define evaluation methods for each apply class.
def constraint(self, PreNode, graph):
return True |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace VkApi.Wrapper.Objects
{
public class BaseLinkRating
{
<summary>
Count of reviews
</summary>
[JsonProperty("reviews_count")]
public int ReviewsCount { get; set; }
<summary>
Count of stars
</summary>
[JsonProperty("stars")]
public double Stars { get; set; }
}
} |
Hello,
<strong>Aaron!</strong> |
// Mouse Class //
export default class Mouse {
constructor(element) {
this.element = element || window;
this.x = ~~(document.documentElement.clientWidth, window.innerWidth || 0) / 2;
this.y = ~~(document.documentElement.clientHeight, window.innerHeight || 0) / 2;
this.pointer = this.pointer.bind(this);
this.getCoordinates = this.getCoordinates.bind(this);
this.events = ['mouseenter', 'mousemove'];
this.events.forEach((eventName) => {
this.element.addEventListener(eventName, this.getCoordinates);
});
}
getCoordinates(event) {
event.preventDefault();
const x = event.pageX;
const y = event.pageY;
this.x = x;
this.y = y;
}
pointer() {
return {
x: this.x,
y: this.y
};
}
} |
Package.describe({
summary: "Lets users upload files to Amazon S3",
version: '0.1.0',
name: "postvideo"
});
Package.onUse(function (api) {
api.use(['templating', 'telescope-base', '<API key>'], ['client','server']);
api.add_files([
'lib/client/templates/post_video.html',
'lib/client/post_video.js'
], ['client','server']);
}); |
/* eslint-disable */
var HTMLImports = {};
/**
* @param {function()=} callback
*/
HTMLImports.whenReady = function(callback) {};
/**
* Returns the import document containing the element.
* @param {!Node} element
* @return {?HTMLLinkElement|?Document|undefined}
*/
HTMLImports.importForElement = function(element) {};
window.HTMLImports = HTMLImports;
var ShadyDOM = {};
ShadyDOM.inUse;
ShadyDOM.flush = function() {};
/**
* @param {!Node} target
* @param {function(Array<MutationRecord>, MutationObserver)} callback
* @return {MutationObserver}
*/
ShadyDOM.observeChildren = function(target, callback) {};
/**
* @param {MutationObserver} observer
*/
ShadyDOM.unobserveChildren = function(observer) {};
/**
* @param {Node} node
*/
ShadyDOM.patch = function(node) {};
/**
* @param {!ShadowRoot} shadowroot
*/
ShadyDOM.flushInitial = function(shadowroot) {};
window.ShadyDOM = ShadyDOM;
var WebComponents = {};
window.WebComponents = WebComponents;
/** @type {Element} */
HTMLElement.prototype._activeElement;
/**
* @param {HTMLTemplateElement} template
*/
HTMLTemplateElement.decorate = function(template){};
/**
* @param {function(function())} cb callback
*/
<API key>.prototype.<API key> = function(cb){};
/**
* @param {string} cssText
*/
CSSStyleSheet.prototype.replaceSync = function(cssText) {}; |
.calendar {
border-width: 1px;
border-style: solid;
padding: 1px;
overflow: hidden;
font-size: 12px;
}
.calendar table {
border-collapse: separate;
font-size: 12px;
width: 100%;
height: 100%;
}
.calendar-noborder {
border: 0;
}
.calendar-header {
position: relative;
height: 22px;
}
.calendar-title {
text-align: center;
height: 22px;
}
.calendar-title span {
position: relative;
display: inline-block;
top: 2px;
padding: 0 3px;
height: 18px;
line-height: 18px;
cursor: pointer;
-moz-border-radius: 5px 5px 5px 5px;
-<API key>: 5px 5px 5px 5px;
border-radius: 5px 5px 5px 5px;
}
.calendar-prevmonth,
.calendar-nextmonth,
.calendar-prevyear,
.calendar-nextyear {
position: absolute;
top: 50%;
margin-top: -7px;
width: 14px;
height: 14px;
cursor: pointer;
font-size: 1px;
-moz-border-radius: 5px 5px 5px 5px;
-<API key>: 5px 5px 5px 5px;
border-radius: 5px 5px 5px 5px;
}
.calendar-prevmonth {
left: 20px;
background: url('../../../../../../32guide/template/js/easyui/themes/default/images/calendar_arrows.png') no-repeat -18px -2px;
}
.calendar-nextmonth {
right: 20px;
background: url('../../../../../../32guide/template/js/easyui/themes/default/images/calendar_arrows.png') no-repeat -34px -2px;
}
.calendar-prevyear {
left: 3px;
background: url('../../../../../../32guide/template/js/easyui/themes/default/images/calendar_arrows.png') no-repeat -1px -2px;
}
.calendar-nextyear {
right: 3px;
background: url('../../../../../../32guide/template/js/easyui/themes/default/images/calendar_arrows.png') no-repeat -49px -2px;
}
.calendar-body {
position: relative;
}
.calendar-body th,
.calendar-body td {
text-align: center;
}
.calendar-day {
border: 0;
padding: 1px;
cursor: pointer;
-moz-border-radius: 5px 5px 5px 5px;
-<API key>: 5px 5px 5px 5px;
border-radius: 5px 5px 5px 5px;
}
.<API key> {
opacity: 0.3;
filter: alpha(opacity=30);
}
.calendar-menu {
position: absolute;
top: 0;
left: 0;
width: 180px;
height: 150px;
padding: 5px;
font-size: 12px;
display: none;
overflow: hidden;
}
.<API key> {
text-align: center;
padding-bottom: 5px;
}
.calendar-menu-year {
width: 40px;
text-align: center;
border-width: 1px;
border-style: solid;
margin: 0;
padding: 2px;
font-weight: bold;
}
.calendar-menu-prev,
.calendar-menu-next {
display: inline-block;
width: 21px;
height: 21px;
vertical-align: top;
cursor: pointer;
-moz-border-radius: 5px 5px 5px 5px;
-<API key>: 5px 5px 5px 5px;
border-radius: 5px 5px 5px 5px;
}
.calendar-menu-prev {
margin-right: 10px;
background: url('../../../../../../32guide/template/js/easyui/themes/default/images/calendar_arrows.png') no-repeat 2px 2px;
}
.calendar-menu-next {
margin-left: 10px;
background: url('../../../../../../32guide/template/js/easyui/themes/default/images/calendar_arrows.png') no-repeat -45px 2px;
}
.calendar-menu-month {
text-align: center;
cursor: pointer;
font-weight: bold;
-moz-border-radius: 5px 5px 5px 5px;
-<API key>: 5px 5px 5px 5px;
border-radius: 5px 5px 5px 5px;
}
.calendar-body th,
.calendar-menu-month {
color: #4d4d4d;
}
.calendar-day {
color: #000000;
}
.calendar-sunday {
color: #CC2222;
}
.calendar-saturday {
color: #00ee00;
}
.calendar-today {
color: #0000ff;
}
.calendar-menu-year {
border-color: #95B8E7;
}
.calendar {
border-color: #95B8E7;
}
.calendar-header {
background: #E0ECFF;
}
.calendar-body,
.calendar-menu {
background: #ffffff;
}
.calendar-body th {
background: #F4F4F4;
}
.calendar-hover,
.calendar-nav-hover,
.calendar-menu-hover {
background-color: #eaf2ff;
color: #000000;
}
.calendar-hover {
border: 1px solid #b7d2ff;
padding: 0;
}
.calendar-selected {
background-color: #FBEC88;
color: #000000;
border: 1px solid #E2C608;
padding: 0;
} |
using System;
using System.Collections.Generic;
using <API key>;
using MagicLockScreen_UI.ViewModels;
using NoteOne_Core.UI.Common;
using Windows.UI.Xaml.Controls;
using ConstKeys = NoteOne_Utility.ConstKeys;
namespace MagicLockScreen_UI
{
<summary>
A page that displays a grouped collection of items.
</summary>
public sealed partial class <API key> : LayoutAwarePage
{
public <API key>()
{
InitializeComponent();
}
<summary>
Populates the page with content passed during navigation. Any saved state is also
provided when recreating a page from a prior session.
</summary>
<param name="navigationParameter">
The parameter value passed to
<see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested.
</param>
<param name="pageState">
A dictionary of state preserved by this page during an earlier
session. This will be null the first time a page is visited.
</param>
protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// For optimaizing the loading performence
// move data initialization into main page
if (!Bootstrapper.CurrentBootstrapper.IsDataInitialized)
{
await Bootstrapper.CurrentBootstrapper.InitializeData();
}
DefaultViewModel = new <API key>(this, pageState);
// Show Help guideline at first run time
if ((bool) AppSettings.Instance[AppSettings.NEED_HELP])
{
var help = new FullScreenPopup(ConstKeys.HELP_KEY, new HelpContent());
help.Show();
AppSettings.Instance[AppSettings.NEED_HELP] = false;
await NoteOne_Utility.AppSettings.SaveSettings(AppSettings.Instance);
}
// If main page init count can mod 10, show rate and review prompt
await ApplicationHelper.<API key>();
}
}
} |
package io.letsplay.saf.server.metrics;
import io.letsplay.saf.server.ListType;
import java.util.Date;
import java.util.List;
/**
* State of the game at a certain point in time.
*/
public class GameProgress {
public Date sessionStarted;
public Date gameStarted;
public Date levelStarted;
public Date waveStarted;
public int numberOfGames;
public String level;
// public String environment; // e.g. oily, foggy, high gravitation
public int wave;
@ListType(Npc.class)
public List<Npc> npcs;
} |
#include "esther/valueobject.h"
#include "esther/esther.h"
#include "esther/string.h"
Object *<API key>(Esther *es, char value) {
return ValueObject_new_var(es, Variant_char(value));
}
Object *ValueObject_new_int(Esther *es, int64_t value) {
return ValueObject_new_var(es, Variant_int(value));
}
Object *<API key>(Esther *es, double value) {
return ValueObject_new_var(es, Variant_real(value));
}
Object *ValueObject_new_var(Esther *es, Variant value) {
Object *self = gc_alloc(sizeof(ValueObject));
ValueObject_init(es, self, value);
return self;
}
static ObjectVTable <API key> = {
.base = {
.base = {
.mapOnRefs = <API key> },
.finalize = <API key> },
.toString = <API key>,
.inspect = <API key>,
.equals = <API key>,
.less = <API key>,
.isTrue = <API key>,
.clone = <API key>
};
void ValueObject_init(Esther *es, Object *self, Variant value) {
Object_init(es, self, TValueObject, <API key>(es, value.type));
as_ValueObject(self)->value = value;
*(void **) self = &<API key>;
}
Variant <API key>(Object *self) {
return as_ValueObject(self)->value;
}
void <API key>(Object *self, Variant value) {
as_ValueObject(self)->value = Variant_convertTo(value, Variant_getType(value));
}
Object *<API key>(Esther *es, Object *self) {
return String_new_move(es, Variant_toString(as_ValueObject(self)->value));
}
Object *<API key>(Esther *es, Object *self) {
return String_new_move(es, Variant_inspect(as_ValueObject(self)->value));
}
bool <API key>(Object *self, Object *obj) {
return Object_getType(obj) == TValueObject ? Variant_eq(as_ValueObject(self)->value, as_ValueObject(obj)->value) : <API key>(self, obj);
}
bool <API key>(Object *self, Object *obj) {
return Object_getType(obj) == TValueObject ? Variant_lt(as_ValueObject(self)->value, as_ValueObject(obj)->value) : Object_virtual_less(self, obj);
}
Object *<API key>(Esther *es, Object *self) {
Object *clone = ValueObject_new_var(es, as_ValueObject(self)->value);
<API key>(self, clone);
return clone;
}
Object *<API key>(Esther *es, VariantType type) {
switch (type) {
case CharVariant:
return <API key>(es, cstr_to_id("Char"));
case IntVariant:
return <API key>(es, cstr_to_id("Int"));
case RealVariant:
return <API key>(es, cstr_to_id("Float"));
default:
return NULL;
}
} |
<?php
return array (
'id' => 'inew_v3e_ver1',
'fallback' => '<API key>',
'capabilities' =>
array (
'mobile_browser' => 'Android Webkit',
'model_name' => 'V3-E',
'brand_name' => 'iNew',
'<API key>' => '111',
'<API key>' => '63',
'resolution_width' => '720',
'resolution_height' => '1280',
'nfc_support' => 'true',
),
); |
export interface SchemaExtension {
description: string;
id: string;
owner: string;
properties: <API key>[];
status: string;
targetTypes: string[];
}
export interface <API key> {
name: string;
type: string;
} |
<md-card style="width: 50%;margin-left: 25%;margin-top: 10%;background-color: white">
<md-input-container>
<label>Contraseña Actual</label>
<input type="password" ng-init="currentPass = ''" ng-model="currentPass">
</md-input-container>
<md-input-container>
<label>Nueva Contraseña</label>
<input type="password" ng-init="newPass = ''" ng-model="newPass">
</md-input-container>
<md-input-container>
<label>Confirmar Contraseña</label>
<input type="password" ng-init="newPass2 = ''" ng-model="newPass2">
</md-input-container>
<div layout="row" layout-align="center">
<md-button ng-click="update()" ng-disabled="currentPass == '' || newPass == '' || newPass2 == '' || newPass != newPass2 " class="md-raised md-primary" style="width: 200px">Guardar</md-button>
</div>
</md-card> |
#pragma once
#include "elloop/inc.h"
NS_BEGIN(elloop);
struct Size
{
Size(float width = 0, float height = 0) :
_width(width),
_height(height)
{}
float _width;
float _height;
};
NS_END(elloop); |
using CrawlerNet.Models;
using CrawlerNet.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CrawlerNet.Utilities
{
public static class ConfigManager
{
public static void SetConfig(Config config)
{
var baseConfig = Properties.Settings.Default;
baseConfig.crawlTimeoutSeconds = config.crawlTimeoutSeconds;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.maxCrawlDepth = config.maxCrawlDepth;
baseConfig.<API key> = config.<API key>;
baseConfig.maxMemoryUsageInMb = config.maxMemoryUsageInMb;
baseConfig.maxPageSizeInBytes = config.maxPageSizeInBytes;
baseConfig.maxPagesToCrawl = config.maxPagesToCrawl;
baseConfig.<API key> = config.<API key>;
baseConfig.maxRetryCount = config.maxRetryCount;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.<API key> = config.<API key>;
baseConfig.userAgentString = config.userAgentString;
baseConfig.Save();
}
public static Config GetConfig()
{
var baseConfig = Properties.Settings.Default;
var config = new Config();
config.crawlTimeoutSeconds = baseConfig.crawlTimeoutSeconds;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.maxCrawlDepth = baseConfig.maxCrawlDepth;
config.<API key> = baseConfig.<API key>;
config.maxMemoryUsageInMb = baseConfig.maxMemoryUsageInMb;
config.maxPageSizeInBytes = baseConfig.maxPageSizeInBytes;
config.maxPagesToCrawl = baseConfig.maxPagesToCrawl;
config.<API key> = baseConfig.<API key>;
config.maxRetryCount = baseConfig.maxRetryCount;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.<API key> = baseConfig.<API key>;
config.userAgentString = baseConfig.userAgentString;
return config;
}
}
} |
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';
import ListItem from '@material-ui/core/ListItem';
import Button from '@material-ui/core/Button';
import Collapse from '@material-ui/core/Collapse';
import Link from 'docs/src/modules/components/Link';
const useStyles = makeStyles(theme => ({
item: {
display: 'block',
paddingTop: 0,
paddingBottom: 0,
},
itemLeaf: {
display: 'flex',
paddingTop: 0,
paddingBottom: 0,
},
button: {
letterSpacing: 0,
justifyContent: 'flex-start',
textTransform: 'none',
width: '100%',
},
buttonLeaf: {
letterSpacing: 0,
justifyContent: 'flex-start',
textTransform: 'none',
width: '100%',
fontWeight: theme.typography.fontWeightRegular,
'&.depth-0': {
fontWeight: theme.typography.fontWeightMedium,
},
},
active: {
color: theme.palette.primary.main,
fontWeight: theme.typography.fontWeightMedium,
},
}));
function AppDrawerNavItem(props) {
const {
children,
depth,
href,
onClick,
openImmediately = false,
topLevel = false,
title,
other
} = props;
const classes = useStyles();
const [open, setOpen] = React.useState(openImmediately);
const handleClick = () => {
setOpen(oldOpen => !oldOpen);
};
const style = {
paddingLeft: 8 * (3 + 2 * depth),
};
if (href) {
return (
<ListItem className={classes.itemLeaf} disableGutters {...other}>
<Button
component={Link}
naked
activeClassName={`drawer-active ${classes.active}`}
href={href}
className={clsx(classes.buttonLeaf, `depth-${depth}`)}
disableTouchRipple
onClick={onClick}
style={style}
>
{title}
</Button>
</ListItem>
);
}
return (
<ListItem className={classes.item} disableGutters {...other}>
<Button
classes={{
root: classes.button,
label: topLevel ? 'algolia-lvl0' : '',
}}
onClick={handleClick}
style={style}
>
{title}
</Button>
<Collapse in={open} timeout="auto" unmountOnExit>
{children}
</Collapse>
</ListItem>
);
}
AppDrawerNavItem.propTypes = {
children: PropTypes.node,
depth: PropTypes.number.isRequired,
href: PropTypes.string,
onClick: PropTypes.func,
openImmediately: PropTypes.bool,
title: PropTypes.string.isRequired,
topLevel: PropTypes.bool,
};
export default AppDrawerNavItem; |
package org.indiarose.backend.activity;
import org.indiarose.R;
import org.indiarose.lib.AppData;
import org.indiarose.lib.view.IndiagramView;
import afzkl.development.colorpickerview.dialog.ColorPickerDialog;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.<API key>;
public class BackgroundColor extends Activity implements OnClickListener {
protected static final String OK = "ok";
protected static final String CANCEL = "cancel";
protected static final int COLOR_TOP = 1;
protected static final int COLOR_BOTTOM = 2;
protected int m_topColor = 0;
protected int m_bottomColor = 0;
protected int m_topSize = 0;
protected boolean active = false;
ViewGroup leftLayout;
ViewGroup rightLayout;
View topArea;
View bottomArea;
View okButton;
View cancelButton;
Spinner spinner;
boolean spinnerInitialised = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<API key>);
AppData.current_activity = this;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ajouterVues();
ajouterListeners();
charger();
}
protected void ajouterVues() {
leftLayout = (ViewGroup) findViewById(R.id.<API key>);
leftLayout = (ViewGroup) findViewById(R.id.<API key>);
topArea = findViewById(R.id.<API key>);
bottomArea = findViewById(R.id.<API key>);
okButton = findViewById(R.id.<API key>);
cancelButton = findViewById(R.id.<API key>);
spinner = (Spinner) findViewById(R.id.<API key>);
}
protected void ajouterListeners() {
topArea.setOnClickListener(this);
bottomArea.setOnClickListener(this);
okButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
}
protected void charger() {
m_topColor = AppData.settings.<API key>;
m_bottomColor = AppData.settings.<API key>;
m_topSize = AppData.settings.heightSelectionArea;
System.out.println(m_topColor + " " + m_bottomColor + " " + m_topSize);
refreshArea();
}
public void <API key>(boolean hasFocus) {
remplirSpinner();
refreshArea();
}
protected void remplirSpinner() {
if (!spinnerInitialised) {
spinnerInitialised = true;
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item);
int minHeight = (int) ((IndiagramView.getDefaultHeight() *1.2)
/ getWindow().getDecorView().getHeight() * 100);
// int maxHeight = 100 - minHeight;
int maxHeight = 95 - minHeight;
int current = 0;
for (int i = minHeight; i <= maxHeight; ++i) {
if (i == AppData.settings.heightSelectionArea) {
current = i - minHeight;
}
adapter.add("" + i + "%");
}
spinner.setAdapter(adapter);
spinner.setSelection(current);
spinner.<API key>(new <API key>() {
public void onItemSelected(AdapterView<?> _parent, View _view,
int _pos, long _id) {
String tmp = ((TextView) _view).getText().toString();
tmp = tmp.substring(0, tmp.length() - 1);
m_topSize = Integer.parseInt(tmp);
refreshArea();
}
public void onNothingSelected(AdapterView<?> _parent) {
}
});
}
}
protected void refreshArea() {
topArea.setBackgroundColor(m_topColor);
bottomArea.setBackgroundColor(m_bottomColor);
int height = leftLayout.getHeight();
int topHeight = (int) (height * (m_topSize / 100.0));
int bottomHeight = height - topHeight;
ViewGroup.LayoutParams top = topArea.getLayoutParams();
top.height = topHeight;
topArea.setLayoutParams(top);
ViewGroup.LayoutParams bottom = bottomArea.getLayoutParams();
bottom.height = bottomHeight;
bottomArea.setLayoutParams(bottom);
/*
* m_topArea.setMinimumHeight(topHeight);
* m_bottomArea.setMinimumHeight(bottomHeight);
*
*
*
* m_topArea.measure(m_topArea.getWidth(), topHeight);
* m_bottomArea.measure(m_bottomArea.getWidth(), bottomHeight);
*/
}
// Color picker
public void onClick(View v) {
switch (v.getId()) {
case R.id.<API key>: {
if (!active) {
active = true;
final ColorPickerDialog colorDialog = new ColorPickerDialog(
this, m_topColor);
colorDialog.<API key>(false);
colorDialog.setTitle(getString(R.string.chooseColor));
colorDialog.setButton(DialogInterface.BUTTON_POSITIVE,
getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
m_topColor = colorDialog.getColor();
refreshArea();
active = false;
}
});
colorDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// Nothing to do here.
active = false;
}
});
colorDialog.show();
}
}
break;
case R.id.<API key>:
{
if (!active) {
active = true;
final ColorPickerDialog colorDialog = new ColorPickerDialog(
this, m_bottomColor);
colorDialog.<API key>(false);
colorDialog.setTitle(getString(R.string.chooseColor));
colorDialog.setButton(DialogInterface.BUTTON_POSITIVE,
getString(android.R.string.ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
active = false;
m_bottomColor = colorDialog.getColor();
refreshArea();
}
});
colorDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
getString(android.R.string.cancel),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
active = false;
// Nothing to do here.
}
});
colorDialog.show();
}
}
break;
case R.id.<API key>:
AppData.settings.<API key> = m_topColor;
AppData.settings.<API key> = m_bottomColor;
AppData.settings.heightSelectionArea = m_topSize;
AppData.settingsChanged();
onBackPressed();
break;
case R.id.<API key>:
onBackPressed();
break;
}
}
@Override
public void onBackPressed() {
Intent i = new Intent(this, AppSettings.class);
startActivity(i);
finish();
}
} |
<?php
namespace OroCRM\Bundle\MagentoBundle\ImportExport\Strategy\StrategyHelper;
use Doctrine\ORM\UnitOfWork;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Symfony\Component\Security\Core\Util\ClassUtils;
use Oro\Bundle\ImportExportBundle\Strategy\Import\<API key>;
class DoctrineHelper
{
/** @var <API key> */
protected $strategyHelper;
public function __construct(<API key> $strategyHelper)
{
$this->strategyHelper = $strategyHelper;
}
/**
* @param mixed $entity New entity
* @param string $entityName Class name
* @param string|array $criteria Fieldname to find existing entity
* @param array $excludedProperties Excluded properties
*
* @return mixed
*/
public function <API key>($entity, $entityName, $criteria = 'id', $excludedProperties = [])
{
if (is_array($criteria)) {
$existingEntity = $this->getEntityByCriteria($criteria, $entity);
} else {
$existingEntity = $this->getEntityOrNull($entity, $criteria, $entityName);
}
if ($existingEntity) {
$this->strategyHelper->importEntity($existingEntity, $entity, $excludedProperties);
$entity = $existingEntity;
} else {
/* @var ClassMetadataInfo $metadata */
$metadata = $this->getEntityManager($entityName)
->getClassMetadata($entityName);
$identifier = $metadata-><API key>();
$setterMethod = 'set' . ucfirst($identifier);
if (method_exists($entity, $setterMethod)) {
$entity->$setterMethod(null);
} elseif (property_exists($entity, $identifier)) {
$reflection = new \ReflectionProperty(ClassUtils::getRealClass($entity), $identifier);
$reflection->setAccessible(true);
$reflection->setValue($entity, null);
}
}
return $entity;
}
/**
* @param mixed $entity
* @param string $entityIdField
* @param string|null $entityClass
*
* @return object|null
*/
public function getEntityOrNull($entity, $entityIdField, $entityClass = null)
{
$existingEntity = null;
$entityId = $entity->{'get' . ucfirst($entityIdField)}();
if (!$entityClass) {
$entityClass = ClassUtils::getRealClass($entity);
}
if ($entityId) {
$existingEntity = $this->getEntityByCriteria([$entityIdField => $entityId], $entityClass);
}
return $existingEntity ? : null;
}
/**
* @param array $criteria
* @param object|string $entity object to get class from or class name
*
* @return object
*/
public function getEntityByCriteria(array $criteria, $entity)
{
$entityClass = ClassUtils::getRealClass($entity);
return $this->getEntityRepository($entityClass)->findOneBy($criteria);
}
/**
* @param $entityName
*
* @return \Doctrine\ORM\EntityManager
*/
public function getEntityManager($entityName)
{
return $this->strategyHelper->getEntityManager($entityName);
}
/**
* @param string $entityName
*
* @return EntityRepository
*/
public function getEntityRepository($entityName)
{
return $this->strategyHelper->getEntityManager($entityName)->getRepository($entityName);
}
/**
* @param $entity
*
* @return object
*/
public function merge($entity)
{
/*
* Reload entity instead merge due to strange behavior with spl_object_hash
* EntityManager#find has own cache, so query will be performed only once per batch (until EntityManager#clear)
*/
$cn = ClassUtils::getRealClass($entity);
$em = $this->getEntityManager($cn);
if ($em->getUnitOfWork()->getEntityState($entity) !== UnitOfWork::STATE_MANAGED) {
$id = $em->getClassMetadata($cn)->getIdentifierValues($entity);
if ($id) {
$entity = $em->find($cn, $id);
}
}
return $entity;
}
} |
class <API key> < ActiveRecord::Migration[5.0]
def change
add_reference :hardwares, :equipment_type, foreign_key: true
end
end |
\section{File List}
Here is a list of all files with brief descriptions\+:\begin{DoxyCompactList}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/\hyperlink{main_8cpp}{main.\+cpp} }{\pageref{main_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/\hyperlink{vict_8cpp}{vict.\+cpp} }{\pageref{vict_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/\hyperlink{body_8cpp}{body.\+cpp} }{\pageref{body_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/\hyperlink{body_8h}{body.\+h} }{\pageref{body_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/engine/\hyperlink{engine_8cpp}{engine.\+cpp} }{\pageref{engine_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/engine/\hyperlink{engine_8h}{engine.\+h} }{\pageref{engine_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/engine/encryption/\hyperlink{encryption_8cpp}{encryption.\+cpp} }{\pageref{encryption_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/engine/encryption/\hyperlink{encryption_8h}{encryption.\+h} }{\pageref{encryption_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/path/\hyperlink{path_8cpp}{path.\+cpp} }{\pageref{path_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/path/\hyperlink{path_8h}{path.\+h} }{\pageref{path_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/search/\hyperlink{search_8cpp}{search.\+cpp} }{\pageref{search_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/body/search/\hyperlink{search_8h}{search.\+h} }{\pageref{search_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/fmanip/\hyperlink{fmanip_8cpp}{fmanip.\+cpp} }{\pageref{fmanip_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/fmanip/\hyperlink{fmanip_8h}{fmanip.\+h} }{\pageref{fmanip_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{log_8cpp}{log.\+cpp} }{\pageref{log_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{log_8h}{log.\+h} }{\pageref{log_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{pow_8cpp}{pow.\+cpp} }{\pageref{pow_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{pow_8h}{pow.\+h} }{\pageref{pow_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{root_8cpp}{root.\+cpp} }{\pageref{root_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{root_8h}{root.\+h} }{\pageref{root_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{trig_8cpp}{trig.\+cpp} }{\pageref{trig_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/math/\hyperlink{trig_8h}{trig.\+h} }{\pageref{trig_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/payload/\hyperlink{payload_8cpp}{payload.\+cpp} }{\pageref{payload_8cpp}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/payload/\hyperlink{payload_8h}{payload.\+h} }{\pageref{payload_8h}}{}
\item\contentsline{section}{/home/superuser/\+Snowball/snowball/\+Tests/\hyperlink{_tests_2vict_8cpp}{vict.\+cpp} }{\pageref{_tests_2vict_8cpp}}{}
\end{DoxyCompactList} |
const bodyParser = require('body-parser').json();
const express = require('express');
const Job = require('../models/job.model');
const Router = express.Router;
const jobRouter = Router();
jobRouter
.get('/', (req, res, next) => {
Job.find()
.then(jobs => res.send(jobs))
.catch(next);
})
.post('/', bodyParser, (req, res, next) => {
return new Job(req.body).save()
.then(job => {
res.send(job);
})
.catch(next);
});
module.exports = jobRouter; |
using System;
namespace Microsoft.MixedReality.Toolkit.Utilities.Gltf.Schema
{
<summary>
Joints and matrices defining a skin.
https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/schema/skin.schema.json
</summary>
[Serializable]
public class GltfSkin : <API key>
{
<summary>
The index of the accessor containing the floating-point 4x4 inverse-bind matrices.
The default is that each matrix is a 4x4 Identity matrix, which implies that inverse-bind
matrices were pre-applied.
</summary>
public int inverseBindMatrices = -1;
<summary>
The index of the node used as a skeleton root.
When undefined, joints transforms resolve to scene root.
</summary>
public int skeleton = -1;
<summary>
Indices of skeleton nodes, used as joints in this skin. The array length must be the
same as the `count` property of the `inverseBindMatrices` accessor (when defined).
</summary>
public int[] joints;
}
} |
# Jekyll variables
layout: subject
permalink: /subjects/<API key>
# Specific subject values
uuid: <API key>
broader:
- prefLabel: Samfundforhold
uuid: <API key>
- prefLabel: Uddannelse og forskning
uuid: <API key>
- prefLabel: Forskning
uuid: <API key>
conceptType: subterm
created: '2016-11-10T07:56:37.231184'
mappings:
- conceptIdentifier: '6306'
conceptURL: http://eurovoc.europa.eu/6306
match: closeMatch
thesaurus: EuroVoc
prefLabel: Forskningsresultat
status: proposed
updated: '2016-11-18T12:02:33.258279' |
<?php
namespace Frontend\<API key>\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Frontend\<API key>\Entity\Tipocorresponsalia;
use Frontend\<API key>\Form\<API key>;
/**
* Tipocorresponsalia controller.
*
*/
class <API key> extends Controller
{
/**
* Lists all Tipocorresponsalia entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('<API key>:Tipocorresponsalia')->findAll();
return $this->render('<API key>:Tipocorresponsalia:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Tipocorresponsalia entity.
*
*/
public function createAction(Request $request)
{
$entity = new Tipocorresponsalia();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('<API key>', array('id' => $entity->getId())));
}
return $this->render('<API key>:Tipocorresponsalia:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a Tipocorresponsalia entity.
*
* @param Tipocorresponsalia $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Tipocorresponsalia $entity)
{
$form = $this->createForm(new <API key>(), $entity, array(
'action' => $this->generateUrl('<API key>'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Tipocorresponsalia entity.
*
*/
public function newAction()
{
$entity = new Tipocorresponsalia();
$form = $this->createCreateForm($entity);
return $this->render('<API key>:Tipocorresponsalia:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Tipocorresponsalia entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('<API key>:Tipocorresponsalia')->find($id);
if (!$entity) {
throw $this-><API key>('Unable to find Tipocorresponsalia entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('<API key>:Tipocorresponsalia:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(), ));
}
/**
* Displays a form to edit an existing Tipocorresponsalia entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('<API key>:Tipocorresponsalia')->find($id);
if (!$entity) {
throw $this-><API key>('Unable to find Tipocorresponsalia entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('<API key>:Tipocorresponsalia:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a Tipocorresponsalia entity.
*
* @param Tipocorresponsalia $entity The entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Tipocorresponsalia $entity)
{
$form = $this->createForm(new <API key>(), $entity, array(
'action' => $this->generateUrl('<API key>', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Tipocorresponsalia entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('<API key>:Tipocorresponsalia')->find($id);
if (!$entity) {
throw $this-><API key>('Unable to find Tipocorresponsalia entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
$this->get('session')->getFlashBag()->add('notice', 'Se ha editado el tipo de corresponsalía exitosamente.');
return $this->redirect($this->generateUrl('<API key>', array('id' => $id)));
}
return $this->render('<API key>:Tipocorresponsalia:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Tipocorresponsalia entity.
*
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('<API key>:Tipocorresponsalia')->find($id);
if (!$entity) {
throw $this-><API key>('Unable to find Tipocorresponsalia entity.');
}
$em->remove($entity);
$em->flush();
}
$this->get('session')->getFlashBag()->add('notice', 'Se ha borrado el tipo de corresponsalía '.strtoupper($entity->getDescripcion()).' exitosamente.');
return $this->redirect($this->generateUrl('tipocorresponsalia'));
}
/**
* Creates a form to delete a Tipocorresponsalia entity by id.
*
* @param mixed $id The entity id
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('<API key>', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'BORRAR'))
->getForm()
;
}
} |
FROM silvioq/ruby-1.8.7
# Install dependencies
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN gem install bundler -v 1.3.5
# Set an environment variable where the Rails app is installed to inside of Docker image:
ENV RAILS_ROOT /var/www/app
RUN mkdir -p $RAILS_ROOT
# Set working directory, where the commands will be ran:
WORKDIR $RAILS_ROOT
# Setting env up
ENV RAILS_ENV="production"
ENV RACK_ENV="production"
ENV SECRET_KEY_BASE="8704xxhhb0b5889cb81d8452a218251f7940d285ffgg79a3c9b4108dd1e9875227a868bb122bc23c833432ca37b3fe7b7c514xxccc9285661e5b2ce8a5a53453"
# Adding gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install
# Adding project files
COPY . .
EXPOSE 3000
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"] |
import React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { createForm } from '@formily/core'
import { LifeCycleTypes, Form, useFormSpy, Field, createFormActions } from '..'
const InputField = props => (
<Field {...props}>
{({ state, mutators }) => (
<input value={state.value || ''} onChange={mutators.change} />
)}
</Field>
)
function Deferred() {
this.resolve = null
this.reject = null
this.promise = new Promise(
function(resolve, reject) {
this.resolve = resolve
this.reject = reject
}.bind(this)
)
Object.freeze(this)
}
describe('useFormSpy hook', () => {
test('basic', async () => {
const opts = {}
const mountFlag = new Deferred()
const endFlag = new Deferred()
const form = createForm(opts)
form.subscribe(({ type, payload }) => {
if (type === LifeCycleTypes.ON_FORM_MOUNT) {
mountFlag.resolve()
}
})
const FormWrapper = props => {
const { children } = props
return (
<Form form={form}>
<InputField name="a" />
{children}
</Form>
)
}
const typeList = []
const Fragment = () => {
const spyData = useFormSpy({ selector: '*', reducer: state => state })
typeList.push(spyData.type)
if (spyData.type === 'custom2') {
endFlag.resolve()
}
return spyData
}
const { result, rerender, waitForNextUpdate } = renderHook(Fragment, {
wrapper: FormWrapper
})
// return form instance
expect(result.current.form).toEqual(form)
expect(result.current.type).toEqual(LifeCycleTypes.ON_FORM_INIT)
expect(result.current.state).toEqual({})
expect(typeList.length).toEqual(1)
await mountFlag.promise
act(() => {
result.current.form.notify('custom1')
})
await waitForNextUpdate()
act(() => {
result.current.form.notify('custom2')
})
await waitForNextUpdate()
await endFlag.promise
rerender()
expect(typeList).toContain('custom1')
expect(typeList).toContain('custom2')
})
test('selector', async () => {
const opts = {}
const mountFlag = new Deferred()
const endFlag = new Deferred()
const form = createForm(opts)
form.subscribe(({ type, payload }) => {
if (type === LifeCycleTypes.ON_FORM_MOUNT) {
mountFlag.resolve()
}
if (type === 'custom2') {
endFlag.resolve()
}
})
const FormWrapper = props => {
const { children } = props
return (
<Form form={form}>
<InputField name="a" />
{children}
</Form>
)
}
const typeList = []
const Fragment = () => {
const spyData = useFormSpy({
selector: [LifeCycleTypes.ON_FORM_INIT, 'custom1'],
reducer: state => state
})
typeList.push(spyData.type)
return spyData
}
const { result, rerender, waitForNextUpdate } = renderHook(Fragment, {
wrapper: FormWrapper
})
await mountFlag.promise
act(() => {
result.current.form.notify('custom1')
})
await waitForNextUpdate()
act(() => {
result.current.form.notify('custom2')
})
await endFlag.promise
rerender()
expect(typeList).toContain('custom1')
expect(typeList).not.toContain('custom2')
})
test('reducer', async () => {
const opts = {}
const mountFlag = new Deferred()
const endFlag = new Deferred()
const form = createForm(opts)
const actions = createFormActions()
form.subscribe(({ type, payload }) => {
if (type === LifeCycleTypes.ON_FORM_MOUNT) {
mountFlag.resolve()
}
})
const FormWrapper = props => {
const { children } = props
return (
<Form actions={actions} form={form}>
<InputField name="a" />
{children}
</Form>
)
}
const typeList = []
const Fragment = () => {
const spyData = useFormSpy({
selector: ['custom1', 'custom2', 'custom3'],
reducer: state => {
return {
count: (state.count || 0) + 1
}
}
})
if (spyData.type === 'custom3') {
endFlag.resolve()
}
typeList.push(spyData.type)
return spyData
}
const { result, rerender, waitForNextUpdate } = renderHook(Fragment, {
wrapper: FormWrapper
})
await mountFlag.promise
act(() => {
form.notify('custom1')
})
await waitForNextUpdate()
act(() => {
form.notify('custom2')
})
await waitForNextUpdate()
act(() => {
form.notify('custom3')
})
await waitForNextUpdate()
await endFlag.promise
rerender()
expect(typeList).toContain('custom1')
expect(typeList).toContain('custom2')
expect(typeList).toContain('custom3')
expect(result.current.state).toEqual({ count: 3 })
})
}) |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>User agent detail - Mozilla/5.0 (Linux; Android 4.2.2; GT-I9060L Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.89 Mobile Safari/537.36 OPR/27.0.1698.89115</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../circle.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Linux; Android 4.2.2; GT-I9060L Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.89 Mobile Safari/537.36 OPR/27.0.1698.89115
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>Browscap<br /><small>6014</small><br /><small>vendor/browscap/browscap/tests/fixtures/issues/issue-635.php</small></td><td>Opera Mobile 27.0</td><td>Blink unknown</td><td>Android 4.2</td><td style="border-left: 1px solid #555">Samsung</td><td>Galaxy Grand Neo</td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Browscap result detail</h4>
<p><pre><code class="php">Array
(
[Comment] => Opera Mobile 27.0 for Android
[Browser] => Opera Mobile
[Browser_Type] => Browser
[Browser_Bits] => 32
[Browser_Maker] => Opera Software ASA
[Browser_Modus] => unknown
[Version] => 27.0
[MajorVer] => 27
[MinorVer] => 0
[Platform] => Android
[Platform_Version] => 4.2
[<API key>] => Android OS
[Platform_Bits] => 32
[Platform_Maker] => Google Inc
[Alpha] =>
[Beta] =>
[Win16] =>
[Win32] =>
[Win64] =>
[Frames] => 1
[IFrames] => 1
[Tables] => 1
[Cookies] => 1
[BackgroundSounds] =>
[JavaScript] => 1
[VBScript] =>
[JavaApplets] =>
[ActiveXControls] =>
[isMobileDevice] => 1
[isTablet] =>
[isSyndicationReader] =>
[Crawler] =>
[isFake] =>
[isAnonymized] =>
[isModified] =>
[CssVersion] => 3
[AolVersion] => 0
[Device_Name] => Galaxy Grand Neo
[Device_Maker] => Samsung
[Device_Type] => Mobile Phone
[<API key>] => touchscreen
[Device_Code_Name] => GT-I9060L
[Device_Brand_Name] => Samsung
[<API key>] => Blink
[<API key>] => unknown
[<API key>] => Google Inc
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Opera Mobile 27.0</td><td>Blink </td><td>Android 4.2</td><td style="border-left: 1px solid #555">Samsung</td><td>Galaxy Grand Neo</td><td>Mobile Phone</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.011</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapFull result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.2.*gt\-i9060l build\/.*\) applewebkit\/.* \(khtml, like gecko\).*chrome\/.*safari\/.* opr\/27\..*$/ |
var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;
var ComitySchema = new mongoose.Schema({
name: {
type: String,
trim: true
},
description: String,
members: [{
type: ObjectId,
ref: 'User'
}],
creator: {
type: ObjectId,
ref: 'User'
}
});
module.exports = mongoose.model('Comity', ComitySchema); |
layout: post
published: true
title: First Meeting
mathjax: false
featured: true
comments: true
headline: First meeting
categories:
- membership
tags: membership
After using [doodle](http:
* In attendance: Nate Burch, Ta-Tao Chuang, James Hallett, and Vivek Patil
* What happened: People introduced themselves - what they did, how they used R, and their length of experience with R. They also talked about whether they taught any classes using R and we spent a little time talking about some of the challenges. Most of the teaching in class was geared towards undergraduate students. We also spent some time talking about what the objective of the group would be and we decided to give this topic some time to crystallize. We also talked about switching locations between Eastern Washington University and Gonzaga. However, the next meeting would continue to be at Gonzaga.
* Next meeting: October 31, Friday, Halloween, at 4:00 pm, Gonzaga. Room, TBD
* Key speaker: Krisztian Magori on challenges with his statistics class.
<br>
Fun times. <br>
<img src="/images/chuang-hallett-9-26.jpg" alt="Ta-Tao Chuang and James Hallett" height="450" width="600">
<img src="/images/burch-9-26.jpg" alt="Nate Burch" height="450" width="600">
<img src="/images/trio-selfie-9-30.jpg" alt="Ta-Tao Chuang, Nate Burch, and Vivek Patil" height="450" width="600"> |
#ifndef <API key>
#define <API key>
#include "cucumberfwd.hpp"
namespace CucumberCPP
{
/** Communicates using the wire protocol but reading from std::cin
and writing to std::cout. This can be turned into a poor man's server using
netcat -l -p 1337 -e ./a.out */
class <API key>
{
public:
static int main(int /*argc*/, char **/*argv*/, WireProtocolService& service);
};
}
#endif |
import * as common from './common';
import * as nodeApi from '<API key>';
import * as ReleaseApi from '<API key>/ReleaseApi';
import * as ReleaseInterfaces from '<API key>/interfaces/ReleaseInterfaces';
export async function run() {
const projectId: string = common.getProject();
const webApi: nodeApi.WebApi = await common.getWebApi();
const releaseApiObject: ReleaseApi.IReleaseApi = await webApi.getReleaseApi();
common.banner('Release Samples');
common.heading('Get releases');
const releases: ReleaseInterfaces.Release[] = await releaseApiObject.getReleases(projectId);
console.log('There are', releases.length, 'releases for this project');
if(releases.length > 0) {
const release = releases[0];
console.log('Info for release', release.name);
console.log('Logs for this release:', releaseApiObject.getLogs(projectId, release.id));
const workItemRefs: ReleaseInterfaces.ReleaseWorkItemRef[] = await releaseApiObject.<API key>(projectId, release.id);
console.log('There are', workItemRefs.length, 'work items associated with this release');
if (workItemRefs.length > 0) {
console.log('Example work item', workItemRefs[0]);
}
}
else {
console.log('Must have at least 1 release to do samples with releases');
}
common.heading('Get metadata');
console.log('Release settings:', await releaseApiObject.getReleaseSettings(projectId));
console.log('Tags:', await releaseApiObject.getTags(projectId));
common.heading('Get Approval information');
const approvals: ReleaseInterfaces.ReleaseApproval[] = await releaseApiObject.getApprovals(projectId);
console.log('There are', approvals.length, 'approvals for this project');
if (approvals.length > 0) {
console.log('Sample approval:', approvals[0]);
}
} |
import Ember from 'ember';
export default Ember.Controller.extend({
multiLineText: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
multiLineText2: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, \n\nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
actions: {
}
}); |
'use strict';
angular.module('mean.students').factory('Students', [
function() {
return {
name: 'students'
};
}
]); |
# docrules
pattern matching assertion framework for documents
try it with [tracery](https://npm.im/tracery)!
(work in progress, see `test/example.js` or ask Jason. Not yet ready for public consumption, ymmv)
## usage
docrules defines sets of `rules` grouped by `selectors`. Rule sets can then be run on a document to generate a report of errors, warnings, and info.
var docrules = require('docrules')
first we create a rule set
var rules = new docrules()
Now add a matching selector. Selectors use mongodb style dot notation. A wildcard `*` can be used to match any key at that level.
`rules.match(selector, (ruleCb) => void)`
The second argument of `rules.match` is a function which takes a ruleCallback. This ruleCallback is used to define rules which should be run on each item which matches the `selector`
rules.match('users.*', function (user) {
We define a rule like so:
user('should have an ID', function (assert) {
Rule callbacks require a label (shown in the report if the rule reports an error, warning, or info), and a body function defining the rule. The body function is passed an `assert` function which should be used to ensure proper reporting. Other assertion libraries should not be used at this time (see the `run` function implementation of `index.js` if you want to hack it in). `this` is bound to the matching value, in this case, a user object.
assert(this.hasOwnProperty(id))
.error()
})
## assertion
Assertions are called as chains. They require a condition and a report, and may have a fix in between.
assert(condition)
.report('level','message')
or
assert(condition)
.fix('label', function() {})
.report('level','message')
There are three aliases for `.report` which pre-fill the label for you - normally you will use this:
.error('message')
.warn('message')
.info('message')
Note the assertion will not throw if you do not call a report function, even if the condition fails. (This may change in future versions)
## running the ruleset
After we've created a ruleset, added some match groups, and defined some rules, we can run these by calling
var report = ruleset.run(document)
The resulting report is an array which looks like this:
[ { inner:
{ name: 'AssertReportError',
level: 'error',
message: 'not a user' },
selector: 'users.*',
path: [ 'users', 'b' ],
value: { firstName: 'Bertha', lastName: 'Cortez', likesStarWars: true },
rule: 'schema',
level: 'error',
message: 'not a user' } ]
With these additional properties:
{
matches: 2,
rules: 6,
errors: [ { inner: [Object],
selector: 'users.*',
path: [Object],
value: [Object],
rule: 'schema',
level: 'error',
message: 'not a user' } ],
warnings: [] }
For a full end-to-end, see `test/example.js`
internal (c) 2013 Agile Diagnosis. |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>simple-io: 19 s </title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.14.1 / simple-io - 0.2</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
simple-io
<small>
0.2
<span class="label label-success">19 s </span>
</small>
</h1>
<p> <em><script>document.write(moment("2022-03-08 04:38:57 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-08 04:38:57 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
conf-gmp 4 Virtual package relying on a GMP lib system installation
coq 8.14.1 Formal proof management system
dune 3.0.3 Fast, portable, and opinionated build system
ocaml 4.10.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.10.2 Official release 4.10.2
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers
# opam file:
opam-version: "2.0"
maintainer: "Li-yao Xia <lysxia@gmail.com>"
authors: "Li-yao Xia"
homepage: "https://github.com/Lysxia/coq-simple-io"
bug-reports: "https://github.com/Lysxia/coq-simple-io/issues"
license: "MIT"
dev-repo: "git+https://github.com/Lysxia/coq-simple-io.git"
build: [
[make "build"]
[make "test"] {with-test}
]
install: [make "install"]
remove: [make "uninstall"]
depends: [
"coq" {>= "8.6.1"}
"ocaml"
]
tags: [
"date:2018-07-28"
"logpath:SimpleIO"
"keyword:extraction"
"keyword:effects"
]
synopsis: "IO monad for Coq"
description: """
This library provides tools to implement IO programs directly in Coq, in a
similar style to Haskell. Facilities for formal verification are not included.
IO is defined as a parameter with a purely functional interface in Coq,
to be extracted to OCaml.
Some wrappers for the basic types and functions in the OCaml Pervasives module
are provided. Users are free to define their own APIs on top of this IO type."""
url {
src: "https://github.com/Lysxia/coq-simple-io/archive/0.2.tar.gz"
checksum: "md5=<API key>"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install </h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-simple-io.0.2 coq.8.14.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-simple-io.0.2 coq.8.14.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>10 s</dd>
</dl>
<h2>Install </h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-simple-io.0.2 coq.8.14.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>19 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 134 K</p>
<ul>
<li>30 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/OcamlPervasives.vo</code></li>
<li>26 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/CoqPervasives.vo</code></li>
<li>22 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/OcamlString.vo</code></li>
<li>11 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/IOMonad.vo</code></li>
<li>10 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/CoqPervasives.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/OcamlPervasives.glob</code></li>
<li>9 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/IOMonad.glob</code></li>
<li>6 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/OcamlPervasives.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/OcamlString.glob</code></li>
<li>3 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/CoqPervasives.v</code></li>
<li>3 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/IOMonad.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.10.2/lib/coq/user-contrib/SimpleIO/OcamlString.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-simple-io.0.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https:
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html> |
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Model\MethodRequestBody.cs.tt
namespace Microsoft.Graph
{
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
<summary>
The type <API key>.
</summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class <API key>
{
<summary>
Gets or sets Name.
</summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "name", Required = Newtonsoft.Json.Required.Default)]
public string Name { get; set; }
}
} |
**
**<http://download.networkbench.com/newlens/android_agent/eclipse>**
*APP_Keyauth*
*<https://github.com/rongcloud/auth-service-nodejs>*
conf.jsonappKey
*DemoContextinitAPP_KeyDemoApiHOSTauth*
*EclipseImportapp/src/main UTF-8
6_FriendListDemo
1MainActivityextends FragmentActivityActivity
public class MainActivity extends FragmentActivity implements OnClickListener{
ActionBar mActionBar;
ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getIntent().setData(Uri.parse("rong://io.rong.imkit.demo").buildUpon().appendPath("conversationlist").appendPath("private")
.<API key>("targetId","user1").build());
setContentView(R.layout.activity_main);
mActionBar = (ActionBar)findViewById(android.R.id.custom);
mActionBar.getTitleTextView().setText("");
mActionBar.setOnBackClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
LayoutInflater inflater = LayoutInflater.from(this);
imageButton = (ImageButton)inflater.inflate(R.layout.<API key>,mActionBar,false);
mActionBar.addView(imageButton);
imageButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int imageButtonId = imageButton.getId();
if(v.getId() == imageButtonId)
{
Intent intent = new Intent(MainActivity.this, TextActivity.class);
startActivity(intent);
}
}
}
2MainActivityactivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<io.rong.imkit.veiw.ActionBar
android:id="@android:id/custom"
style="@style/RcTheme.ActionBar">
</io.rong.imkit.veiw.ActionBar>
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="io.rong.imkit.fragment.<API key>"/>
</LinearLayout>
3rc_imagebutton_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_margin="5dp"
android:layout_height="wrap_content"
style="@style/RcTheme.ActionBar.ButtonAdd"/>
4rc_theme.xml
<style name="RcTheme.ActionBar.ButtonAdd" parent="@android:TextAppearance.Small.Inverse">
<item name="android:gravity">center</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:background">@drawable/rc_add_people</item>
<item name="android:textColor">@drawable/<API key></item>
</style>
3TextActivity.java
activity_text.xml
Button
@Override
public void onClick(View v) {
Intent intent = new Intent(TextActivity.this, RongActivity.class);
intent.putExtra(RCloudConst.EXTRA.CONTENT, <API key>.class.getName());
startActivity(intent);
}
Email<bd@rongcloud.cn>
[@RongCloud](http://weibo.com/rongcloud)
QQ 2948214065
RongCloud RongCloud
;
~ConsoleGraphic();
void restart(Player& player, int x, int y, console::Console* console);
int getWidth() const;
int getHeight() const;
void callback(GameEvent gameEvent, const TetrisBoard& tetrisBoard);
void updatePoints(int points);
void updateLevel(int level);
void draw(const TetrisBoard& tetrisBoard);
void drawStatic() const;
private:
void drawText() const;
void drawSquare(int x, int y, BlockType blockType) const;
void draw(int x, int y, char key) const;
void draw(int x, int y, std::string text) const;
void draw(int x, int y, std::string text, int number) const;
void drawNextBlock(BlockType nextBlockType) const;
void drawCurrentBlock(const Block& currentBlock) const;
void drawBoard(const TetrisBoard& board) const;
static const std::string SQUARE;
mw::signals::Connection connection_;
std::string playerName_;
int x_, y_;
int rows_, columns_;
int nbrRemovedRows_;
BlockType nextBlockType_;
Block currentBlock_;
int points_, level_;
console::Console* console_;
};
#endif // CONSOLEGRAPHIC_H |
Test to check degurechaff parser
with toml-test data
import { parse } from '../src/degurechaff'
import * as ast from '../src/lib/chevAst'
import * as utils from '../src/lib/utils'
import * as fs from 'fs'
import * as path from 'path'
convert AST root node to JSON compatible object structure
in folder data
function toJsonSpec(root: ast.Root) {
const result = {}
convert pair first
dumpPairs(result, root.pairs)
tables
for (const table of root.tables) {
const currentObject = utils.lookupObject(result, table.name.segments)
// console.log("segments::", table.name)
// console.log("pairs::", table.pairs)
dumpPairs(currentObject, table.pairs)
}
array of table
for (const aot of root.arrayOfTables) {
const currentArray = utils.lookupArray(result, aot.name.segments)
// console.log("dump pairs::", aot.pairs)
const newObject = {}
dumpPairs(newObject, aot.pairs)
// console.log("currentArray:", currentArray, "segments:", aot.name.segments)
currentArray.push(newObject)
}
return result
}
function dumpPairs(node: { [index: string]: any }, pairs: ast.Pair[]) {
for (const pair of pairs) {
const key = pair.key
const value = pair.value
node[key] = toValueSpec(value)
}
}
function toValueSpec(data: ast.Value): any {
if (data instanceof ast.InlineTableValue) {
const result = {}
dumpPairs(result, data.pairs)
return result
}
other data have same format {'type': ..., 'value': ....}
let type
let value
if (data instanceof ast.ArrayValue) {
type = 'array'
value = []
for (const item of data.items) {
value.push(toValueSpec(item))
}
} else if (data instanceof ast.AtomicValue) {
if (data.kind === ast.AtomicValueKind.String) {
type = 'string'
value = data.content
} else if (data.kind === ast.AtomicValueKind.Integer) {
type = 'integer'
value = data.toString()
} else if (data.kind === ast.AtomicValueKind.Float) {
type = 'float'
value = data.toString()
} else if (data.kind === ast.AtomicValueKind.Boolean) {
type = 'bool'
value = data.toString()
} else if (data.kind === ast.AtomicValueKind.Date) {
type = 'datetime'
value = data.toString()
} else {
throw new Error('sementara error: ' + data.kind)
}
} else {
throw new Error('imposible to reach')
}
return { type, value }
}
function testSpec(folder: string, filename: string) {
const tomlData = fs.readFileSync(`${folder}/${filename}.toml`, 'utf8')
const jsonData = fs.readFileSync(`${folder}/${filename}.json`, 'utf8')
// console.log(tomlData)
const root = parse(tomlData)
convert to test json data
const expected = JSON.parse(jsonData)
check AST
const result = toJsonSpec(root)
expect(result).toEqual(expected)
}
function testInvalid(folder: string, filename: string) {
const tomlData = fs.readFileSync(`${folder}/${filename}.toml`, 'utf8')
expect(() => {
const root = parse(tomlData)
const result = toJsonSpec(root)
}).toThrow()
}
describe('test valid toml file', () => {
const dirname = 'test/data/valid'
const allFiles = fs.readdirSync(dirname)
const tomlFiles = allFiles
.filter(x => path.extname(x) === '.toml')
FIXME: js native don't support big integer
.filter(x => x !== 'long-integer.toml')
FIXME: disable for now. revisit later when error handling done
.filter(x => x !== '<API key>.toml')
.map(x => path.basename(x).slice(0, -5))
tomlFiles.forEach(filename => {
test(`${filename}`, () => testSpec(dirname, filename))
})
})
test('test invalid toml file', () => {
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'duplicate-key-table')
testInvalid('test/data/invalid', 'duplicate-keys')
testInvalid('test/data/invalid', 'duplicate-tables')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'empty-table')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'float-leading-zero')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'key-empty')
testInvalid('test/data/invalid', 'key-hash')
testInvalid('test/data/invalid', 'key-newline')
testInvalid('test/data/invalid', 'key-no-eol')
testInvalid('test/data/invalid', 'key-open-bracket')
testInvalid('test/data/invalid', 'key-space')
testInvalid('test/data/invalid', 'key-start-bracket')
testInvalid('test/data/invalid', 'key-two-equals')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'string-bad-escape')
testInvalid('test/data/invalid', 'string-bad-uni-esc')
testInvalid('test/data/invalid', 'string-byte-escapes')
testInvalid('test/data/invalid', 'string-no-close')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'table-empty')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'table-whitespace')
testInvalid('test/data/invalid', 'table-with-pound')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'text-after-integer')
testInvalid('test/data/invalid', 'text-after-string')
testInvalid('test/data/invalid', 'text-after-table')
testInvalid('test/data/invalid', '<API key>')
testInvalid('test/data/invalid', 'text-in-array')
// / NOTE: toml node allow it
// testInvalid('test/data/invalid', '<API key>')
TODO: fix it
// testInvalid('test/data/invalid', '<API key>')
// testInvalid('test/data/invalid', '<API key>')
// testInvalid('test/data/invalid', 'key-after-array')
// testInvalid('test/data/invalid', 'key-after-table')
// testInvalid('test/data/invalid', 'llbrace')
// testInvalid('test/data/invalid', 'rrbrace')
}) |
angular.module( 'sailng.post', [
])
.config(function config( $stateProvider ) {
$stateProvider.state( 'post', {
url: '/post',
views: {
"main": {
controller: 'PostController',
templateUrl: 'post/index.tpl.html'
}
},
resolve: {
posts: function(PostModel) {
return PostModel.getAll().then(function(models) {
return models;
});
}
}
});
})
.controller( 'PostController', function PostController( $scope, $sailsSocket, lodash, config, titleService, PostModel, posts ) {
titleService.setTitle('Posts');
$scope.newPost = {};
$scope.posts = posts;
$scope.currentUser = config.currentUser;
$sailsSocket.subscribe('post', function (envelope) {
switch(envelope.verb) {
case 'created':
//console.log(envelope.data);
$scope.posts.unshift(envelope.data);
break;
case 'destroyed':
lodash.remove($scope.posts, {id: envelope.id});
break;
}
});
$scope.destroyPost = function(post) {
// check here if this post belongs to the currentUser
if (post.user.id === config.currentUser.id) {
PostModel.delete(post).then(function(model) {
// [post] has been deleted, and removed from $scope.posts
});
}
};
$scope.createPost = function(newPost) {
newPost.user = config.currentUser.id;
//console.log(newPost);
PostModel.create(newPost).then(function(model) {
console.log(model);
$scope.newPost = {};
});
};
}); |
using System.Numerics;
namespace Myre.UI
{
<summary>
A static class containing extension methods.
</summary>
static class Extensions
{
#region Vector2
<summary>
Converts this Vector2 into an Int2D.
</summary>
<param name="v">The v.</param>
<returns></returns>
public static Int2D ToInt2D(this Vector2 v)
{
return new Int2D(v);
}
#endregion
}
} |
# Ghoul - Prettier Git For Everyone :)
Ghoul is a simple yet good looking interface for your git repositories written in sinatra. It is currently only for demonstration purposes and use on your secure local machine as it does not enforce any authentication as of yet.InstallationGhoul can be run either using the ghoul gem or by downloading the git repository and running through the rackup command.
## Installing via rubygems
gem install ghoul
ghoul server
## Installing from the git repository
git clone http://github.com/georgedrummond/ghoul
cd ghoul
bundle install
rackup
## How it works
Ghoul uses the grit, written by the guys at github for parsing your repositories which are located in a folder named "repos" within your home folder e.g. /Users/georgedrummond/repos. For git push, ghoul uses grack. Grack has no authentication so ghoul should only be used on your local machine.
Copyright (c) 2011 George Drummond, george@accountsapp.com
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
<?php
namespace Mondido\Mondido\Test\Unit\Observer;
use Mondido\Mondido\Test\Unit\<API key> as ObjectManager;
class <API key> extends \PHPUnit\Framework\TestCase
{
protected $object;
/**
* @var \Magento\Framework\TestFramework\Unit\Helper\ObjectManager
*/
protected $objectManager;
/**
* Set up
*
* @return void
*/
protected function setUp()
{
$this->objectManager = new ObjectManager($this);
$this->object = $this->objectManager->getObject(
'Mondido\Mondido\Observer\<API key>'
);
}
/**
* Test execute
*
* @return void
*/
public function testExecute()
{
$this->assertEquals(get_class($this->object), 'Mondido\Mondido\Observer\<API key>');
}
/**
* Tear down
*
* @return void
*/
protected function tearDown()
{
$this->object = null;
$this->objectManager = null;
}
} |
/* globals $ */
function solve() {
return function (selector) {
var data = {
animals: [{
name: 'Lion',
url: 'https://susanmcmovies.files.wordpress.com/2014/12/<API key>.jpg'
}, {
name: 'Turtle',
url: 'http:
}, {
name: 'Dog'
}, {
name: 'Cat',
url: 'http://i.imgur.com/Ruuef.jpg'
}, {
name: 'Dog Again'
}]
};
var template = ' <div class="container">' +
'<h1>Animals</h1>' +
'<ul class="animals-list">' +
'{{#each animals}}' +
'<li><a {{#if url}}href="{{url}}"{{/if}} {{
'</a>{{#if url}}See a {{name}}{{/if}}{{#unless url}}No link for {{name}}, here is Batman!{{/unless}}</li>' +
'{{/each}}' +
'</ul>' +
'</div>';
$(selector).html(template);
};
};
module.exports = solve; |
def yield_function(n):
for i in range(n):
print "pre", i
yield i
print "post", i
for x in yield_function(10):
print x
print |
require "watir"
require 'fileutils'
require 'json'
require 'webrick'
require 'socket'
require "marta/version"
require "marta/object"
require 'marta/public_methods'
require 'marta/options_and_paths'
require 'marta/read_write'
require 'marta/user_values_prework'
require 'marta/dialogs'
require 'marta/classes_creation'
require 'marta/lightning'
require 'marta/injector'
require 'marta/json_2_class'
require 'marta/black_magic'
require 'marta/<API key>'
require 'marta/x_path'
require 'marta/page_arithmetic'
require 'marta/server'
# Marta class is providing three simple methods.
# const_missing is hijacked. And in a learn mode marta will treat any unknown
# constant as an unknown pageobject and will try to ask about using browser
module Marta
include OptionsAndPaths, ReadWrite, Json2Class
class SmartPage
attr_accessor :data, :class_name, :edit_mark
include BlackMagic, XPath, SimpleElementFinder, ClassesCreation,
PublicMethods, Dialogs, Injector, Lightning, OptionsAndPaths,
Json2Class, ReadWrite, UserValuePrework, PageArithmetic, Server
# open_page can create new instance
def self.open_page(*args)
page = self.new
page.open_page(*args)
end
end
# Marta is returning an engine (it should be a browser instance)
# Watir::Browser.new(:chrome) by default
def engine
SettingMaster.engine
end
# dance_with is for creating settings to be used later.
# Settings can be changed at any time by calling dance with.
# Read more in the README
def dance_with(browser: nil, folder: nil, learn: nil, tolerancy: nil,
base_url: nil, cold_timeout: nil, port: nil, clear: nil)
SettingMaster.clear if clear
SettingMaster.set_port port
# We are always turning the server on in order to show Welcome!
SettingMaster.set_server # server should be before browser
SettingMaster.set_engine browser # browser should be before learn!
SettingMaster.set_learn learn
SettingMaster.set_folder folder
SettingMaster.set_base_url base_url
read_folder
SettingMaster.set_tolerancy tolerancy
SettingMaster.set_cold_timeout cold_timeout
engine
end
end |
<?php
namespace Yusuke\HimatanBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* UserArea
* @ORM\Entity(repositoryClass="Yusuke\HimatanBundle\Entity\Repository\UserAreaRepository")
* @ORM\Table(name="user_area")
*/
class UserArea
{
/**
* @var /UserPost
*
* @ORM\ManyToOne(targetEntity="UserPost")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="post_id", <API key>="id")
* })
*/
private $post;
/**
* @var integer
*
* @ORM\Column(name="area_id", type="integer", nullable=false)
*/
private $areaId;
/**
* @var \DateTime
*
* @ORM\Column(name="created_at", type="datetime", nullable=false)
* @Gedmo\Timestampable(on="create")
*/
private $createdAt;
/**
* @var \DateTime
*
* @ORM\Column(name="updated_at", type="datetime", nullable=false)
* @Gedmo\Timestampable(on="update")
*/
private $updatedAt;
/**
* @var integer
*
* @ORM\Column(name="delete_flag", type="integer")
*/
private $deleteFlag = 0;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* Set areaId
*
* @param integer $areaId
* @return UserArea
*/
public function setAreaId($areaId)
{
$this->areaId = $areaId;
return $this;
}
/**
* Get areaId
*
* @return integer
*/
public function getAreaId()
{
return $this->areaId;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
* @return UserArea
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
* @return UserArea
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set deleteFlag
*
* @param boolean $deleteFlag
* @return UserArea
*/
public function setDeleteFlag($deleteFlag)
{
$this->deleteFlag = $deleteFlag;
return $this;
}
/**
* Get deleteFlag
*
* @return boolean
*/
public function getDeleteFlag()
{
return $this->deleteFlag;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Get post
*
* @return /Post
*/
public function getPost()
{
return $this->post;
}
/**
* Set post
*
* @param integer $post
* @return UserArea
*/
public function setPost($post)
{
$this->post = $post;
return $this;
}
} |
import {
Component, OnInit, Input, OnDestroy, ViewChild, Inject, AfterViewInit, ChangeDetectorRef,
HostListener, Output, EventEmitter
} from '@angular/core';
import { Router, ActivatedRoute, ParamMap, RouterLink } from '@angular/router';
import { TranslateService, TranslatePipe } from '@ngx-translate/core';
import { DOCUMENT, DecimalPipe } from '@angular/common';
import { Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/takeUntil';
import { ToastsManager, ToastOptions } from 'ng2-toastr';
import { environment } from '../../../../environments/environment';
import { RankingLocation } from '../../ranking-location';
import { RankingService } from '../../ranking.service';
import { ScrollService } from '../../../services/scroll.service';
import { LoadingService } from '../../../services/loading.service';
import { PlatformService } from '../../../services/platform.service';
import { AnalyticsService } from '../../../services/analytics.service';
import { RankingUiComponent } from '../../ranking-ui/ranking-ui.component';
import { <API key> } from '../../ranking-list/ranking-list.component';
import { <API key> } from '../../ranking-panel/ranking-panel.component';
@Component({
selector: 'app-evictions',
templateUrl: './evictions.component.html',
styleUrls: ['./evictions.component.scss']
})
export class EvictionsComponent implements OnInit, AfterViewInit, OnDestroy {
/** string representing the region */
@Input()
set region(regionValue) {
if (!regionValue) { return; }
if (regionValue !== this.store.region) {
this.debug('set region', regionValue, this.store.region);
this.store.region = regionValue;
this.updateEvictionList();
}
}
get region() { return this.store.region; }
/** ID representing the selected area type */
@Input()
set areaType(newType) {
if (!newType) { return; }
if ((!this.store.areaType || newType.value !== this.store.areaType.value) && newType) {
this.debug('set areaType', newType, this.store.areaType);
this.store.areaType = newType;
this.updateEvictionList();
this.trackAreaChange();
}
}
get areaType() { return this.store.areaType; }
/** object key representing the data property to sort by */
@Input()
set dataProperty(newProp) {
if (!newProp) { return; }
if ((!this.store.dataProperty || newProp.value !== this.store.dataProperty.value) && newProp) {
this.debug('set dataProp', newProp, this.store.dataProperty);
this.store.dataProperty = newProp;
this.updateEvictionList();
this.trackRankByChange();
}
}
get dataProperty() { return this.store.dataProperty; }
/** the index of the selected location for the data panel */
@Input()
set selectedIndex(value: number) {
const panelOpened = this.store.selectedIndex === null;
this.store.selectedIndex = value;
// location exists in the current list, set active and scroll to it
if (value !== null && value < this.topCount) { this.scrollToIndex(value); }
// if the panel is newly opened, focus
if (panelOpened) { this.focusPanel(); }
this.updateTweet();
}
get selectedIndex(): number { return this.store.selectedIndex; }
/** Reference to the ranking list component */
@ViewChild(<API key>) rankingList: <API key>;
/** Reference to the ranking panel component */
@ViewChild(<API key>) rankingPanel: <API key>;
/** tracks if the data has been loaded and parsed */
isDataReady = false;
/** A shortened version of `listData`, containing only the first `topCount` items */
truncatedList: Array<RankingLocation>;
/** Stores the maximum value in the truncated List */
dataMax = 1;
/** list of data for the current UI selections */
listData: Array<RankingLocation>; // Array of locations to show the rank list for
/** state for UI panel on mobile / tablet */
showUiPanel = false;
/** Boolean of whether to show scroll to top button */
showScrollButton = false;
/** number of items to show in the list */
topCount = 100;
/** true if in kiosk mode */
kiosk = false;
/** Tweet text */
tweet: string;
/** Stores the current language */
currentLang = 'en';
private store = {
region: 'United States',
areaType: this.rankings.areaTypes[0],
dataProperty: this.rankings.sortProps[0],
selectedIndex: null
};
/** returns if all of the required params are set to be able to fetch data */
get canRetrieveData(): boolean {
return this.canNavigate && this.isDataReady;
}
private get canNavigate(): boolean {
return this.region && this.areaType && this.dataProperty &&
this.areaType.hasOwnProperty('value') &&
this.dataProperty.hasOwnProperty('value');
}
private destroy: Subject<any> = new Subject();
private _debug = true;
constructor(
public rankings: RankingService,
public loader: LoadingService,
public platform: PlatformService,
private route: ActivatedRoute,
private router: Router,
private scroll: ScrollService,
private translate: TranslateService,
private analytics: AnalyticsService,
private translatePipe: TranslatePipe,
private decimal: DecimalPipe,
private changeDetectorRef: ChangeDetectorRef,
private toast: ToastsManager,
@Inject(DOCUMENT) private document: any
) {
this.store.areaType = this.rankings.areaTypes[0];
this.store.dataProperty = this.rankings.sortProps[0];
this.toast.onClickToast().subscribe(t => this.toast.dismissToast(t));
this.debug('init');
}
/** subscribe to when the rankings data is ready, show loading */
ngOnInit() {
this.rankings.isReady.takeUntil(this.destroy)
.subscribe((ready) => {
this.isDataReady = ready;
if (ready) {
this.updateEvictionList();
this.loader.end('evictions');
}
});
this.translate.onLangChange.subscribe((l) => {
this.currentLang = l.lang;
this.updateQueryParam('lang', l.lang);
this.updateTweet();
});
// set kiosk mode if kiosk url
this.kiosk = this.platform.nativeWindow.location.hostname.includes('kiosk');
}
/** load data once the view has been initialized */
ngAfterViewInit() {
this.loader.start('evictions');
this.rankings.loadEvictionsData();
// list takes a bit to render, so setup page scroll in a timeout instead
setTimeout(() => { this.setupPageScroll(); }, 500);
}
/** clear any subscriptions on destroy */
ngOnDestroy() {
this.rankings.setReady(false);
this.destroy.next();
this.destroy.complete();
}
/** Move to previous or next location with arrows, hide panel with escape */
@HostListener('keydown', ['$event']) onKeypress(e) {
if (this.selectedIndex === null) { return; }
if ((e.keyCode === 37 || e.keyCode === 39)) {
// left or right
const newValue = (e.keyCode === 37) ? this.selectedIndex - 1 : this.selectedIndex + 1;
this.setCurrentLocation(Math.min(Math.max(0, newValue), this.topCount));
}
if (e.keyCode === 27) {
// escape
this.onClose();
e.preventDefault();
}
}
/** Updates one of the query parameters and updates the route */
updateQueryParam(paramName: string, value: any) {
if (!this.canNavigate) { return; }
if (paramName === 'r' || paramName === 'a' || paramName === 'd') {
this.selectedIndex = null;
}
const params = this.getQueryParams();
params[paramName] = value;
this.router.navigate([ '/', 'evictions' ], { queryParams: params });
}
/** Update the route when the region changes */
onRegionChange(newRegion: string) {
if (newRegion === this.region) { return; }
this.updateQueryParam('r', newRegion);
}
/** Update the route when the area type changes */
onAreaTypeChange(areaType: { name: string, value: number }) {
if (this.areaType && areaType.value === this.areaType.value) { return; }
this.updateQueryParam('a', areaType.value);
}
/** Update the sort property when the area type changes */
<API key>(dataProp: { name: string, value: string }) {
if (this.dataProperty && dataProp.value === this.dataProperty.value) { return; }
this.updateQueryParam('d', dataProp.value);
}
/** Update current location, shows toast if data unavailable */
setCurrentLocation(locationIndex: number) {
if (this.selectedIndex === locationIndex) { return; }
if (this.isLocationInvalid(locationIndex)) {
this.<API key>();
return;
}
const value = (locationIndex || locationIndex === 0) ? locationIndex : null;
this.updateQueryParam('l', value);
}
/**
* Scrolls to the searched location if it exists in the list
* or switches to the corresponding area type for the location and activates
* the location
* @param location
*/
<API key>(e: { selection: RankingLocation, queryTerm: string } | null) {
let location: RankingLocation = null;
if (e.selection) { location = e.selection; }
if (location === null) { return this.setCurrentLocation(null); }
this.showUiPanel = false;
let listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
if (listIndex > -1) {
this.setCurrentLocation(listIndex);
} else {
// location doesn't exist in the list, update to full list and find the location
this.region = 'United States';
this.areaType = this.rankings.areaTypes.filter(t => t.value === location.areaType)[0];
this.updateEvictionList();
listIndex = this.listData.findIndex(d => d.geoId === location.geoId);
this.setCurrentLocation(listIndex);
}
this.scrollToIndex(Math.min(99, listIndex));
this.<API key>(location, e.queryTerm);
}
/** handles the click on a specific location */
onClickLocation(index: number) {
this.setCurrentLocation(index);
this.<API key>(this.listData[index]);
}
/** Switch the selected location to the next one in the list */
onGoToNext() {
if (this.selectedIndex < this.listData.length - 1) {
this.setCurrentLocation(this.selectedIndex + 1);
}
}
/** Switch the selected location to the previous one in the list */
onGoToPrevious() {
if (this.selectedIndex > 0) {
this.setCurrentLocation(this.selectedIndex - 1);
}
}
/** Removes currently selected index on closing the panel */
onClose() {
this.scrollToIndex(this.selectedIndex, true);
this.setCurrentLocation(null);
}
/**
* Checks if location is in view, scrolls to it if so
* @param rank Rank of location
*/
<API key>(rank: number) {
this.scrollToIndex(rank - 1);
}
/** Updates Twitter text for city rankings based on selections */
updateTweet() {
if (!this.canNavigate || !this.listData) { return ''; }
this.tweet = this.isDefaultSelection() ? this.getDefaultTweet() :
(this.isLocationSelected() ? this.getLocationTweet() : this.getRegionTweet());
this.debug('updated tweet - ', this.tweet);
}
scrollToTop() {
this.scroll.scrollTo(this.rankingList.el.nativeElement);
// set focus to an element at the top of the page for keyboard nav
const focusableEl = this.rankingList.el.nativeElement.querySelector('app-ranking-list button');
setTimeout(() => {
if (focusableEl.length) {
focusableEl[0].focus();
focusableEl[0].blur();
}
}, this.scroll.defaultDuration);
}
private isLocationInvalid(locationIndex: number) {
return locationIndex !== null && (
this.listData[locationIndex][this.dataProperty.value] < 0 ||
this.listData[locationIndex]['evictions'] < 0
);
}
/** Get location selected data for analytics tracking */
private getSelectedData(location: RankingLocation): any {
return {
locationSelected: location.displayName,
<API key>: this.rankings.areaTypes[location.areaType].langKey,
};
}
/** Gets the selected filters for analytics tracking */
private getSelectedFilters() {
return {
area: this.areaType.langKey,
rankBy: this.dataProperty.langKey,
region: this.region
};
}
private trackAreaChange() {
this.analytics.trackEvent('<API key>', this.getSelectedFilters());
}
private trackRankByChange() {
this.analytics.trackEvent('<API key>', this.getSelectedFilters());
}
/** Track when a location is selected */
private <API key>(location: RankingLocation, method = 'list') {
const selectedEvent: any = this.getSelectedData(location);
selectedEvent.<API key> = method;
this.analytics.trackEvent('locationSelection', selectedEvent);
}
/** Track when an option in search is selected. */
private <API key>(location: RankingLocation, term: string) {
this.<API key>(location, 'search');
const searchEvent = {
locationSearchTerm: term, ...this.getSelectedData(location), <API key>: 'search'
};
this.analytics.trackEvent('searchSelection', searchEvent);
}
private setupPageScroll() {
this.scroll.defaultScrollOffset = 0;
this.scroll.verticalOffset$
.map(offset => offset > 600)
.<API key>()
.subscribe(showButton => {
this.debug('show scroll to top button:', showButton);
this.showScrollButton = showButton;
});
}
/** Shows a toast message indicating the data is not available */
private <API key>() {
this.toast.error(
this.translatePipe.transform('RANKINGS.<API key>'),
null,
{messageClass: 'ranking-error'}
);
}
/** gets the query parameters for the current view */
private getQueryParams() {
// this.selectedIndex
const params = {
r: this.region,
a: this.areaType.value,
d: this.dataProperty.value
};
if (this.translate.currentLang !== 'en') {
params['lang'] = this.translate.currentLang;
}
if (this.selectedIndex || this.selectedIndex === 0) {
params['l'] = this.selectedIndex;
}
return params;
}
/**
* Set default tweet parameters with the US and no location selected, has the
* following parameters:
* - areaType: selected area type
* - action: string representing if it was an eviction or filing
* - amount: the average of the top 10 if showing rates, otherwise the total of the top 10
* - year: year for the data
* - link: link to the view
*/
private getDefaultTweet(): string {
// action text
let action = this.isPropJudgments() ?
'RANKINGS.<API key>' : 'RANKINGS.SHARE_FILING_PLURAL';
action = this.translatePipe.transform(action);
// add together top 10 for amount
let amount = this.listData.slice(0, 10).reduce((a, b) => {
return a + b[this.dataProperty.value];
}, 0);
// format number based on if it's a rate or not
amount = this.isRateValue() ?
this.cappedRateValue(amount / 10) : this.decimal.transform(amount);
// add average text if the number is an average rate
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_AVERAGE', { amount }) : amount;
return this.translatePipe.transform('RANKINGS.SHARE_DEFAULT', {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
action,
amount,
year: this.rankings.year,
link: this.platform.currentUrl()
});
}
/**
* Creates the tweet string based on the selected location
*/
private getLocationTweet() {
const location = this.listData[this.selectedIndex];
// if there is no location, exit early
if (!location) { return; }
let amount = this.isRateValue() ?
this.cappedRateValue(location[this.dataProperty.value]) :
this.decimal.transform(location[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.<API key>') :
this.translatePipe.transform('RANKINGS.<API key>');
const category = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_RATE') :
this.translatePipe.transform('RANKINGS.SHARE_TOTAL');
const ranking =
`${this.selectedIndex + 1}${this.rankings.ordinalSuffix(
this.selectedIndex + 1, this.isRateValue()
)}`;
// Needs to be split because of gender in Spanish
const translationKey = this.isRateValue() ?
'RANKINGS.<API key>' : 'RANKINGS.<API key>';
return this.translatePipe.transform(translationKey, {
areaType: this.translatePipe.transform(this.areaType.langKey).toLowerCase(),
region: this.region,
year: this.rankings.year,
amount,
area: location.name,
action,
ranking,
category,
link: this.platform.currentUrl()
});
}
/**
* Creates a tweet for when there is a region selected, but no location
*/
private getRegionTweet() {
const action = this.isPropJudgments() ?
this.translatePipe.transform('RANKINGS.<API key>') :
this.translatePipe.transform('RANKINGS.<API key>');
const state = this.rankings.stateData.find(s => s.name === this.region);
if (state[this.dataProperty.value] < 0) {
return this.getFallbackTweet();
}
let amount = this.isRateValue() ?
this.cappedRateValue(state[this.dataProperty.value]) :
this.decimal.transform(state[this.dataProperty.value]);
amount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_PERCENT_OF', { amount }) :
amount;
const areaType = this.translatePipe.transform(this.areaType.langKey).toLowerCase();
const hadAmount = this.isRateValue() ?
this.translatePipe.transform('RANKINGS.SHARE_HAD_RATE', { areaType }) :
this.translatePipe.transform('RANKINGS.SHARE_HAD_COUNT', { areaType });
const topArea = this.listData.length > 0 ?
this.translatePipe.transform(
'RANKINGS.<API key>', { topArea: this.listData[0].name, hadAmount }
) : '';
// Translate region amount (since possible that it's unavailable)
const regionParams = {
year: this.rankings.year, region: this.region, amount, action
};
const regionAmount = (amount || state[this.dataProperty.value] === 0) ?
this.translatePipe.transform('RANKINGS.SHARE_REGION_AMOUNT', regionParams) :
this.translatePipe.transform('RANKINGS.<API key>', regionParams);
return this.translatePipe.transform('RANKINGS.<API key>', {
regionAmount, topArea, link: this.platform.currentUrl()
});
}
/**
* Creates fallback tweet for states where data is unavailable
*/
private getFallbackTweet() {
return this.translatePipe.transform('RANKINGS.SHARE_FALLBACK', {
link: this.platform.currentUrl()
});
}
/** Sets the focus on the first button in the rankings panel */
private focusPanel() {
if (!this.rankingPanel || !this.rankingPanel.el) { return; }
// use a timeout, the buttons are not immediately available
setTimeout(() => {
const buttons = this.rankingPanel.el.nativeElement.<API key>('button');
if (buttons.length) {
buttons[0].focus();
}
}, 500);
}
/** Scrolls to an item in the list and optionally sets focus */
private scrollToIndex(index: number, focus = false) {
if (!this.rankingList || !this.rankingList.el) { return; }
// set focus back to the list item
const listItems = this.rankingList.el.nativeElement.<API key>('button');
if (listItems.length > index) {
// timeout to allow item to expand first
if (focus) { listItems[index].focus(); }
}
setTimeout(() => { this.scroll.scrollTo(listItems[index]); }, 100);
}
/** Returns true if the data property is eviction judgements */
private isPropJudgments(): boolean {
return this.dataProperty.value.startsWith('e');
}
/** Returns true if all of the user selections are at their default values */
private isDefaultSelection(): boolean {
return this.region === 'United States' &&
!this.selectedIndex && this.selectedIndex !== 0;
}
/** Returns true if a location is selected */
private isLocationSelected(): boolean {
return (this.selectedIndex !== null && this.selectedIndex !== undefined);
}
/** Returns true if the data property is a rate instead of a count */
private isRateValue(): boolean {
return this.dataProperty.value.endsWith('Rate');
}
/** Returns the formatted rate number, with >100 instead of values over */
private cappedRateValue(val: number): string {
return val > 100 ? '>100' : this.decimal.transform(val, '1.1-2');
}
/**
* Update the list data based on the selected UI properties
*/
private updateEvictionList() {
if (this.canRetrieveData) {
this.listData = this.rankings.<API key>(
this.region, this.areaType.value, this.dataProperty.value
);
this.truncatedList = this.listData.slice(0, this.topCount);
// TODO: find highest value including CIs, remove 1.1
this.dataMax = Math.max.apply(
Math, this.truncatedList.map(l => {
return !isNaN(l[this.dataProperty.value]) ? l[this.dataProperty.value] : 0;
})
) * 1.1;
this.updateTweet();
this.changeDetectorRef.detectChanges();
} else {
console.warn('data is not ready yet');
}
}
private debug(...args) {
// tslint:disable-next-line
environment.production || !this._debug ? null : console.debug.apply(console, [ 'evictions: ', ...args]);
}
} |
import { connect } from 'react-redux'
import { increment, doubleAsync } from '../modules/code'
/* This is a container component. Notice it does not contain any JSX,
nor does it import React. This component is **only** responsible for
wiring in the actions and state necessary to render a presentational
component - in this case, the counter: */
import Code from '../components/Code'
/* Object of action creators (can also be function that returns object).
Keys will be passed as props to presentational components. Here we are
implementing our wrapper around increment; the component doesn't care */
const mapDispatchToProps = {
increment : () => increment(1),
doubleAsync
}
const mapStateToProps = (state) => ({
})
export default connect(mapStateToProps, mapDispatchToProps)(Code) |
/* eslint-disable import/no-commonjs, no-var */
// This file only exist to allow the import from '<API key>/server'
// We can't have this import working easily with the current project architecture.
// The main reason is that we require to have the files transpiled at development
// time to allow the import accross Workspaces (node_modules are not transpiled).
// To achieve this we scope all the packages artefacts in the `dist` folder under
// `/cjs` & `/es`. At the end we can require the package as it is with a `main`
// that point to `./dist/cjs/index.js` & `module` that point to the `es` folder.
// But the `/server` import will fallback into this file instead of the correct
// one the `dist` folder.
// We now have the solution for those use cases: private packages. You can have
// nested private packages inside your "main" package. The advantage of this
// approach is to leverage the module resolution of npm. A popular package built
var server = require('./dist/cjs/server');
module.exports = server; |
#ifndef <API key>
#define <API key>
#include "Message.h"
namespace FIX44
{
class <API key> : public Message
{
public:
<API key>() : Message(MsgType()) {}
<API key>(const FIX::Message& m) : Message(m) {}
<API key>(const Message& m) : Message(m) {}
<API key>(const <API key>& m) : Message(m) {}
static FIX::MsgType MsgType() { return FIX::MsgType("AM"); }
<API key>(
const FIX::PosMaintRptID& aPosMaintRptID,
const FIX::PosTransType& aPosTransType,
const FIX::PosMaintAction& aPosMaintAction,
const FIX::OrigPosReqRefID& aOrigPosReqRefID,
const FIX::PosMaintStatus& aPosMaintStatus,
const FIX::<API key>& <API key>,
const FIX::Account& aAccount,
const FIX::AccountType& aAccountType,
const FIX::TransactTime& aTransactTime )
: Message(MsgType())
{
set(aPosMaintRptID);
set(aPosTransType);
set(aPosMaintAction);
set(aOrigPosReqRefID);
set(aPosMaintStatus);
set(<API key>);
set(aAccount);
set(aAccountType);
set(aTransactTime);
}
FIELD_SET(*this, FIX::PosMaintRptID);
FIELD_SET(*this, FIX::PosTransType);
FIELD_SET(*this, FIX::PosReqID);
FIELD_SET(*this, FIX::PosMaintAction);
FIELD_SET(*this, FIX::OrigPosReqRefID);
FIELD_SET(*this, FIX::PosMaintStatus);
FIELD_SET(*this, FIX::PosMaintResult);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::SettlSessID);
FIELD_SET(*this, FIX::SettlSessSubID);
FIELD_SET(*this, FIX::NoPartyIDs);
class NoPartyIDs: public FIX::Group
{
public:
NoPartyIDs() : FIX::Group(453,448,FIX::message_order(448,447,452,802,0)) {}
FIELD_SET(*this, FIX::PartyID);
FIELD_SET(*this, FIX::PartyIDSource);
FIELD_SET(*this, FIX::PartyRole);
FIELD_SET(*this, FIX::NoPartySubIDs);
class NoPartySubIDs: public FIX::Group
{
public:
NoPartySubIDs() : FIX::Group(802,523,FIX::message_order(523,803,0)) {}
FIELD_SET(*this, FIX::PartySubID);
FIELD_SET(*this, FIX::PartySubIDType);
};
};
FIELD_SET(*this, FIX::Account);
FIELD_SET(*this, FIX::AcctIDSource);
FIELD_SET(*this, FIX::AccountType);
FIELD_SET(*this, FIX::Symbol);
FIELD_SET(*this, FIX::SymbolSfx);
FIELD_SET(*this, FIX::SecurityID);
FIELD_SET(*this, FIX::SecurityIDSource);
FIELD_SET(*this, FIX::Product);
FIELD_SET(*this, FIX::CFICode);
FIELD_SET(*this, FIX::SecurityType);
FIELD_SET(*this, FIX::SecuritySubType);
FIELD_SET(*this, FIX::MaturityMonthYear);
FIELD_SET(*this, FIX::MaturityDate);
FIELD_SET(*this, FIX::CouponPaymentDate);
FIELD_SET(*this, FIX::IssueDate);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::RepurchaseTerm);
FIELD_SET(*this, FIX::RepurchaseRate);
FIELD_SET(*this, FIX::Factor);
FIELD_SET(*this, FIX::CreditRating);
FIELD_SET(*this, FIX::InstrRegistry);
FIELD_SET(*this, FIX::CountryOfIssue);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::LocaleOfIssue);
FIELD_SET(*this, FIX::RedemptionDate);
FIELD_SET(*this, FIX::StrikePrice);
FIELD_SET(*this, FIX::StrikeCurrency);
FIELD_SET(*this, FIX::OptAttribute);
FIELD_SET(*this, FIX::ContractMultiplier);
FIELD_SET(*this, FIX::CouponRate);
FIELD_SET(*this, FIX::SecurityExchange);
FIELD_SET(*this, FIX::Issuer);
FIELD_SET(*this, FIX::EncodedIssuerLen);
FIELD_SET(*this, FIX::EncodedIssuer);
FIELD_SET(*this, FIX::SecurityDesc);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::EncodedSecurityDesc);
FIELD_SET(*this, FIX::Pool);
FIELD_SET(*this, FIX::ContractSettlMonth);
FIELD_SET(*this, FIX::CPProgram);
FIELD_SET(*this, FIX::CPRegType);
FIELD_SET(*this, FIX::DatedDate);
FIELD_SET(*this, FIX::InterestAccrualDate);
FIELD_SET(*this, FIX::NoSecurityAltID);
class NoSecurityAltID: public FIX::Group
{
public:
NoSecurityAltID() : FIX::Group(454,455,FIX::message_order(455,456,0)) {}
FIELD_SET(*this, FIX::SecurityAltID);
FIELD_SET(*this, FIX::SecurityAltIDSource);
};
FIELD_SET(*this, FIX::NoEvents);
class NoEvents: public FIX::Group
{
public:
NoEvents() : FIX::Group(864,865,FIX::message_order(865,866,867,868,0)) {}
FIELD_SET(*this, FIX::EventType);
FIELD_SET(*this, FIX::EventDate);
FIELD_SET(*this, FIX::EventPx);
FIELD_SET(*this, FIX::EventText);
};
FIELD_SET(*this, FIX::Currency);
FIELD_SET(*this, FIX::TransactTime);
FIELD_SET(*this, FIX::NoPositions);
class NoPositions: public FIX::Group
{
public:
NoPositions() : FIX::Group(702,703,FIX::message_order(703,704,705,10107,10108,706,539,0)) {}
FIELD_SET(*this, FIX::PosType);
FIELD_SET(*this, FIX::LongQty);
FIELD_SET(*this, FIX::ShortQty);
FIELD_SET(*this, FIX::LongPrice);
FIELD_SET(*this, FIX::ShortPrice);
FIELD_SET(*this, FIX::PosQtyStatus);
FIELD_SET(*this, FIX::NoNestedPartyIDs);
class NoNestedPartyIDs: public FIX::Group
{
public:
NoNestedPartyIDs() : FIX::Group(539,524,FIX::message_order(524,525,538,804,0)) {}
FIELD_SET(*this, FIX::NestedPartyID);
FIELD_SET(*this, FIX::NestedPartyIDSource);
FIELD_SET(*this, FIX::NestedPartyRole);
FIELD_SET(*this, FIX::NoNestedPartySubIDs);
class NoNestedPartySubIDs: public FIX::Group
{
public:
NoNestedPartySubIDs() : FIX::Group(804,545,FIX::message_order(545,805,0)) {}
FIELD_SET(*this, FIX::NestedPartySubID);
FIELD_SET(*this, FIX::<API key>);
};
};
};
FIELD_SET(*this, FIX::NoPosAmt);
class NoPosAmt: public FIX::Group
{
public:
NoPosAmt() : FIX::Group(753,707,FIX::message_order(707,708,0)) {}
FIELD_SET(*this, FIX::PosAmtType);
FIELD_SET(*this, FIX::PosAmt);
};
FIELD_SET(*this, FIX::AdjustmentType);
FIELD_SET(*this, FIX::ThresholdAmount);
FIELD_SET(*this, FIX::Text);
FIELD_SET(*this, FIX::EncodedTextLen);
FIELD_SET(*this, FIX::EncodedText);
FIELD_SET(*this, FIX::NoLegs);
class NoLegs: public FIX::Group
{
public:
NoLegs() : FIX::Group(555,600,FIX::message_order(600,601,602,603,604,607,608,609,764,610,611,248,249,250,251,252,253,257,599,596,597,598,254,612,942,613,614,615,616,617,618,619,620,621,622,623,624,556,740,739,955,956,0)) {}
FIELD_SET(*this, FIX::LegSymbol);
FIELD_SET(*this, FIX::LegSymbolSfx);
FIELD_SET(*this, FIX::LegSecurityID);
FIELD_SET(*this, FIX::LegSecurityIDSource);
FIELD_SET(*this, FIX::LegProduct);
FIELD_SET(*this, FIX::LegCFICode);
FIELD_SET(*this, FIX::LegSecurityType);
FIELD_SET(*this, FIX::LegSecuritySubType);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::LegMaturityDate);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::LegIssueDate);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::LegRepurchaseTerm);
FIELD_SET(*this, FIX::LegRepurchaseRate);
FIELD_SET(*this, FIX::LegFactor);
FIELD_SET(*this, FIX::LegCreditRating);
FIELD_SET(*this, FIX::LegInstrRegistry);
FIELD_SET(*this, FIX::LegCountryOfIssue);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::LegLocaleOfIssue);
FIELD_SET(*this, FIX::LegRedemptionDate);
FIELD_SET(*this, FIX::LegStrikePrice);
FIELD_SET(*this, FIX::LegStrikeCurrency);
FIELD_SET(*this, FIX::LegOptAttribute);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::LegCouponRate);
FIELD_SET(*this, FIX::LegSecurityExchange);
FIELD_SET(*this, FIX::LegIssuer);
FIELD_SET(*this, FIX::EncodedLegIssuerLen);
FIELD_SET(*this, FIX::EncodedLegIssuer);
FIELD_SET(*this, FIX::LegSecurityDesc);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::LegRatioQty);
FIELD_SET(*this, FIX::LegSide);
FIELD_SET(*this, FIX::LegCurrency);
FIELD_SET(*this, FIX::LegPool);
FIELD_SET(*this, FIX::LegDatedDate);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::NoLegSecurityAltID);
class NoLegSecurityAltID: public FIX::Group
{
public:
NoLegSecurityAltID() : FIX::Group(604,605,FIX::message_order(605,606,0)) {}
FIELD_SET(*this, FIX::LegSecurityAltID);
FIELD_SET(*this, FIX::<API key>);
};
};
FIELD_SET(*this, FIX::NoUnderlyings);
class NoUnderlyings: public FIX::Group
{
public:
NoUnderlyings() : FIX::Group(711,311,FIX::message_order(311,312,309,305,457,462,463,310,763,313,542,241,242,243,244,245,246,256,595,592,593,594,247,316,941,317,436,435,308,306,362,363,307,364,365,877,878,318,879,810,882,883,884,885,886,0)) {}
FIELD_SET(*this, FIX::UnderlyingSymbol);
FIELD_SET(*this, FIX::UnderlyingSymbolSfx);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::UnderlyingProduct);
FIELD_SET(*this, FIX::UnderlyingCFICode);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::UnderlyingIssueDate);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::UnderlyingFactor);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::UnderlyingIssuer);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::UnderlyingCPProgram);
FIELD_SET(*this, FIX::UnderlyingCPRegType);
FIELD_SET(*this, FIX::UnderlyingCurrency);
FIELD_SET(*this, FIX::UnderlyingQty);
FIELD_SET(*this, FIX::UnderlyingPx);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::UnderlyingEndPrice);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::UnderlyingEndValue);
FIELD_SET(*this, FIX::<API key>);
class <API key>: public FIX::Group
{
public:
<API key>() : FIX::Group(457,458,FIX::message_order(458,459,0)) {}
FIELD_SET(*this, FIX::<API key>);
FIELD_SET(*this, FIX::<API key>);
};
};
FIELD_SET(*this, FIX::NoTradingSessions);
class NoTradingSessions: public FIX::Group
{
public:
NoTradingSessions() : FIX::Group(386,336,FIX::message_order(336,625,0)) {}
FIELD_SET(*this, FIX::TradingSessionID);
FIELD_SET(*this, FIX::TradingSessionSubID);
};
};
}
#endif |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'easy_cooking',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
); |
// @flow
import * as React from 'react'
import {StyleSheet} from 'react-native'
import type {UnprocessedBusLine} from './types'
import MapView from '@mapbox/<API key>'
import moment from 'moment-timezone'
import {NoticeView} from '../../components/notice'
import type {<API key>} from '../../types'
import {getScheduleForNow, processBusLine} from './lib'
import uniqBy from 'lodash/uniqBy'
import isEqual from 'lodash/isEqual'
const TIMEZONE = 'America/Winnipeg'
const styles = StyleSheet.create({
map: {...StyleSheet.absoluteFillObject},
})
type Props = <API key> & {|
navigation: {
state: {
params: {
line: UnprocessedBusLine,
},
},
},
|}
type State = {|
now: moment,
region: {
latitude: number,
latitudeDelta: number,
longitude: number,
longitudeDelta: number,
},
|}
export class BusMap extends React.PureComponent<Props, State> {
static navigationOptions = (args: {
navigation: {state: {params: {line: UnprocessedBusLine}}},
}) => ({
title: `${args.navigation.state.params.line.line} Map`,
})
_intervalId: ?IntervalID
state = {
now: moment.tz(TIMEZONE),
region: {
latitude: 44.44946671480875,
latitudeDelta: 0.06175530810822494,
longitude: -93.17014753996669,
longitudeDelta: 0.05493163793703104,
},
}
componentDidMount() {
// This updates the screen every second, so that the "next bus" times are
// updated without needing to leave and come back.
this._intervalId = setInterval(this.updateTime, 1000)
}
<API key>() {
this._intervalId && clearInterval(this._intervalId)
}
<API key> = (newRegion: {
latitude: number,
latitudeDelta: number,
longitude: number,
longitudeDelta: number,
}) => {
this.setState(state => {
if (isEqual(state.region, newRegion)) {
return
}
return {region: newRegion}
})
}
updateTime = () => {
this.setState(() => ({now: moment.tz(TIMEZONE)}))
}
render() {
const {now} = this.state
// now = moment.tz('Fri 8:13pm', 'ddd h:mma', true, TIMEZONE)
const lineToDisplay = this.props.navigation.state.params.line
const processedLine = processBusLine(lineToDisplay, now)
const scheduleForToday = getScheduleForNow(processedLine.schedules, now)
if (!scheduleForToday) {
const notice = `No schedule was found for today, ${now.format('dddd')}`
return <NoticeView text={notice} />
}
const <API key> = scheduleForToday.timetable.filter(
entry => entry.coordinates,
)
if (!<API key>.length) {
const today = now.format('dddd')
const msg = `No coordinates have been provided for today's (${today}) schedule on the "${lineToDisplay}" line`
return <NoticeView text={msg} />
}
const markers = uniqBy(<API key>, ({name}) => name)
return (
<MapView
loadingEnabled={true}
<API key>={this.<API key>}
region={this.state.region}
style={styles.map}
>
{markers.map(({name, coordinates: [lat, lng] = []}, i) => (
// we know from <API key> that all of these will have
// coordinates; I just can't convince flow of that without a default value
<MapView.Marker
key={i}
coordinate={{lat, lng}}
title={name}
// description={marker.description}
// TODO: add "next arrival" time as the description
/>
))}
</MapView>
)
}
} |
package com.slack.api.scim.request;
import com.slack.api.scim.SCIMApiRequest;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class UsersSearchRequest implements SCIMApiRequest {
private String token;
// https://api.slack.com/scim#filter
private String filter;
private Integer count;
private Integer startIndex;
} |
#ifndef <API key>
#define <API key>
#include "<API key>.h"
#include "btSoftBody.h"
typedef <API key><btSoftBody*> btSoftBodyArray;
class <API key> : public <API key>
{
btSoftBodyArray m_softBodies;
int m_drawFlags;
bool m_drawNodeTree;
bool m_drawFaceTree;
bool m_drawClusterTree;
btSoftBodyWorldInfo m_sbi;
protected:
virtual void <API key>(btScalar timeStep);
virtual void <API key>( btScalar timeStep);
void updateSoftBodies();
void <API key>();
public:
<API key>(btDispatcher* dispatcher,<API key>* pairCache,btConstraintSolver* constraintSolver,<API key>* <API key>);
virtual ~<API key>();
virtual void debugDrawWorld();
void addSoftBody(btSoftBody* body);
void removeSoftBody(btSoftBody* body);
int getDrawFlags() const { return(m_drawFlags); }
void setDrawFlags(int f) { m_drawFlags=f; }
btSoftBodyWorldInfo& getWorldInfo()
{
return m_sbi;
}
const btSoftBodyWorldInfo& getWorldInfo() const
{
return m_sbi;
}
btSoftBodyArray& getSoftBodyArray()
{
return m_softBodies;
}
const btSoftBodyArray& getSoftBodyArray() const
{
return m_softBodies;
}
};
#endif //<API key> |
// NSAttributedString+DVSTracking.h
// <API key>
#import <Foundation/Foundation.h>
@interface NSAttributedString (DVSTracking)
+ (instancetype) <API key>:(NSString *)string
tracking:(CGFloat)tracking
font:(UIFont *)font;
@end |
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\<API key>;
class AuthController extends Controller
{
use <API key>, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/home';
protected $guard = 'user';
/**
* Create a new authentication controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
} |
# -*- coding: utf-8 -*-
# import sqlite3 as sqlite
import sys
import uuid
from pysqlcipher3 import dbapi2 as sqlite
def main():
print("***************** Welcome to OSS DataMaster-Rigster System *******************")
print("* *")
print("******************************************************************************")
conn = sqlite.connect('DataMasterSystem.db')
c = conn.cursor()
c.execute("PRAGMA key='data_master_system'") # sqlite
try:
c.execute('create table data_master_system (data_master_name text, password text, unique_id text)')
except sqlite.OperationalError as e:
pass
unique_id = uuid.uuid1()
data_masters = c.execute("select * from data_master_system").fetchall()
if len(data_masters) != 0:
data_master_name = input("[*] Input your data master name:\n")
for col in data_masters:
if data_master_name.strip() == col[0]:
print("[!] Data Master Name has existed!")
print("******************************************************************************")
print("* *")
print("*********************** Data Master Rigster Is Failed! ***********************")
sys.exit(-1)
else:
data_master_name = input("[*] Input your data master name:\n")
password = input("[*] Input your password:\n")
repeat_password = input("[*] Input your password again:\n")
if password.strip() != repeat_password.strip():
print("[!] Password is not equal to RePassword!")
print("******************************************************************************")
print("* *")
print("*********************** Data Master Rigster Is Failed! ***********************")
sys.exit(-1)
c.execute('insert into data_master_system values ("{}", "{}", "{}")'.format(data_master_name, password, unique_id))
conn.commit()
c.close()
print("******************************************************************************")
print("* *")
print("********************* Data Master Rigster Is Successful! *********************")
if __name__ == '__main__':
main() |
# This file was generated by the `rspec --init` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# Require this file using `require "spec_helper"` to ensure that it is only
# loaded once.
require 'coveralls'
Coveralls.wear!
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
ENV["RAILS_ENV"] ||= 'test'
# Only the parts of rails we want to use
# if you want everything, use "rails/all"
require "action_controller/railtie"
require "rails/test_unit/railtie"
require 'juvia_rails'
# Define the application and configuration
module Test
class Application < ::Rails::Application
# configuration here if needed
config.active_support.deprecation = :stderr
end
end
# Initialize the application
Test::Application.initialize!
RSpec.configure do |config|
config.<API key> = true
config.<API key> = true
config.filter_run :focus
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
end |
package nl.myndocs.database.migrator.util;
public class Assert {
public static void notNull(Object object, String message) {
if (object == null) {
throw new <API key>(message);
}
}
} |
<!DOCTYPE html>
<html>
<head>
<title>Reflection </title>
<meta charset="UTF-8">
<link href="../styles/main.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Reflection</h1>
<div class="nav">
<ul>
<li><a href="http:/nick-shanks.github.io/index.html">Home</li>
<li><a href="http:/nick-shanks.github.io/blog/c1-reflection-blog.html">Blog 1: Reflection</li></li>
<li><a href="http:/nick-shanks.github.io/blog/<API key>.html">Blog 2: Time and Habits</a></li>
</ul>
</div>
<div class="container">
<p>
Below is a reflection on <a href="https://vimeo.com/85001014">Shereef's Fireside Chat</a></p>
</div>
<img width="1000px" height="400px" src="https://images7.alphacoders.com/314/314550.jpg"/>
<div class="nick">
<h3>By Nick Shanks</h3>
</div>
<p><em>2 July 2016</em></p>
<br>
<h3>What's your take on the DBC/EDA experience?</h3>
<p>My take on what Shereef explained about DBC/EDA is it will be a rollercoaster of learning about yourself and others just as much as it will be about learning code. The experience is going to be what you make of it <em>yourself</em>, not how others are going to make for you. For myself this will be great and like Shereef said, is something most of us need to work on. I know I need to!
</p>
<h3>What are your impressions?</h3>
<p>From this chat, my immediate impression is do not go in with a restaurant mindset! Most of us go in to things we have paid for and expect a service, Shereef used some great examples that made it easy to understand. It's not just that simple. Everything is what <em>you</em> make of it.
</p>
<h3>How do you see yourself engaging with this type of culture?</h3>
<p>I see myself fitting in to this culture well. I am excited to meet new people and work with in a team who is learning and going through the same day to day experiences. I am keen to motivate the next person as much as I am wanting to push and motivate myself.</p>
<h3>Have your expectations of EDA changed? If so, how?</h3>
<p>Definitely more inspired. I was put on to the EDA course by a friend who explained how everything worked, so I did have an idea of what to expect in this regard. I had also done the reading on Engineering Empathy prior to the video but it was great to hear it from a Founding Father to give it that extra importance.</p>
<h3>Are you excited to participate in this kind of learning environment? Does it make you nervous?</h3>
<p>Am I excited? For sure. In the past I have worked for companies where everyone just stuck to themselves and it does not create a fun and inspiring working/learning enviroment. A place where everyone pushes each other to be the best version of themselves excites me. Am I nervous? For sure. But if I wasn't nervous, I don't think it wouldn't mean as much to me. </p>
</body>
</html> |
<?hh // strict
namespace Haku;
use Haku\RequestInterface;
use Haku\Router;
use Haku\Route;
class Application
{
private Router $router;
public function __construct()
{
$this->router = new Router();
}
public function post(string $pattern, (function(...):array<mixed>) $action): Route {
$route = new Route($pattern, $action);
$route->addMethod('POST');
$this->router->add($route);
return $route;
}
public function get(string $pattern, (function(...):array<mixed>) $action): Route {
$route = new Route($pattern, $action);
$route->addMethod('GET');
$this->router->add($route);
return $route;
}
public function put(string $pattern, (function(...):array<mixed>) $action): Route {
$route = new Route($pattern, $action);
$route->addMethod('PUT');
$this->router->add($route);
return $route;
}
public function delete(string $pattern, (function(...):array<mixed>) $action): Route {
$route = new Route($pattern, $action);
$route->addMethod('DELETE');
$this->router->add($route);
return $route;
}
public function run(RequestInterface $request) : void {
$route = $this->router->match($request);
if (!$route) {
http_response_code(404);
echo "No application route was found for that URL path.";
exit();
}
$action = $route->getAction();
$r = new \ReflectionFunction($action);
$arguments = array_map($param ==> {
if ($param->info['type'] === 'Haku\Request') {
return $request;
}
if (!$route->getParams()->containsKey($param->name)) {
throw new \RuntimeException('Cannot set parameter from routing : ' . $param->name);
}
return $route->getParams()->get($param->name);
}, $r->getParameters());
$data = <API key>($action, $arguments);
echo json_encode($data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
}
} |
package bankapp.account;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import bankapp.bank.AccountType;
import bankapp.bank.BankException;
/**
* The class Account represents bank accounts.
* @author Samuel Pulfer
*
*/
public abstract class Account implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Constructs an empty bank account.
* @param nr the account number
* @param pin the PIN of the account
*/
public Account (int nr, String pin) {
this(nr,pin,0.0);
}
/**
* Constructs a bank account.
* @param nr the account number
* @param pin the PIN of the account
* @param balance the initial balance
*/
public Account (int nr, String pin, double balance) {
this.balance = balance;
this.nr = nr;
this.pin = pin;
transactions = new ArrayList<Transaction>();
transactions.add(new Transaction(balance, balance));
}
/**
* The account balance.
*/
protected double balance;
/**
* The number of the account.
*/
protected int nr;
/**
* The PIN of the account
*/
protected String pin = "";
/**
* The transactions of the account.
*/
private List<Transaction> transactions;
// Methods
/**
* Checks the PIN of the account.
* @param pin the PIN to check
* @throws BankException if the PIN is invalid
*/
public void checkPIN(String pin) throws BankException{
if (!pin.equals(this.pin))
throw new BankException("Pin is invalid");
}
/**
* Deposits money into the account.
* @param amount the amount of money to deposit
* @throws BankException if the deposit failed
*/
public synchronized void deposit(double amount) throws BankException {
if (amount >= 0) {
balance = Math.round(100 * (balance + amount)) / 100.0;
transactions.add(new Transaction(amount, balance));
} else {
throw new BankException("Deposit failed");
}
}
/**
* Checks if the account is equal to an another object by the AccountNr.
* @param object the other object
* @return true if the accounts are equal, false otherwise
*/
@Override
public boolean equals(Object object) {
if (object == null)
return false;
if (object instanceof Account) {
Account other = (Account)object;
if (object != null && other.nr == this.nr) {
return true;
}
}
return false;
}
/**
* Gets the balance of the account.
* @return the account balance
*/
public double getBalance() {
return balance;
}
/**
* Gets the number of the account.
* @return the account number
*/
public int getNr() {
return nr;
}
/**
* Takes the AccountNr as hash code.
* @return returns the AccountNr as hash code.
*/
@Override
public int hashCode() {
return nr;
}
/**
* Generates a string representation of the account
*/
@Override
public String toString() {
return getClass().getSimpleName() + " {nr=" + nr + ", balance=" + balance + ", type=" + getType() + "}";
/*
StringBuilder sb = new StringBuilder();
sb.append("AccountNr: " + nr);
sb.append("\nBalance: " + balance);
sb.append("\nPIN: " + pin);
return sb.toString();
*/
}
/**
* Withdraws money from the account.
* @param amount the amount of money to withdraw
* @throws BankException if the withdrawal failed
*/
public synchronized void withdraw(double amount) throws BankException {
if (amount > 0) {
balance = Math.round(100 * (balance - amount)) / 100.0;
transactions.add(new Transaction(0.0 - amount, balance));
} else {
throw new BankException("Withdrawal failed");
}
}
/**
* Withdraws money from the account.
* @param amount the amount of money to withdraw
* @throws BankException if the withdrawal failed
*/
public synchronized void withdraw(int amount) throws BankException {
withdraw((double) amount);
}
/**
* Gets the type of the account.
* @return the account type
*/
public abstract AccountType getType();
/**
* Gets the transactions of the account.
* @return the account transactions
*/
public List<Transaction> getTransactions(){
return transactions;
}
/** Gets the interest rate.
* @return the interest rate
*/
public abstract double getInterestRate();
public synchronized void payInterests() {
try {
if (balance >= 0)
deposit(balance * getInterestRate());
else
withdraw(0.0 - balance * getInterestRate());
} catch (BankException e) {
// This should never happen.
System.out.println("Can't pay interests " + e.getMessage());
}
}
} |
layout: page
published: false
title: "Header Image With Background Color"
subheadline: "Headers With Style"
teaser: "Feeling Responsive allows you to use all kinds of headers. This example shows a header image with a defined background color via front matter."
categories:
- design
tags:
- design
- background color
- header
header:
image: <API key>.jpg
background-color: "#304558"
caption: This is a caption for the header image with link
caption_url: https://unsplash.com/
It's so easy to do. Just define in front matter an image and a background color. Instead of a color you can also use a pattern image. Have a look at the [example with a background pattern]({{ site.url }}/design/<API key>/).
<!--more
## Front Matter Code
{% include alert alert="WARNING: To make this work the value of `background-color` must be inbetween quotes." %}
header:
image: "<API key>.jpg"
background-color: "#fabb00"
caption: This is a caption for the header image with link
caption_url: https://unsplash.com/
All Header-Styles
{: .t60 }
{% include list-posts tag='header' %} |
package com.example.<API key>;
import android.content.Context;
import android.support.test.<API key>;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
@RunWith(AndroidJUnit4.class)
public class <API key> {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = <API key>.getTargetContext();
assertEquals("com.example.<API key>", appContext.getPackageName());
}
} |
# Plugin.js
A better jQuery plugin boilerplate system.
***
## Changelog
v0.5 / 05.24.2012
- Initial release, still developing idea
- Main goals of Plugin.js:
- Acts as a base to extend on for all plugins
- Automatically create instances for each passed in element
- Automatically set a unique ID if the element does not have one
- Create consistent structure for plugins to inherit
- Allow plugins to extend from each other
- Allows you to rename plugins to whatever you'd like |
package com.cezarykluczynski.stapi.etl.template.common.dto.datetime;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor(staticName = "of")
@NoArgsConstructor
public class StardateYearDTO {
private Float stardateFrom;
private Float stardateTo;
private Integer yearFrom;
private Integer yearTo;
} |
#include "Tweener.h"
#include "Actor.h"
#include "ColorRectSprite.h"
#include <limits.h>
namespace oxygine
{
Tween::Tween():_duration(0),
_loops(0),
_percent(0),
_status(status_not_started),
_elapsed(0), _twoSides(false), _ease(ease_linear), _detach(false), _delay(0), _client(0)
{
}
Tween::~Tween()
{
}
void Tween::reset()
{
_elapsed = 0;
_status = status_not_started;
}
void Tween::init(timeMS duration, int loops, bool twoSides, timeMS delay, EASE ease)
{
_duration = duration;
_ease = ease;
_loops = loops;
_twoSides = twoSides;
_delay = delay;
if (_duration <= 0)
{
OX_ASSERT(!"Tweener duration should be more than ZERO");
_duration = 1;
}
}
void Tween::setDoneCallback(EventCallback cb)
{
_cbDone = cb;
}
EventCallback Tween::getDoneCallback() const
{
return _cbDone;
}
void Tween::addDoneCallback(EventCallback cb)
{
addEventListener(TweenEvent::DONE, cb);
}
float Tween::calcEase(EASE ease, float v)
{
float vi;
float r = 0;
const float s = 1.70158f;
switch(ease)
{
case ease_linear:
r = v;
break;
case ease_inExpo:
r = powf(2.0f, 10.0f * (v - 1.0f));
break;
case ease_outExpo:
r = 1.0f - powf(2.0f, -10.0f * v);
break;
case ease_inSin:
r = 1.0f - scalar::cos(v * (MATH_PI/2.0f));
break;
case ease_outSin:
r = scalar::sin(v * (MATH_PI/2.0f));
break;
case ease_inCubic:
r = v * v * v;
break;
case ease_outCubic:
vi = v - 1.0f;
r = vi * vi * vi + 1.0f;
break;
case ease_inOutBack:
{
const float s15 = s * 1.525f;
v *= 2;
if (v < 1)
{
r = v * v * ((s15 + 1) * v - s15);
}
else
{
v-=2;
r = v * v * ((s15 + 1) * v + s15) + 2;
}
r /= 2;
}
break;
case ease_inBack:
r = v * v * ((s + 1) * v - s);
break;
case ease_outBack:
v -= 1;
r = v * v *((s + 1)*v + s) + 1;
break;
default:
OX_ASSERT(!"unsupported ease");
break;
}
return r;
}
float Tween::_calcEase(float v)
{
if (_twoSides)
{
if (v > 0.5f)
v = 1.0f - v;
v *= 2.0f;
}
v = calcEase(_ease, v);
return v;
}
void Tween::complete(timeMS deltaTime)
{
if (_loops == -1)
return;
//if already done
if (_status >= status_done)
return;
OX_ASSERT(_client);
//OX_ASSERT(!"not implemented");
//not started yet because if delay
if (_status == status_delayed)
{
_start(*_client);
_status = status_started;
}
OX_ASSERT(_status == status_started);
//while (_status != status_remove)
{
UpdateState us;
us.dt = deltaTime;
update(*_client, us);
}
OX_ASSERT(_status == status_done);
//_client->removeTween(this);
}
void Tween::start(Actor &actor)
{
_client = &actor;
_status = status_delayed;
if (_delay == 0)
{
_status = status_started;
_start(actor);
}
}
void Tween::update(Actor &actor, const UpdateState &us)
{
_elapsed += us.dt;
switch(_status)
{
case status_delayed:
{
if (_elapsed >= _delay)
{
_status = status_started;
_start(*_client);
}
}
break;
case status_started:
{
if (_duration)
{
timeMS localElapsed = _elapsed - _delay;
int loopsDone = localElapsed / _duration;
_percent = _calcEase(((float)(localElapsed - loopsDone * _duration)) / _duration);
if (_loops > 0 && int(loopsDone) >= _loops)
{
if (_twoSides)
_percent = 0;
else
_percent = 1;
_status = status_done;
}
}
_update(*_client, us);
}
break;
case status_done:
{
done(*_client, us);
}
break;
}
}
void Tween::done(Actor &actor, const UpdateState &us)
{
_done(actor, us);
if (_detach)
{
actor.detach();
}
TweenEvent ev(this, &us);
ev.target = ev.currentTarget = &actor;
ev.tween = this;
if (_cbDone)
_cbDone(&ev);
dispatchEvent(&ev);
_status = status_remove;
}
spTween TweenQueue::add(spTween t)
{
OX_ASSERT(t);
if (!t)
return 0;
_tweens.append(t);
return t;
}
void TweenQueue::complete(timeMS deltaTime)
{
OX_ASSERT("Tween::complete is not supported for TweenQueue");
}
void TweenQueue::_start(Actor &actor)
{
_current = _tweens._first;
if (!_current)
return;
_current->start(actor);
}
void TweenQueue::_update(Actor &actor, const UpdateState &us)
{
_elapsed += us.dt;
if (_current)
{
spTween next = _current->getNextSibling();
_current->update(actor, us);
if (_current->isDone())
{
_current = next;
if (_current)
_current->start(actor);
}
}
if (!_current)
_status = status_done;
}
Actor* TweenEvent::getActor() const
{
return safeCast<Actor*>(currentTarget.get());
}
} |
<html>
<head>
<title>User agent detail - Mozilla/5.0 (Linux; Android 4.2.2; SM-T110 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.59 Safari/537.36</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Linux; Android 4.2.2; SM-T110 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.59 Safari/537.36
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Source result (test suite)</th></tr><tr><td>browscap/browscap<br /><small>/tests/fixtures/issues/issue-525.php</small></td><td>Chrome 39.0</td><td>Android 4.2</td><td>unknown </td><td style="border-left: 1px solid #555">Samsung</td><td>Galaxy Tab 3 Lite 7</td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-test">Detail</a>
<!-- Modal Structure -->
<div id="modal-test" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Testsuite result detail</h4>
<p><pre><code class="php">Array
(
[Browser] => Chrome
[Browser_Type] => Browser
[Browser_Bits] => 32
[Browser_Maker] => Google Inc
[Version] => 39.0
[MajorVer] => 39
[MinorVer] => 0
[Platform] => Android
[Platform_Version] => 4.2
[Platform_Bits] => 32
[Platform_Maker] => Google Inc
[isMobileDevice] => 1
[isTablet] => 1
[Crawler] =>
[JavaScript] => 1
[Cookies] => 1
[Frames] => 1
[IFrames] => 1
[Tables] => 1
[Device_Name] => Galaxy Tab 3 Lite 7
[Device_Maker] => Samsung
[Device_Type] => Tablet
[<API key>] => touchscreen
[Device_Code_Name] => SM-T110
[Device_Brand_Name] => Samsung
[<API key>] => Blink
[<API key>] => unknown
[<API key>] => Google Inc
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapPhp<br /><small>6012</small></td><td>Chrome 39.0</td><td>Blink </td><td>Android 4.2</td><td style="border-left: 1px solid #555">Samsung</td><td>Galaxy Tab 3 Lite 7</td><td>Tablet</td><td>yes</td><td>yes</td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.04501</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#<API key>">Detail</a>
<!-- Modal Structure -->
<div id="<API key>" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*android.4\.2.*sm\-t110 build\/.*\) applewebkit\/.* \(khtml, like gecko\) chrome\/39\..*safari\/.*$/ |
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>wgbow</title>
<link rel="stylesheet" type="text/css" href="csound.css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
<link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
<link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" />
<link rel="prev" href="weibull.html" title="weibull" />
<link rel="next" href="wgbowedbar.html" title="wgbowedbar" />
</head>
<body>
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">wgbow</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="weibull.html">Précédent</a> </td>
<th width="60%" align="center">Opcodes et opérateurs de l'orchestre</th>
<td width="20%" align="right"> <a accesskey="n" href="wgbowedbar.html">Suivant</a></td>
</tr>
</table>
<hr />
</div>
<div class="refentry">
<a id="wgbow"></a>
<div class="titlepage"></div>
<a id="IndexWgbow" class="indexterm"></a>
<div class="refnamediv">
<h2>
<span class="refentrytitle">wgbow</span>
</h2>
<p>wgbow —
Simule un son de corde frottée.
</p>
</div>
<div class="refsect1">
<a id="idm47887612550528"></a>
<h2>Description</h2>
<p>
La sortie audio simule un son de corde frottée, réalisé au moyen d'un
modèle physique développé par Perry Cook, mais recodé pour Csound.
</p>
</div>
<div class="refsect1">
<a id="idm47887612548880"></a>
<h2>Syntaxe</h2>
<pre class="synopsis">ares <span class="command"><strong>wgbow</strong></span> kamp, kfreq, kpres, krat, kvibf, kvamp \
[, ifn] [, iminfreq]</pre>
</div>
<div class="refsect1">
<a id="idm47887612546848"></a>
<h2>Initialisation</h2>
<p>
<span class="emphasis"><em>ifn</em></span> -- table facultative contenant la forme du
vibrato, par défaut une table de sinus.
</p>
<p>
<span class="emphasis"><em>iminfreq</em></span> (facultatif)
l'instrument sera joué. Si elle est omise, elle prend la valeur initiale de
<span class="emphasis"><em>kfreq</em></span>. Si <span class="emphasis"><em>iminfreq</em></span> est négative,
l'initialisation est ignorée.
</p>
</div>
<div class="refsect1">
<a id="idm47887612542976"></a>
<h2>Exécution</h2>
<p>
Une note est jouée sur un instrument de type corde, avec les arguments ci-dessous.
</p>
<p>
<span class="emphasis"><em>kamp</em></span> -- amplitude de la note.
</p>
<p>
<span class="emphasis"><em>kfreq</em></span>
</p>
<p>
<span class="emphasis"><em>kpres</em></span>
sur la corde. Les valeurs doivent se situer autour de 3. L'intervalle utile
va approximativement de 1 à 5.
</p>
<p>
<span class="emphasis"><em>krat</em></span> -- la position de l'archet le long de la corde. Le
jeu habituel se fait environ à 0.127236. L'intervalle recommandé va de 0.025
à 0.23.
</p>
<p>
<span class="emphasis"><em>kvibf</em></span>
recommandé va de 0 à 12.
</p>
<p>
<span class="emphasis"><em>kvamp</em></span> -- l'amplitude du vibrato.
</p>
</div>
<div class="refsect1">
<a id="idm47887612535760"></a>
<h2>Exemples</h2>
<p>
Voici un exemple de l'opcode wgbow. Il utilise le fichier
<a class="ulink" href="examples/wgbow.csd" target="_top"><em class="citetitle">wgbow.csd</em></a>.
</p>
<div class="example">
<a id="idm47887612533904"></a>
<p class="title">
<strong>Exemple 1074. Exemple de l'opcode wgbow.</strong>
</p>
<div class="example-contents">
<p>Voir les sections <a class="link" href="UsingRealTime.html" title="Audio en temps réel"><em class="citetitle">Audio en Temps Réel</em></a>
et <a class="link" href="CommandFlags.html" title="Ligne de commande de Csound"><em class="citetitle">Options de la Ligne de Commande</em></a> pour plus
d'information sur l'utilisation des options de la ligne de commande.</p>
<div class="refsect1">
<a id="idm47887495196512"></a>
<pre class="programlisting">
<span class="csdtag"><CsoundSynthesizer></span>
<span class="csdtag"><CsOptions></span>
<span class="comment">; Select audio/midi flags here according to platform</span>
-odac <span class="comment">;;;realtime audio out</span>
<span class="comment">;-iadc ;;;uncomment -iadc if RT audio input is needed too</span>
<span class="comment">; For Non-realtime ouput leave only the line below:</span>
<span class="comment">; -o wgbow.wav -W ;;; for file output any platform</span>
<span class="csdtag"></CsOptions></span>
<span class="csdtag"><CsInstruments></span>
<span class="ohdr">sr</span> <span class="op">=</span> 44100
<span class="ohdr">ksmps</span> <span class="op">=</span> 32
<span class="ohdr">nchnls</span> <span class="op">=</span> 2
<span class="ohdr">0dbfs</span> <span class="op">=</span> 1
<span class="oblock">instr</span> 1
kpres <span class="op">=</span> p4 <span class="comment">;pressure value</span>
krat <span class="op">=</span> p5 <span class="comment">;position along string</span>
kvibf <span class="op">=</span> 6.12723
kvib <span class="opc">linseg</span> 0, 0.5, 0, 1, 1, p3<span class="op">-</span>0.5, 1 <span class="comment">; amplitude envelope for the vibrato. </span>
kvamp <span class="op">=</span> kvib <span class="op">*</span> 0.01
asig <span class="opc">wgbow</span> .7, 55, kpres, krat, kvibf, kvamp, 1
<span class="opc">outs</span> asig, asig
<span class="oblock">endin</span>
<span class="csdtag"></CsInstruments></span>
<span class="csdtag"><CsScore></span>
<span class="stamnt">f</span> 1 0 2048 10 1 <span class="comment">;sine wave</span>
<span class="stamnt">i</span> 1 0 3 3 0.127236
<span class="stamnt">i</span> 1 + 3 5 0.127236
<span class="stamnt">i</span> 1 + 3 5 0.23
<span class="stamnt">e</span>
<span class="csdtag"></CsScore></span>
<span class="csdtag"></CsoundSynthesizer></span>
</pre>
</div>
</div>
</div>
<p><br class="example-break" />
</p>
</div>
<div class="refsect1">
<a id="idm47887612529600"></a>
<h2>Crédits</h2>
<p>
</p>
<table border="0" summary="Simple list" class="simplelist">
<tr>
<td>Auteur : John ffitch (d'après Perry Cook)</td>
</tr>
<tr>
<td>Université de Bath, Codemist Ltd.</td>
</tr>
<tr>
<td>Bath, UK</td>
</tr>
</table>
<p>
</p>
<p>Nouveau dans la version 3.47 de Csound</p>
<p><span class="emphasis"><em>ifn</em></span> est devenu facultatif dans la version 6.06</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="weibull.html">Précédent</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="OpcodesTop.html">Niveau supérieur</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="wgbowedbar.html">Suivant</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">weibull </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Sommaire</a>
</td>
<td width="40%" align="right" valign="top"> wgbowedbar</td>
</tr>
</table>
</div>
</body>
</html> |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# ** PTS -- Python Toolkit for working with SKIRT **
# Import the relevant PTS classes and modules
from pts.core.basics.configuration import <API key>
# Create the configuration
definition = <API key>()
# Add optional arguments
definition.add_section("wavelengths")
definition.sections["wavelengths"].add_optional("unit", str, "the unit of the wavelengths", "micron")
definition.sections["wavelengths"].add_optional("min", float, "the minimum wavelength", 0.09)
definition.sections["wavelengths"].add_optional("max", float, "the maximum wavelength", 2000)
definition.sections["wavelengths"].add_optional("npoints", int, "the number of wavelength points", 100)
definition.sections["wavelengths"].add_optional("min_zoom", float, "the minimum wavelength of the zoomed-in grid", 1)
definition.sections["wavelengths"].add_optional("max_zoom", float, "the maximum wavelength of the zoomed-in grid", 30)
definition.sections["wavelengths"].add_optional("npoints_zoom", int, "the number of wavelength points in the zoomed-in grid", 100)
definition.add_optional("packages", float, "the number of photon packages per wavelength", 2e5)
definition.add_flag("selfabsorption", "enable dust self-absorption")
definition.add_optional("dust_grid", str, "the type of dust grid to use (bintree, octtree or cartesian)", "bintree") |
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>App Engine Python SDK: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="common.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="gae-python.logo.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">App Engine Python SDK
 <span id="projectnumber">v1.6.9 rev.445</span>
</div>
<div id="projectbrief">The Python runtime is available as an experimental Preview feature.</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.7 -->
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>google</b></li><li class="navelem"><b>appengine</b></li><li class="navelem"><b>api</b></li><li class="navelem"><b>system</b></li><li class="navelem"><b>system_service_pb</b></li><li class="navelem"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">SystemServiceError</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">google.appengine.api.system.system_service_pb.SystemServiceError Member List</div> </div>
</div><!--header
<div class="contents">
<p>This is the complete list of members for <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>__init__</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>__str__</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>BACKEND_REQUIRED</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ByteSize</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ByteSizePartial</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>Clear</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Equals</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>ErrorCode_Name</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ErrorCode_Name</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>INTERNAL_ERROR</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>IsInitialized</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>LIMIT_REACHED</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>MergeFrom</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>OK</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"><span class="mlabel">static</span></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>OutputPartial</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0"><td class="entry"><b>OutputUnchecked</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>TryMerge</b> (defined in <a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a>)</td><td class="entry"><a class="el" href="classgoogle_1_1appengine_1_1api_1_1system_1_1system__service__pb_1_1_system_service_error.html">google.appengine.api.system.system_service_pb.SystemServiceError</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
<address class="footer">
<small>Maintained by <a href="http:
</address> |
package com.punyal.symbiotic.core.feature.wheelloader;
import static com.punyal.symbiotic.constants.ConstantsNet.RESOURCE_ANGLE;
import com.punyal.symbiotic.core.Core;
import com.punyal.symbiotic.core.net.CoapObserver;
import org.eclipse.californium.core.CoapResponse;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class AngleThread extends Thread {
private final Core core;
private boolean running;
private final CoapObserver observer;
public AngleThread(final Core core) {
this.core = core;
this.setDaemon(true);
observer = new CoapObserver(core, RESOURCE_ANGLE) {
@Override
public void incomingData(CoapResponse response) {
try {
//System.out.println(response.getResponseText());
JSONObject json = (JSONObject) JSONValue.parse(response.getResponseText());
//System.out.println(json.get("v"));
core.getStatus().setWheelLoaderAngle(-1*(Double.parseDouble(json.get("v").toString())+14));
} catch( <API key> ex) {}
}
@Override
public void error() {
throw new <API key>("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
};
}
public void startThread() {
this.start();
observer.startObserve();
}
public void stopThread() {
running = false;
observer.stopObserve();
}
@Override
public void run() {
try {
while (running) {
// process data here....
try {
Thread.sleep(1000); // 1 s
} catch (<API key> ex) {
Thread.currentThread().interrupt(); // This should kill it propertly
}
}
}
finally {
System.out.println("Killing AngleThread");
}
}
} |
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
<?php echo $title;?>
<small>Semua data seminar saya</small>
</h1>
<ol class="breadcrumb">
<li><a href="<?php echo site_url('panitia')?>"><i class="fa fa-dashboard"></i>Home</a></li>
<li><a class="active"><?php echo $title;?></a></li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<script type="text/javascript">
<?php //$this->session->flashdata('bounce');?>
<?php $this->session->flashdata('notification');?>
</script>
<div class="row">
<div class="col-xs-12">
<!-- Default box -->
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title"><?php echo $seminar[0]->judul;?></h3>
<div class="box-tools pull-right">
<!--<button class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Minimize"><i class="fa fa-minus"></i></button>
<button class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove"><i class="fa fa-times"></i></button>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-4">
<center><img src="<?php echo base_url('uploads/seminar/').$seminar[0]->foto;?>" width="300" height="400"></center>
</div>
<div class="col-xs-8">
<table class="table table-striped">
<tr>
<th class="col-xs-4">Tanggal Acara</th>
<td class="col-xs-8"><?php echo $seminar[0]->tanggal;?></td>
</tr>
<tr>
<th class="col-xs-4">Harga Tiket</th>
<td class="col-xs-8"><?php echo $seminar[0]->harga;?></td>
</tr>
<tr>
<th class="col-xs-4">Target Peserta</th>
<td class="col-xs-8"><?php echo $seminar[0]->peserta;?></td>
</tr>
<tr>
<th class="col-xs-4">Persentase Peserta Mendaftar</th>
<td class="col-xs-8">
<div class="progress progress-xs progress-striped active">
<div class="progress-bar progress-bar-info" style="width: <?php echo $kuota_peserta.'%';?>"></div>
</div><?php echo $kuota_peserta."%";?>
</td>
</tr>
<tr>
<th>Status Seminar</th>
<?php
if ($kuota_peserta<100) {
echo "<td>Pendaftaran masih dibuka</td>";
} else {
echo "<td class='text-red'>Pendaftaran sudah ditutup</td>";
}
?>
</tr>
<tr>
<th class="col-xs-4">Deskripsi</th>
<td class="col-xs-8"><?php echo $seminar[0]->deskripsi;?></td>
</tr>
</table>
</div>
</div>
<br>
</div><!-- /.box-body -->
<div class="box-footer">
<a class="btn btn-primary btn-flat" href="<?php echo site_url('panitia/editSeminar/'.$seminar[0]->id)?>">Edit</a>
<!--<a class="btn btn-danger btn-flat" href="<?php echo site_url('panitia/hapusSeminar/'.$sem->id)?>">Hapus</a>-->
<a onclick="hapus('<?php echo $seminar[0]->id; ?>')" class="btn btn-danger btn-flat"> Hapus</a>
<a class="btn bg-maroon btn-flat" href="<?php echo site_url('panitia/lihatLaporanSeminar/'.$seminar[0]->id)?>">Laporan</a>
<a class="btn bg-purple btn-flat" href="<?php echo site_url('panitia/managePesertaById/'.$seminar[0]->id)?>">Manage Peserta</a>
<a href="javascript:history.go(-1)" class="pull-right">Kembali</a>
</div><!-- /.box-footer-->
</div><!-- /.box -->
</div>
</div>
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
<script type="text/javascript">
function hapus(id){
swal({
title: "Yakin ingin menghapus ?",
text: "Data akan dihapus dari sistem",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Ya, Hapus!",
cancelButtonText: "Tidak, Batal!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
var link = "<?php echo site_url('panitia/hapusSeminar/'); ?>"+id;
window.location = link;
//swal("Terhapus!", "Data seminar berhasil dihapus", "success");
} else {
swal("Batal", "Anda batal menghapus", "error");
}
});
}
</script> |
-----------Import modules---------------
import argparse
import nucleoatac.Magic
from nucleoatac import __version__
def nucleoatac_main(args):
"""The Main function for calling nucleoatac
"""
#Parse options...
call = args.call
parser = nucleoatac_parser()
if call == "occ":
from nucleoatac.run_occ import run_occ
print('
run_occ(args)
elif call == "vprocess":
from nucleoatac.run_vprocess import run_vprocess
print('
run_vprocess(args)
elif call == "nuc":
from nucleoatac.run_nuc import run_nuc
print('
run_nuc(args)
elif call == "merge":
from nucleoatac.merge import run_merge
print('
run_merge(args)
elif call == "nfr":
from nucleoatac.run_nfr import run_nfr
print('
run_nfr(args)
elif call == "run":
occ_args = parser.parse_args(map(str,['occ','--bed',args.bed,'--bam',args.bam,
'--fasta', args.fasta, '--pwm', args.pwm,
'--out',args.out,'--cores',args.cores]))
vprocess_args = parser.parse_args(['vprocess','--sizes',args.out+'.nuc_dist.txt','--out',args.out])
nuc_args_list = ['nuc','--bed',args.bed,'--bam',args.bam,'--out',args.out,'--cores', str(args.cores),
'--occ_track', args.out + '.occ.bedgraph.gz','--vmat', args.out + '.VMat',
'--fasta', args.fasta, '--pwm', args.pwm, '--sizes', args.out + '.fragmentsizes.txt']
if args.write_all:
nuc_args_list.extend(['--write_all'])
nuc_args = parser.parse_args(nuc_args_list)
merge_args = parser.parse_args(['merge','--occpeaks',args.out +'.occpeaks.bed.gz','--nucpos',args.out+'.nucpos.bed.gz',
'--out',args.out])
nfr_args = parser.parse_args(['nfr','--bed', args.bed, '--occ_track', args.out + '.occ.bedgraph.gz', '--calls',
args.out + '.nucmap_combined.bed.gz','--out',args.out, '--fasta', args.fasta,
'--pwm', args.pwm , '--bam', args.bam])
from nucleoatac.run_occ import run_occ
from nucleoatac.run_vprocess import run_vprocess
from nucleoatac.run_nuc import run_nuc
from nucleoatac.merge import run_merge
from nucleoatac.run_nfr import run_nfr
print('
run_occ(occ_args)
print('
run_vprocess(vprocess_args)
print('
run_nuc(nuc_args)
print('
run_merge(merge_args)
print('
run_nfr(nfr_args)
def nucleoatac_parser():
"""Prepares argparse object
"""
argparser = argparse.ArgumentParser(description = "%(prog)s -- Nucleosome Calling for ATAC-Seq",
epilog = "For command line options for each command, type %(prog)s COMMAND -h")
argparser.add_argument("--version", action="version", version="%(prog)s "+__version__)
subparsers = argparser.add_subparsers(dest = 'call' )
add_run_parser( subparsers)
add_occ_parser( subparsers)
add_vprocess_parser( subparsers)
add_nuc_parser( subparsers)
add_merge_parser( subparsers)
add_nfr_parser( subparsers)
return argparser
def add_occ_parser( subparsers):
"""Add argument parsers for the occ utility
"""
parser = subparsers.add_parser("occ", help = "nucleoatac function: Call nucleosome occupancy")
group1 = parser.add_argument_group('Required', 'Necessary arguments')
group1.add_argument('--bed', metavar='bed_file' , help = 'Peaks in bed format', required=True)
group1.add_argument('--bam', metavar='bam_file',
help = 'Sorted (and indexed) BAM file', required=True)
group1.add_argument('--out', metavar='basename',
help="give output basename", required = True)
group4 = parser.add_argument_group("Bias calculation information","Highly recommended. If fasta is not provided, will not calculate bias")
group4.add_argument('--fasta', metavar = 'genome_seq',
help = 'Indexed fasta file')
group4.add_argument('--pwm', metavar = 'Tn5_PWM', help = "PWM descriptor file. Default is Human.PWM.txt included in package", default = "Human")
group2 = parser.add_argument_group('General Options', '')
group2.add_argument('--sizes', metavar = 'fragmentsizes_file',
help = "File with fragment size distribution. Use if don't want calculation of fragment size")
group2.add_argument('--cores', metavar = 'int',default=1,
help='Number of cores to use',type=int)
group3 = parser.add_argument_group('Occupancy parameter', 'Change with caution')
group3.add_argument('--upper',metavar="int",default=251,
help="upper limit in insert size. default is 251",type=int)
group3.add_argument('--flank',metavar="int",default=60,
help="Distance on each side of dyad to include for local occ calculation. Default is 60.",type=int)
group3.add_argument('--min_occ', metavar = "float", default=0.1,type=float,
help="Occupancy cutoff for determining nucleosome distribution. Default is 0.1")
group3.add_argument('--nuc_sep',metavar='int',default=120,type=int,
help = "minimum separation between occupany peaks. Default is 120.")
group3.add_argument('--confidence_interval', metavar='float',default=0.9,type=float,
help = "confidence interval level for lower and upper bounds. default is 0.9, should be between 0 and 1")
group3.add_argument('--step', metavar = 'int', default = 5, type=int,
help= "step size along genome for comuting occ. Default is 5. Should be odd, or will be subtracted by 1")
return
def add_merge_parser( subparsers):
"""Add argument parser for merge utility"""
parser = subparsers.add_parser("merge", help = "nucleoatac function: Merge occ and nuc calls")
group1 = parser.add_argument_group('Required', 'Necessary arguments')
group1.add_argument('--occpeaks', metavar = 'occpeaks_file', required = True,
help = "Output from occ utility")
group1.add_argument('--nucpos', metavar = 'nucpos_file', required = True,
help = "Output from nuc utility")
group2 = parser.add_argument_group("Options","optional")
group2.add_argument('--out', metavar = 'out_basename', help = "output file basename")
group2.add_argument('--sep', metavar = 'min_separation', default = 120,
help = "minimum separation between call")
group2.add_argument('--min_occ', metavar = 'min_occ', default = 0.1,
help = "minimum lower bound occupancy of nucleosomes to be considered for excluding NFR. default is 0.1")
def add_nfr_parser( subparsers):
"""Add argument parser for nfr utility
"""
parser = subparsers.add_parser("nfr", help = "nucleoatac function: Call NFRs")
group1 = parser.add_argument_group('Required', 'Necessary arguments')
group1.add_argument('--bed', metavar='bed_file' , help = 'Peaks in bed format', required=True)
group1.add_argument('--occ_track', metavar = 'occ_file', required = True,
help = "bgzip compressed, tabix-indexed bedgraph file with occcupancy track.")
group1.add_argument('--calls', metavar = 'nucpos_file', required = True,
help = "bed file with nucleosome center calls")
group6 = parser.add_argument_group("Insertion track options","Either input insertion track or bamfile")
group6.add_argument('--ins_track', metavar = 'ins_file',
help = "bgzip compressed, tabix-indexed bedgraph file with insertion track. will be generated if not included")
group6.add_argument('--bam', metavar='bam_file',
help = 'Sorted (and indexed) BAM file')
group4 = parser.add_argument_group("Bias calculation information","Highly recommended. If fasta is not provided, will not calculate bias")
group4.add_argument('--fasta', metavar = 'genome_seq',
help = 'Indexed fasta file')
group4.add_argument('--pwm', metavar = 'Tn5_PWM', help = "PWM descriptor file. Default is Human.PWM.txt included in package", default = "Human")
group2 = parser.add_argument_group("General options","optional")
group2.add_argument('--out', metavar = 'out_basename', help = "output file basename")
group2.add_argument('--cores', metavar = 'num_cores',default=1,
help='Number of cores to use',type=int)
group5 = parser.add_argument_group("NFR determination parameters")
group5.add_argument('--max_occ', metavar= 'float', default = 0.1,
help = 'Maximum mean occupancy for NFR. Default is 0.1', type = float)
group5.add_argument('--max_occ_upper', metavar= 'float', default = 0.25,
help = 'Maximum for minimum of upper bound occupancy in NFR. Default is 0.25', type = float)
def add_vprocess_parser( subparsers):
"""Add argument parsers for the vprocess utility
"""
parser = subparsers.add_parser("vprocess", help = "nucleoatac function: Make processed vplot to use for nucleosome calling")
group1 = parser.add_argument_group('Required', 'Necessary arguments')
group1.add_argument('--out', metavar='output_basename',required=True)
group2 = parser.add_argument_group('VPlot and Insert Size Options', 'Optional')
group2.add_argument('--sizes', metavar='file' , help = 'Insert distribution file')
group2.add_argument('--vplot', metavar='vmat_file',
help = 'Accepts VMat file. Default is Vplot from S. Cer.',
default = nucleoatac.Magic.default_vplot)
group3 = parser.add_argument_group('Size parameers', 'Use sensible values')
group3.add_argument('--lower',metavar="int",default=105,
help="lower limit (inclusive) in insert size. default is 105",type=int)
group3.add_argument('--upper',metavar="int",default=251,
help="upper limit (exclusive) in insert size. default 251",type=int)
group3.add_argument('--flank',metavar="int",default=60,
help="distance on each side of dyad to include",type=int)
group4 = parser.add_argument_group('Options', '')
group4.add_argument('--smooth', metavar = "float", default = 0.75, type = float,
help="SD to use for gaussian smoothing. Use 0 for no smoothing.")
group4.add_argument('--plot_extra', action='store_true',default=False,
help="Make some additional plots")
return
def add_nuc_parser( subparsers):
"""Add argument parsers for the nuc utility
"""
parser = subparsers.add_parser("nuc", help = "nucleoatac function: Call nucleosome positions and make signal tracks")
group1 = parser.add_argument_group('Required', 'Necessary arguments')
group1.add_argument('--bed', metavar='bed_file' , help = 'Regions for which \
to do stuff.', required=True)
group1.add_argument('--vmat', metavar='vdensity_file', help = "VMat object", required=True)
group1.add_argument('--bam', metavar='bam_file',
help = 'Accepts sorted BAM file', required=True)
group1.add_argument('--out', metavar='basename',
help="give output basename", required = True)
group2 = parser.add_argument_group('Bias options',"If --fasta not provided, bias not calculated")
group2.add_argument('--fasta', metavar = 'genome_seq',
help = 'Indexed fasta file')
group2.add_argument('--pwm', metavar = 'Tn5_PWM', help = "PWM descriptor file. Default is Human.PWM.txt included in package", default = "Human")
group3 = parser.add_argument_group('General options', '')
group3.add_argument('--sizes', metavar = 'fragmentsizes_file',
help = "File with fragment size distribution. Use if don't want calculation of fragment size")
group3.add_argument('--occ_track', metavar = 'occ_file',
help = "bgzip compressed, tabix-indexed bedgraph file with occcupancy track. Otherwise occ not determined for nuc positions.")
group3.add_argument('--cores', metavar = 'num_cores',default=1,
help='Number of cores to use',type=int)
group3.add_argument('--write_all', action="store_true", default = False,
help="write all tracks")
group3.add_argument('--not_atac', dest = "atac", action="store_false", default = True,
help="data is not atac-seq")
group5 = parser.add_argument_group('Nucleosome calling parameters','Change with caution')
group5.add_argument('--min_z', metavar='float', default = 3,
help = 'Z-score threshold for nucleosome calls. Default is 3', type = float)
group5.add_argument('--min_lr', metavar='float', default = 0,
help = 'Log likelihood ratio threshold for nucleosome calls. Default is 0', type = float)
group5.add_argument('--nuc_sep',metavar='int',default=120,type=int,
help = "Minimum separation between non-redundant nucleosomes. Default is 120")
group5.add_argument('--redundant_sep',metavar='int',default=25,type=int,
help = "Minimum separation between redundant nucleosomes. Not recommended to be below 15. Default is 25")
group5.add_argument('--sd',metavar='int', type=int,
default=10, help = "Standard deviation for smoothing. Affect the \
resolution at which nucleosomes can be positioned. Not recommended to \
exceed 25 or to be smaller than 10. Default is 10" )
return
def add_run_parser( subparsers):
"""Add argument parsers for the run utility
"""
parser = subparsers.add_parser("run", help = "Main nucleoatac utility-- runs through occupancy determination & calling nuc positions")
group1 = parser.add_argument_group('Required', 'Necessary arguments')
group1.add_argument('--bed', metavar='bed_file' , help = 'Regions for which \
to do stuff.', required=True)
group1.add_argument('--bam', metavar='bam_file',
help = 'Accepts sorted BAM file', required=True)
group1.add_argument('--out', metavar='output_basename',
help="give output basename", required=True)
group1.add_argument('--fasta', metavar = 'genome_seq',
help = 'Indexed fasta file', required=True)
group4 = parser.add_argument_group("Bias calculation parameters","")
group4.add_argument('--pwm', metavar = 'Tn5_PWM', help = "PWM descriptor file. Default is Human.PWM.txt included in package", default = "Human")
group3 = parser.add_argument_group('General options', '')
group3.add_argument('--cores', metavar = 'num_cores',default=1,
help='Number of cores to use',type=int)
group3.add_argument('--write_all', action="store_true", default = False,
help="write all tracks")
return |
package peer
import (
"net"
"time"
"github.com/cenkalti/rain/internal/peerconn"
"github.com/cenkalti/rain/internal/peerprotocol"
"github.com/cenkalti/rain/internal/pexlist"
)
type pex struct {
conn *peerconn.Conn
extID uint8
// Contains added and dropped peers.
pexList *pexlist.PEXList
pexAddPeerC chan *net.TCPAddr
pexDropPeerC chan *net.TCPAddr
closeC chan struct{}
doneC chan struct{}
}
func newPEX(conn *peerconn.Conn, extID uint8, initialPeers map[*Peer]struct{}, recentlySeen *pexlist.RecentlySeen) *pex {
pl := pexlist.NewWithRecentlySeen(recentlySeen.Peers())
for pe := range initialPeers {
if pe.Addr().String() != conn.Addr().String() {
pl.Add(pe.Addr())
}
}
return &pex{
conn: conn,
extID: extID,
pexList: pl,
pexAddPeerC: make(chan *net.TCPAddr),
pexDropPeerC: make(chan *net.TCPAddr),
closeC: make(chan struct{}),
doneC: make(chan struct{}),
}
}
func (p *pex) close() {
close(p.closeC)
<-p.doneC
}
func (p *pex) run() {
defer close(p.doneC)
p.pexFlushPeers()
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case addr := <-p.pexAddPeerC:
p.pexList.Add(addr)
case addr := <-p.pexDropPeerC:
p.pexList.Drop(addr)
case <-ticker.C:
p.pexFlushPeers()
case <-p.closeC:
return
}
}
}
func (p *pex) Add(addr *net.TCPAddr) {
select {
case p.pexAddPeerC <- addr:
case <-p.doneC:
}
}
func (p *pex) Drop(addr *net.TCPAddr) {
select {
case p.pexDropPeerC <- addr:
case <-p.doneC:
}
}
func (p *pex) pexFlushPeers() {
added, dropped := p.pexList.Flush()
if len(added) == 0 && len(dropped) == 0 {
return
}
extPEXMsg := peerprotocol.ExtensionPEXMessage{
Added: added,
Dropped: dropped,
}
msg := peerprotocol.ExtensionMessage{
ExtendedMessageID: p.extID,
Payload: extPEXMsg,
}
p.conn.SendMessage(msg)
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SpaceKanjiAdmin
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
} |
<?php
/* TwigBundle:Exception:error.html.twig */
class <API key> extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<!DOCTYPE html>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<title>An Error Occurred: ";
// line 5
echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true);
echo "</title>
</head>
<body>
<h1>Oops! An Error Occurred</h1>
<h2>The server returned a \"";
// line 9
echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : null), "html", null, true);
echo " ";
echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true);
echo "\".</h2>
<div>
Something is broken. Please e-mail us at [email] and let us know
what you were doing when this error occurred. We will fix it as soon
as possible. Sorry for any inconvenience caused.
</div>
</body>
</html>
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:error.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 30 => 9, 23 => 5, 17 => 1,);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Diagnostics;
using ULog;
using WebRequest.Common;
namespace WebRequest.Http
{
class JSonRequest : HttpRequest
{
public JSonRequest(string uri, JObject jObject, string method = HttpConst.HttpMethod_Post)
: base(uri, method)
{
#if DEBUG
Object = jObject;
#endif
DiagnoseHelper.CheckArgument(jObject, "jObject can not be null");
Serialize2Stream(jObject);
}
#if DEBUG
public JObject Object { get; private set; }
#endif
private void Serialize2Stream(JObject jObject)
{
string jsonText = jObject.ToString();
MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
stream.Seek(0, SeekOrigin.Begin);
SetRequestStream(stream, HttpLayer.JSonContentType);
}
}
class ContentTypeEntity
{
public ContentTypeEntity(string rawContentType)
{
var cts = rawContentType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
ContentType = cts[0];
Encoding = Encoding.UTF8;
}
public Encoding Encoding { get; set; }
public string ContentType { get; set; }
}
class JSonResponse : HttpResponse
{
public JSonResponse(HttpWebResponse response, int requestId)
: base(response, requestId)
{
//<API key>();
}
public JObject Object
{
get;
private set;
}
internal override void <API key>()
{
DiagnoseHelper.CheckReference(ResponseStream, "Can not get response stream");
ResponseStream.Seek(0, SeekOrigin.Begin);
ContentTypeEntity ct = new ContentTypeEntity(OriginalResponse.ContentType);
int contentLen = (int)OriginalResponse.ContentLength;
//DiagnoseHelper.<API key>(ct.ContentType, HttpLayer.JSonContentType, "Login response content type is not correct");
byte[] buffer = null;
if (contentLen != -1)
{
buffer = new byte[contentLen];
int leftLen = contentLen;
while (leftLen != 0)
{
int readLen = ResponseStream.Read(buffer, 0, leftLen);
leftLen -= readLen;
if (leftLen != 0)
{
LogHelper.OnlineLogger.Debug("ToDo:: can not read all data in once, need to sleep!" + HttpLayer.LogRequetId(ResponseId));
}
}
}
else
{
List<byte> buffList = new List<byte>();
int tempBufLen = 10 * 1024;
byte[] bufTemp = new byte[tempBufLen];
int readLen = 0;
while ((readLen = ResponseStream.Read(bufTemp, 0, tempBufLen)) != 0)
{
if (readLen == tempBufLen)
buffList.AddRange(bufTemp);
else
buffList.AddRange(bufTemp.Take(readLen));
}
buffer = buffList.ToArray();
contentLen = buffList.Count;
}
string sResult = ct.Encoding.GetString(buffer, 0, contentLen);
DiagnoseHelper.CheckString(sResult, "Login response content is empty");
this.Object = JsonConvert.DeserializeObject<JObject>(sResult);
}
}
} |
require '<API key>/tablet'
require 'rails'
require 'rack/mobile-detect'
module <API key>
autoload :Helper, '<API key>/helper'
class Railtie < Rails::Railtie
initializer "<API key>.configure" do |app|
app.config.middleware.use Rack::MobileDetect
end
if Rails::VERSION::MAJOR >= 3
initializer "<API key>.action_controller" do |app|
ActiveSupport.on_load :action_controller do
include ActionController::<API key>
end
end
initializer "<API key>.action_view" do |app|
ActiveSupport.on_load :action_view do
include <API key>::Helper
alias_method_chain :stylesheet_link_tag, :mobilization
end
end
end
Mime::Type.register_alias "text/html", :mobile
Mime::Type.register_alias "text/html", :tablet
end
end
module ActionController
module <API key>
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
# Add this to one of your controllers to use <API key>.
# class <API key> < ActionController::Base
# has_mobile_fu
# end
# If you don't want mobile_fu to set the request format automatically,
# you can pass false here.
# class <API key> < ActionController::Base
# has_mobile_fu false
# end
def has_mobile_fu(set_request_format = true)
include ActionController::<API key>::InstanceMethods
before_filter :set_request_format if set_request_format
helper_method :is_mobile_device?
helper_method :is_tablet_device?
helper_method :in_mobile_view?
helper_method :in_tablet_view?
helper_method :is_device?
helper_method :mobile_device
end
# Add this to your controllers to prevent the mobile format from being set for specific actions
# class AwesomeController < <API key>
# <API key> :index
# def index
# # Mobile format will not be set, even if user is on a mobile device
# end
# def show
# # Mobile format will be set as normal here if user is on a mobile device
# end
# end
def <API key>(*actions)
@<API key> = actions
end
# Add this to your controllers to only let those actions use the mobile format
# this method has priority over the #<API key>
# class AwesomeController < <API key>
# has_mobile_fu_for :index
# def index
# # Mobile format will be set as normal here if user is on a mobile device
# end
# def show
# # Mobile format will not be set, even if user is on a mobile device
# end
# end
def has_mobile_fu_for(*actions)
@<API key> = actions
end
end
module InstanceMethods
def set_request_format(force_mobile = false)
force_mobile ? force_mobile_format : set_mobile_format
end
alias :set_device_type :set_request_format
# Forces the request format to be :mobile
def force_mobile_format
unless request.xhr?
request.format = :mobile
session[:mobile_view] = true if session[:mobile_view].nil?
end
end
# Forces the request format to be :tablet
def force_tablet_format
unless request.xhr?
request.format = :tablet
session[:tablet_view] = true if session[:tablet_view].nil?
end
end
# Determines the request format based on whether the device is mobile or if
# the user has opted to use either the 'Standard' view or 'Mobile' view or
# 'Tablet' view.
def set_mobile_format
if request.format.html? && mobile_action? && is_mobile_device? && (!request.xhr? || request.headers["jqm-Ajax-Request"])
request.format = :mobile unless session[:mobile_view] == false
session[:mobile_view] = true if session[:mobile_view].nil?
elsif request.format.html? && mobile_action? && is_tablet_device? && (!request.xhr? || request.headers["jqm-Ajax-Request"])
request.format = :tablet unless session[:tablet_view] == false
session[:tablet_view] = true if session[:tablet_view].nil?
end
end
# Returns either true or false depending on whether or not the format of the
# request is either :mobile or not.
def in_mobile_view?
return false unless request.format
request.format.to_sym == :mobile
end
# Returns either true or false depending on whether or not the format of the
# request is either :tablet or not.
def in_tablet_view?
return false unless request.format
request.format.to_sym == :tablet
end
# Returns either true or false depending on whether or not the user agent of
# the device making the request is matched to a device in our regex.
def is_tablet_device?
::<API key>::Tablet.is_a_tablet_device? request.user_agent
end
def is_mobile_device?
!is_tablet_device? && !!mobile_device
end
def mobile_device
request.headers['X_MOBILE_DEVICE']
end
# Can check for a specific user agent
# e.g., is_device?('iphone') or is_device?('mobileexplorer')
def is_device?(type)
request.user_agent.to_s.downcase.include? type.to_s.downcase
end
# Returns true if current action is supposed to use mobile format
# See #has_mobile_fu_for
def mobile_action?
if self.class.<API key>("@<API key>").nil? #Now we know we dont have any includes, maybe excludes?
return !mobile_exempt?
else
self.class.<API key>("@<API key>").try(:include?, params[:action].try(:to_sym))
end
end
# Returns true if current action isn't supposed to use mobile format
# See #<API key>
def mobile_exempt?
self.class.<API key>("@<API key>").try(:include?, params[:action].try(:to_sym))
end
end
end
end
if Rails::VERSION::MAJOR < 3
ActionController::Base.send :include, ActionController::<API key>
ActionView::Base.send :include, <API key>::Helper
ActionView::Base.send :alias_method_chain, :stylesheet_link_tag, :mobilization
end |
<div class="dw-login" ng-controller="AuthCtrl">
<form ng-submit="signin(credentials)">
<div class="modal-header">
<h3 class="modal-title">Sign in</h3>
</div>
<div class="modal-body">
<div class="alert alert-warning" ng-show="error">{{ error }}</div>
<div class="form-group">
<input type="text" class="form-control input-lg" ng-model="credentials.username" placeholder="Username" />
</div>
<div class="form-group">
<input type="password" class="form-control input-lg" ng-model="credentials.password" placeholder="Password" />
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Sign in</button>
</div>
</form>
</div> |
# encoding: utf-8
# of this software and associated documentation files (the 'Software'), to deal
# in the Software without restriction, including without limitation the rights
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# copies or substantial portions of the Software.
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFINGEMENT. IN NO EVENT SHALL THE
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
module HOC
# Set of hits.
class Hits
def initialize(date, total)
@date = date
@total = total
end
attr_reader :date, :total
end
end |
'use strict';
/*
* Directive: 'validation-errors'
* Restrict: A
*/
angular.module('uiFormValidation.directives').directive('validationErrors', function($timeout, utilsService, uiFormValidation, <API key>, $parse) {
return {
replace:true,
restrict: 'A',
require: ['^?uiValidation', 'validationErrors'],
templateUrl: function($element, $scope) {
var <API key> = $element.attr('<API key>');
return <API key> ? <API key> : uiFormValidation.<API key>;
},
scope: {
'<API key>' : '@',
'$index': '@'
},
controller: '<API key>',
link: function(scope, element, attrs, controllers) {
var <API key> = controllers[0];
var <API key> = controllers[1];
var <API key> = null;
if (<API key>) {
<API key> = <API key>.controllerName;
} else {
<API key> = attrs.<API key>;
}
utilsService.<API key>(scope, <API key>, <API key>);
scope.errors = {};
utilsService.<API key>(scope, <API key>, function () {
var <API key> = utilsService.<API key>[scope][<API key>];
var watchedControls = <API key>.<API key>(attrs['validationErrors']);
scope.$watch(function () {
return <API key>.<API key>(watchedControls);
}, function (shouldToggleHidden) {
element.toggleClass('hidden', !shouldToggleHidden);
});
angular.forEach(watchedControls, function (watchedControl) {
var controlWrapper = <API key>.controls[watchedControl.controlName];
if (!controlWrapper) {
throw "Undefined control '" + watchedControl.controlName + '" to watch.';
}
var <API key> = function () {
if (watchedControl.errors && watchedControl.errors.length < 1) {
return;
}
var controlErrors = <API key>.getControlErrors(scope, <API key>, watchedControl, controlWrapper);
scope.errors[watchedControl.controlName] = controlErrors;
};
scope.$watchCollection(function () {
return controlWrapper.control.$error;
}, <API key>);
scope.$watch(function () {
return <API key>.invalidatedDate;
}, <API key>);
});
});
}
};
}); |
import { RouterContext } from '@koa/router'
import httpErrors from 'http-errors'
import Joi from 'joi'
import Koa from 'koa'
import { container } from 'tsyringe'
import { assertUnreachable } from '../../../common/assert-unreachable'
import { USERNAME_MAXLENGTH, USERNAME_MINLENGTH, USERNAME_PATTERN } from '../../../common/constants'
import { <API key>, <API key> } from '../../../common/whispers'
import { httpApi, httpBeforeAll } from '../http/http-api'
import { httpBefore, httpDelete, httpGet, httpPost } from '../http/route-decorators'
import ensureLoggedIn from '../session/ensure-logged-in'
import createThrottle from '../throttle/create-throttle'
import throttleMiddleware from '../throttle/middleware'
import { validateRequest } from '../validation/joi-validator'
import WhisperService, { WhisperServiceError, <API key> } from './whisper-service'
const startThrottle = createThrottle('whisperstart', {
rate: 3,
burst: 10,
window: 60000,
})
const closeThrottle = createThrottle('whisperclose', {
rate: 10,
burst: 20,
window: 60000,
})
const sendThrottle = createThrottle('whispersend', {
rate: 30,
burst: 90,
window: 60000,
})
const retrievalThrottle = createThrottle('whisperretrieval', {
rate: 30,
burst: 120,
window: 60000,
})
function <API key>(err: unknown) {
if (!(err instanceof WhisperServiceError)) {
throw err
}
switch (err.code) {
case <API key>.UserOffline:
case <API key>.UserNotFound:
throw new httpErrors.NotFound(err.message)
case <API key>.InvalidCloseAction:
case <API key>.<API key>:
throw new httpErrors.BadRequest(err.message)
case <API key>.NoSelfMessaging:
throw new httpErrors.Forbidden(err.message)
default:
assertUnreachable(err.code)
}
}
async function <API key>(ctx: RouterContext, next: Koa.Next) {
try {
await next()
} catch (err) {
<API key>(err)
}
}
function <API key>(ctx: RouterContext) {
const {
params: { targetName },
} = validateRequest(ctx, {
params: Joi.object<{ targetName: string }>({
targetName: Joi.string()
.min(USERNAME_MINLENGTH)
.max(USERNAME_MAXLENGTH)
.pattern(USERNAME_PATTERN)
.required(),
}),
})
return targetName
}
@httpApi('/whispers')
@httpBeforeAll(ensureLoggedIn, <API key>)
export class WhisperApi {
constructor(private whisperService: WhisperService) {
container.resolve(WhisperService)
}
@httpPost('/:targetName')
@httpBefore(throttleMiddleware(startThrottle, ctx => String(ctx.session!.userId)))
async startWhisperSession(ctx: RouterContext): Promise<void> {
const targetName = <API key>(ctx)
await this.whisperService.startWhisperSession(ctx.session!.userId, targetName)
ctx.status = 204
}
@httpDelete('/:targetName')
@httpBefore(throttleMiddleware(closeThrottle, ctx => String(ctx.session!.userId)))
async closeWhisperSession(ctx: RouterContext): Promise<void> {
const targetName = <API key>(ctx)
await this.whisperService.closeWhisperSession(ctx.session!.userId, targetName)
ctx.status = 204
}
@httpPost('/:targetName/messages')
@httpBefore(throttleMiddleware(sendThrottle, ctx => String(ctx.session!.userId)))
async sendWhisperMessage(ctx: RouterContext): Promise<void> {
const targetName = <API key>(ctx)
const {
body: { message },
} = validateRequest(ctx, {
body: Joi.object<<API key>>({
message: Joi.string().min(1).required(),
}),
})
await this.whisperService.sendWhisperMessage(ctx.session!.userId, targetName, message)
ctx.status = 204
}
// Leaving the old API with a dummy payload in order to not break the auto-update functionality
// for old clients.
@httpGet('/:targetName/messages')
@httpBefore(throttleMiddleware(retrievalThrottle, ctx => String(ctx.session!.userId)))
<API key>(ctx: RouterContext): Omit<<API key>, 'mentions'> {
return {
messages: [],
users: [],
}
}
@httpGet('/:targetName/messages2')
@httpBefore(throttleMiddleware(retrievalThrottle, ctx => String(ctx.session!.userId)))
async getSessionHistory(ctx: RouterContext): Promise<<API key>> {
const targetName = <API key>(ctx)
const {
query: { limit, beforeTime },
} = validateRequest(ctx, {
query: Joi.object<{ limit: number; beforeTime: number }>({
limit: Joi.number().min(1).max(100),
beforeTime: Joi.number().min(-1),
}),
})
return await this.whisperService.getSessionHistory(
ctx.session!.userId,
targetName,
limit,
beforeTime,
)
}
} |
<?php
/* @var $this SiteController */
$this->pageTitle=Yii::app()->name;
?>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/js/app/build/chapycard.js"></script>
<script type="text/javascript" src="<?php echo Yii::app()->theme->baseUrl; ?>/template/setting.json"></script>
<script type="text/javascript">
var manifest = {
app:{
frontside:{
selector: ".frontside"
},
backside:{
selector: ".backside"
}
},
tab:{
general:{
name: "general",
controls: {
width: {
name: "width",
selector: ".chapycard"
},
height: {
name: "height",
selector: ".chapycard"
},
corner: {
name: "corner",
selector: ".chapycard"
}
},
init: true
},
design:{
name: "design",
controls:{
border:{
name: "border",
selector: ".chapycard"
},
background:{
name: "background",
selector: ".chapycard"
}
},
init: false
}
}
};
</script>
<!-- for test only -->
<div id="wrapper">
<div id="firstColumn">
<div id="chapycontrol"></div>
</div>
<div id="secondColumn"><iframe id="framecard" src="<?php echo Yii::app()->theme->baseUrl; ?>/template/index.html" ></iframe></div>
</div>
<!-- end test -->
<script type="text/javascript">
$(document).ready(function(){
chapyCardInit = function(){
var frame = $("#framecard");
var controls = $("#chapycontrol");
var builder = new ChapyCard.Builder(frame, manifest, controls);
}
});
</script> |
(function ($) {
$.fn.toggleType = function (options) {
var params = $.extend({
type: 'text',
element : null,
callback : null
}, options),
target = params.element || options;
target.before(
target.clone().prop(
'type', function (self) {
var status = self.data('status') === 'checked';
if (params.callback)
params.callback(self);
//set default type
if (typeof params.callback === 'function')
self.data('type', target.prop('type'));
//toggle type
self.data('status', status ? '' : 'checked');
return status;
}(this) ? this.data('type') : params.type
)
).remove();
return this;
};
})(jQuery); |
const lazyseqs = require('../lib/lazyseq');
const lists = require('../lib/list');
exports['create and consume lazy seq'] = function (test) {
let n = 1;
const fn = function () {
return lists.list(n++, lazyseqs.create(fn));
}
const lseq = lazyseqs.create(fn);
test.ok(lseq);
test.equal(lseq.first(), 1);
test.equal(lseq.first(), 1);
test.ok(lseq.next());
test.equal(lseq.next().first(), 2);
test.equal(lseq.next().first(), 2);
test.ok(lseq.next());
test.equal(lseq.next().next().first(), 3);
test.equal(lseq.next().next().first(), 3);
}
exports['create empty lazy seq'] = function (test) {
test.ok(lists.isEmptyList(lazyseqs.create(null)));
} |
# require 'config/boot'
# require 'active_support'
# $:.unshift(RAILS_ROOT + "/lib")
require 'config/environment'
context "Ext::Tree::TreeLoader without args" do
setup do
@ext = Ext::Tree::TreeLoader.new
end
specify do
@ext.class.ext_class.should == 'Ext.tree.TreeLoader'
end
specify do
@ext.args.size.should == 1
end
specify do
@ext.args.first.should is_a?(Hash)
end
specify do
expected = %w( dataUrl )
@ext.options.keys.map(&:to_s).sort.should == expected
end
specify do
expected = 'new Ext.tree.TreeLoader({dataUrl: null})'
end
end
context "Ext::Tree::TreeLoader with url" do
setup do
@ext = Ext::Tree::TreeLoader.new :url => '/foo'
end
specify do
expected = 'new Ext.tree.TreeLoader({dataUrl: "/foo"})'
end
end
__END__
new Tree.TreeLoader({dataUrl:'#{url}'}), |
package com.amb_it_ion.refocus.persistence;
import com.amb_it_ion.refocus.external.plug.api.PersistencePlug;
import com.google.inject.AbstractModule;
public class AppInjector extends AbstractModule {
@Override
protected void configure() {
bind(PersistencePlug.class).to(Server.class);
}
} |
using System;
using System.IO;
using NUnit.Engine.TestHelpers;
namespace NUnit.Engine.Integration
{
internal sealed class <API key> : IDisposable
{
public string Directory { get; }
<summary>
Returns the transitive closure of assemblies needed to copy.
Deals with assembly names rather than paths to work with runners that shadow copy.
</summary>
public <API key>(params string[] assemblyNames)
{
Directory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
System.IO.Directory.CreateDirectory(Directory);
foreach (var neededAssembly in ShadowCopyUtils.<API key>(assemblyNames))
{
File.Copy(neededAssembly, Path.Combine(Directory, Path.GetFileName(neededAssembly)));
}
}
public void Dispose()
{
System.IO.Directory.Delete(Directory, true);
}
}
} |
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
namespace Repo2.SDK.WPF45.ControlBehaviors.WindowBehaviors
{
public class DraggableBehavior : Behavior<Window>
{
protected override void OnAttached()
{
AssociatedObject.MouseDown += (s, e) =>
{
if (e.ChangedButton == MouseButton.Left)
(s as Window)?.DragMove();
};
}
}
} |
// BFTextField.h
// BFKit
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
@import UIKit;
@import Foundation;
/**
* This class adds some useful methods to UITextField that cannot be in a category
*/
@interface BFTextField : UITextField
/**
* Defines the max number of characters the user can insert. Default to 0
*/
@property IBInspectable NSInteger <API key>;
@end |
-- Hammerspoon config
-- NOTE: if requiring a file inside a folder in ~/.hammerspoon, replace "/" with "."
-- (ex. ~/.hammerspoon/someFolder/someFile.lua => require('someFolder.someFile')
-- you can also require all files in a folder by requiring the folder name (ex. require('someFolder')
-- Logger setup
hs.logger.setGlobalLogLevel('warning')
hs.logger.defaultLogLevel = 'warning'
logger = hs.logger.new('Init')
hs.console.clearConsole()
-- CLI integration
require("hs.ipc") -- provides server portion of cli
if not hs.ipc.cliStatus() then
logger.w('No IPC installed, trying to install now')
if not hs.ipc.cliInstall() then -- installs cli named 'hs' in /Applications/Hammerspoon.app/Contents/Resources/extensions/hs/ipc/bin/
logger.e('Attempt to install IPC failed, trying uninstall first before install now')
hs.ipc.cliUninstall()
if not hs.ipc.cliInstall() then
logger.e('IPC still install failed, require user triage')
end
end
end
-- miscellaneous configs
hs.autoLaunch(true)
hs.<API key>(true)
hs.preferencesDarkMode(true)
hs.accessibilityState(true) -- show System Preferences if Accessibility is not enabled for Hammerspoon
hs.dockIcon(false)
hs.menuIcon(false)
hs.consoleOnTop(true)
-- window configs
hs.window.animationDuration = 0
hs.window.filter.setLogLevel = 'error'
hs.window.filter.ignoreAlways['Spotlight'] = false -- NOTE: set to false for window-filter to auto center Spotlight
hs.window.filter.ignoreAlways['Hammerspoon'] = false -- prevent wfiltre warning
hs.window.filter.ignoreAlways['Hammerspoon Networking'] = true -- prevent wfiltre warning
hs.window.filter.ignoreAlways['Autoupdate'] = true -- prevent wfiltre warning
hs.window.filter.ignoreAlways['Siri'] = true -- prevent wfilter warning
-- assign imported modules to global variable to avoid getting destroyed by garbage collection
console = require("console")
utility = require("utility")
hotkey = require("hotkey")
caffeine = require("caffeine")
windowFilter = require("windowFilter")
applicationWatcher = require("applicationWatcher").start()
fileWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/.hammerspoon/init.lua", reloadConfig):start() -- reloads Hammerspoon whenever ~/.hammerspoon/init.lua is edited and saved
-- plugin to auto pause music when headphone disconnects
hs.loadSpoon('HeadphoneAutoPause')
spoon.HeadphoneAutoPause.autoResume = false
spoon.HeadphoneAutoPause.defaultControlFns('iTunes')
spoon.HeadphoneAutoPause:start()
-- plugin to get notification when WiFi changes
hs.loadSpoon('WifiNotifier')
spoon.WifiNotifier:init()
spoon.WifiNotifier:start()
-- callback when Hammerspoon is exiting or reloading, mainly for serialising state,
-- destroying system resources that will not be released by normal Lua garbage collection processes, etc
hs.shutdownCallback = function()
applicationWatcher.stop()
spoon.WifiNotifier:stop()
spoon.HeadphoneAutoPause:stop()
localProfile = nil
logger.i("Hammerspoon Shutting Down")
-- no OS/GUI commands will be executed in here since Hammerspoon is already shutting down
end
logger.i("Hammerspoon Config Loaded")
if hs.fs.displayName(os.getenv("HOME") .. "/.hammerspoon/local_profile.lua") == "local_profile.lua" then
localProfile = require("local_profile")
-- TODO: replace with logger (broken, no messages logged to hs console)
-- hs.alert("Loaded local profile: ~/.hammerspoon/local_profile.lua")
end
-- plugin to display Hammerspoon logo to indicate Hammerspoon successfully loaded
hs.loadSpoon('FadeLogo')
spoon.FadeLogo.zoom = false
spoon.FadeLogo.image_size = hs.geometry.size(80, 80)
spoon.FadeLogo.run_time = 1.5
spoon.FadeLogo:start() |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_05) on Thu Jul 03 13:49:04 PDT 2008 -->
<TITLE>
edu.sdsc.inca.agent Class Hierarchy
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="edu.sdsc.inca.agent Class Hierarchy";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<A NAME="navbar_top"></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../edu/sdsc/inca/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../edu/sdsc/inca/agent/access/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?edu/sdsc/inca/agent/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
Hierarchy For Package edu.sdsc.inca.agent
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.Object<UL>
<LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/AccessMethod.html" title="class in edu.sdsc.inca.agent"><B>AccessMethod</B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/AccessMethodOutput.html" title="class in edu.sdsc.inca.agent"><B>AccessMethodOutput</B></A><LI TYPE="circle">junit.framework.Assert<UL>
<LI TYPE="circle">junit.framework.TestCase (implements junit.framework.Test)
<UL>
<LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.html" title="class in edu.sdsc.inca.agent"><B><API key></B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/RepositoryCacheTest.html" title="class in edu.sdsc.inca.agent"><B>RepositoryCacheTest</B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/SuiteTableTest.html" title="class in edu.sdsc.inca.agent"><B>SuiteTableTest</B></A></UL>
</UL>
<LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.html" title="class in edu.sdsc.inca.agent"><B><API key></B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.html" title="class in edu.sdsc.inca.agent"><B><API key></B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/SuiteTable.html" title="class in edu.sdsc.inca.agent"><B>SuiteTable</B></A><LI TYPE="circle">java.lang.Thread (implements java.lang.Runnable)
<UL>
<LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.MockAgent.html" title="class in edu.sdsc.inca.agent"><B><API key>.MockAgent</B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.html" title="class in edu.sdsc.inca.agent"><B><API key></B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.html" title="class in edu.sdsc.inca.agent"><B><API key></B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/RepositoryCache.html" title="class in edu.sdsc.inca.agent"><B>RepositoryCache</B></A></UL>
<LI TYPE="circle">java.lang.Throwable (implements java.io.Serializable)
<UL>
<LI TYPE="circle">java.lang.Exception<UL>
<LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.html" title="class in edu.sdsc.inca.agent"><B><API key></B></A><LI TYPE="circle">edu.sdsc.inca.agent.<A HREF="../../../../edu/sdsc/inca/agent/<API key>.html" title="class in edu.sdsc.inca.agent"><B><API key></B></A></UL>
</UL>
</UL>
</UL>
<HR>
<A NAME="navbar_bottom"></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="<API key>"></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../edu/sdsc/inca/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../edu/sdsc/inca/agent/access/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?edu/sdsc/inca/agent/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
</BODY>
</HTML> |
module Releaser
class FromFile
attr_accessor :name
def initialize(file_name = File.join(Rails.root, "CURRENT_VERSION"))
self.name = file_name
end
def version(default = "development")
if exists?
from_file
else
default
end
end
protected
def from_file
`cat #{name}`
end
def exists?
File.exists?(name)
end
end
end |
/* select theme in here */
@import url("./themes/dark-blue/iframe.css"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.