code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
class Admin_GeneralModel extends CI_Model {
public function GetAdminModuleCategoryList()
{
$this->db->select('CID, CategoryName');
$this->db->from('admin_module_category');
$this->db->order_by('Ordering');
$query = $this->db->get();
if($query->num_rows())
return $query;
else
return FALSE;
}
public function GetAdminModuleList()
{
$this->db->select('MID, CID, ModuleName, DisplayName');
$this->db->from('admin_module');
$this->db->order_by('Ordering');
$query = $this->db->get();
if($query->num_rows())
return $query;
else
return FALSE;
}
public function GetAdminModuleActions($MID = NULL)
{
$this->db->select('AID, MID, Action');
$this->db->from('admin_module_action');
if($MID != NULL)
$this->db->where('MID', $MID);
$query = $this->db->get();
if($query->num_rows())
return $query->result();
else
return FALSE;
}
}
?> | Java |
#ifndef SYMTAB_H
#define SYMTAB_H
#include "symbol.h"
void symtab_init();
void push_scope();
void pop_scope();
symbol *bind_symbol(char *name);
symbol *lookup_symbol(char *name);
void print_symtab();
#endif
| Java |
RSpec.describe("executables", skip_db_cleaner: true) do
include SharedSpecSetup
before do
#migrations don't work if we are still connected to the db
ActiveRecord::Base.remove_connection
end
it "extracts the schema" do
output = `bin/extract #{config_filename} production #{schema_filename} 2>&1`
expect(output).to match(/extracted to/)
expect(output).to match(/#{schema_filename}/)
end
it "transfers the schema" do
output = `bin/transfer-schema #{config_filename} production test config/include_tables.txt 2>&1`
expect(output).to match(/transferred schema from production to test/)
end
end
| Java |
## S3proxy - serve S3 files simply
S3proxy is a simple flask-based REST web application which can expose files (keys) stored in the AWS Simple Storage Service (S3) via a simple REST api.
### What does this do?
S3proxy takes a set of AWS credentials and an S3 bucket name and provides GET and HEAD endpoints on the files within the bucket. It uses the [boto][boto] library for internal access to S3. For example, if your bucket has the following file:
s3://mybucket/examples/path/to/myfile.txt
then running S3proxy on a localhost server (port 5000) would enable you read (GET) this file at:
http://localhost:5000/files/examples/path/to/myfile.txt
Support exists in S3proxy for the `byte-range` header in a GET request. This means that the API can provide arbitrary parts of S3 files if requested/supported by the application making the GET request.
### Why do this?
S3proxy simplifies access to private S3 objects. While S3 already provides [a complete REST API][s3_api], this API requires signed authentication headers or parameters that are not always obtainable within existing applications (see below), or overly complex for simple development/debugging tasks.
In fact, however, S3proxy was specifically designed to provide a compatability layer for viewing DNA sequencing data in(`.bam` files) using [IGV][igv]. While IGV already includes an interface for reading bam files from an HTTP endpoint, it does not support creating signed requests as required by the AWS S3 API (IGV does support HTTP Basic Authentication, a feature that I would like to include in S3proxy in the near future). Though it is in principal possible to provide a signed AWS-compatible URL to IGV, IGV will still not be able to create its own signed URLs necessary for accessing `.bai` index files, usually located in the same directory as the `.bam` file. Using S3proxy you can expose the S3 objects via a simplified HTTP API which IGV can understand and access directly.
This project is in many ways similar to [S3Auth][s3auth], a hosted service which provides a much more complete API to a private S3 bucket. I wrote S3proxy as a faster, simpler solution-- and because S3Auth requires a domain name and access to the `CNAME` record in order to function. If you want a more complete API (read: more than just GET/HEAD at the moment) should check them out!
### Features
- Serves S3 file objects via standard GET request, optionally providing only a part of a file using the `byte-range` header.
- Easy to configure via a the `config.yaml` file-- S3 keys and bucket name is all you need!
- Limited support for simple url-rewriting where necessary.
- Uses the werkzeug [`SimpleCache` module][simplecache] to cache S3 object identifiers (but not data) in order to reduce latency and lookup times.
### Usage
#### Requirements
To run S3proxy, you will need:
- [Flask][flask]
- [boto][boto]
- [PyYAML][pyyaml]
- An Amazon AWS account and keys with appropriate S3 access
#### Installation/Configuration
At the moment, there is no installation. Simply put your AWS keys and bucket name into the config.yaml file:
```yaml
AWS_ACCESS_KEY_ID: ''
AWS_SECRET_ACCESS_KEY: ''
bucket_name: ''
```
You may also optionally specify a number of "rewrite" rules. These are simple pairs of a regular expression and a replacement string which can be used to internally redirect (Note, the API does not actually currently send a REST 3XX redirect header) file paths. The example in the config.yaml file reads:
```yaml
rewrite_rules:
bai_rule:
from: ".bam.bai$"
to: ".bai"
```
... which will match all url/filenames ending with ".bam.bai" and rewrite this to ".bai".
If you do not wish to use any rewrite_rules, simply leave this commented out.
#### Running S3cmd:
Once you have filled out the config.yaml file, you can test out S3proxy simply by running on the command line:
python app.py
*Note*: Running using the built-in flask server is not recommended for anything other than debugging. Refer to [these deployment options][wsgi_server] for instructions on how to set up a flask applicaiton in a WSGI framework.
#### Options
If you wish to see more debug-level output (headers, etc.), use the `--debug` option. You may also specify a yaml configuration file to load using the `--config` parameter.
### Important considerations and caveats
S3proxy should not be used in production-level or open/exposed servers! There is currently no security provided by S3proxy (though I may add basic HTTP authentication later). Once given the AWS credentials, S3proxy will serve any path available to it. And, although I restrict requests to GET and HEAD only, I cannot currently guarantee that a determined person would not be able to execute a PUT/UPDATE/DELETE request using this service. Finally, I highly recommend you create a separate [IAM role][iam_roles] in AWS with limited access and permisisons to S3 only for use with S3proxy.
### Future development
- Implement HTTP Basic Authentication to provide some level of security.
- Implement other error codes and basic REST responses.
- Add ability to log to a file and specify a `--log-level` (use the Python logging module)
[boto]: http://boto.readthedocs.org/
[flask]: http://flask.pocoo.org/
[pyyaml]: http://pyyaml.org/wiki/PyYAML
[s3_api]: http://docs.aws.amazon.com/AmazonS3/latest/API/APIRest.html
[igv]: http://www.broadinstitute.org/igv/home
[wsgi_server]: http://flask.pocoo.org/docs/deploying/
[iam_roles]: http://aws.amazon.com/iam/
[simplecache]: http://flask.pocoo.org/docs/patterns/caching/
[s3auth]: http://www.s3auth.com/
| Java |
Title: Survey data
Template: survey
Slug: survey/data
Github: True
The code to clean and process the survey data is available in the [GitHub repository](https://github.com/andrewheiss/From-the-Trenches-Anti-TIP-NGOs-and-US) for Andrew Heiss and Judith G. Kelley. 2016. "From the Trenches: A Global Survey of Anti-TIP NGOs and their Views of US Efforts." *Journal of Human Trafficking*. [doi:10.1080/23322705.2016.1199241](https://dx.doi.org/10.1080/23322705.2016.1199241)
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<div class="github-widget" data-repo="andrewheiss/From-the-Trenches-Anti-TIP-NGOs-and-US"></div>
</div>
</div>
The free response answers for respondents who requested anonymity have been
redacted.
- CSV file: [`responses_full_anonymized.csv`](/files/data/responses_full_anonymized.csv)
- R file: [`responses_full_anonymized.rds`](/files/data/responses_full_anonymized.rds)
| Java |
// @flow
import { StyleSheet } from 'react-native';
import { colors } from '../../themes';
const styles = StyleSheet.create({
divider: {
height: 1,
marginHorizontal: 0,
backgroundColor: colors.darkDivider,
},
});
export default styles;
| Java |
## Testing testing, 1, 2, 3
Let's see how *[this](https://github.com/imathis/jekyll-markdown-block)* does.
puts 'awesome' unless not_awesome?
- One item
- Two item
- Three Item
- Four!
And… scene!
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 21 16:03:26 EST 2012 -->
<TITLE>
ResourceXmlPropertyEmitterInterface
</TITLE>
<META NAME="date" CONTENT="2012-11-21">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ResourceXmlPropertyEmitterInterface";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ResourceXmlPropertyEmitterInterface.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </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-files/index-1.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="../../../../org/pentaho/di/resource/ResourceUtil.html" title="class in org.pentaho.di.resource"><B>PREV CLASS</B></A>
<A HREF="../../../../org/pentaho/di/resource/SequenceResourceNaming.html" title="class in org.pentaho.di.resource"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/pentaho/di/resource/ResourceXmlPropertyEmitterInterface.html" target="_top"><B>FRAMES</B></A>
<A HREF="ResourceXmlPropertyEmitterInterface.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.pentaho.di.resource</FONT>
<BR>
Interface ResourceXmlPropertyEmitterInterface</H2>
<HR>
<DL>
<DT><PRE>public interface <B>ResourceXmlPropertyEmitterInterface</B></DL>
</PRE>
<P>
<HR>
<P>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../org/pentaho/di/resource/ResourceXmlPropertyEmitterInterface.html#getExtraResourceProperties(org.pentaho.di.resource.ResourceHolderInterface, int)">getExtraResourceProperties</A></B>(<A HREF="../../../../org/pentaho/di/resource/ResourceHolderInterface.html" title="interface in org.pentaho.di.resource">ResourceHolderInterface</A> ref,
int indention)</CODE>
<BR>
Allows injection of additional relevant properties in the
to-xml of the Resource Reference.</TD>
</TR>
</TABLE>
<P>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getExtraResourceProperties(org.pentaho.di.resource.ResourceHolderInterface, int)"><!-- --></A><H3>
getExtraResourceProperties</H3>
<PRE>
<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A> <B>getExtraResourceProperties</B>(<A HREF="../../../../org/pentaho/di/resource/ResourceHolderInterface.html" title="interface in org.pentaho.di.resource">ResourceHolderInterface</A> ref,
int indention)</PRE>
<DL>
<DD>Allows injection of additional relevant properties in the
to-xml of the Resource Reference.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>ref</CODE> - The Resource Reference Holder (a step, or a job entry)<DD><CODE>indention</CODE> - If -1, then no indenting, otherwise, it's the indent level to indent the XML strings
<DT><B>Returns:</B><DD>String of injected XML</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<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="navbar_bottom_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="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/ResourceXmlPropertyEmitterInterface.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </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-files/index-1.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="../../../../org/pentaho/di/resource/ResourceUtil.html" title="class in org.pentaho.di.resource"><B>PREV CLASS</B></A>
<A HREF="../../../../org/pentaho/di/resource/SequenceResourceNaming.html" title="class in org.pentaho.di.resource"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?org/pentaho/di/resource/ResourceXmlPropertyEmitterInterface.html" target="_top"><B>FRAMES</B></A>
<A HREF="ResourceXmlPropertyEmitterInterface.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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | CONSTR | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | CONSTR | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| Java |
require 'ffi'
module ProcessShared
module Posix
module Errno
extend FFI::Library
ffi_lib FFI::Library::LIBC
attach_variable :errno, :int
# Replace methods in +syms+ with error checking wrappers that
# invoke the original method and raise a {SystemCallError} with
# the current errno if the return value is an error.
#
# Errors are detected if the block returns true when called with
# the original method's return value.
def error_check(*syms, &is_err)
unless block_given?
is_err = lambda { |v| (v == -1) }
end
syms.each do |sym|
method = self.method(sym)
new_method_body = proc do |*args|
ret = method.call(*args)
if is_err.call(ret)
raise SystemCallError.new("error in #{sym}", Errno.errno)
else
ret
end
end
define_singleton_method(sym, &new_method_body)
define_method(sym, &new_method_body)
end
end
end
end
end
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<!-- UASR: Unified Approach to Speech Synthesis and Recognition
< - Documentation home page
<
< AUTHOR : Matthias Wolff
< PACKAGE: n/a
<
< Copyright 2013 UASR contributors (see COPYRIGHT file)
< - Chair of System Theory and Speech Technology, TU Dresden
< - Chair of Communications Engineering, BTU Cottbus
<
< This file is part of UASR.
<
< UASR is free software: you can redistribute it and/or modify it under the
< terms of the GNU Lesser General Public License as published by the Free
< Software Foundation, either version 3 of the License, or (at your option)
< any later version.
<
< UASR is distributed in the hope that it will be useful, but WITHOUT ANY
< WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
< FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
< more details.
<
< You should have received a copy of the GNU Lesser General Public License
< along with UASR. If not, see [http://www.gnu.org/licenses/].
-->
<html>
<head>
<link rel=stylesheet type="text/css" href="toc.css">
</head>
<script type="text/javascript">
if (top==self)
top.location = "index.html";
</script>
<script type="text/javascript" src="default.js"></script>
<body onload="void(__tocInit('tocRoot'));">
<h2 class="CONT">Manual</h2>
<noscript><div class="noscript">
JavaScript is not enabled.
</div></noscript>
<div class="tocRoot" id="tocRoot">
<div class="tocLeaf"><a class="toc" href="home.html" target="contFrame" title="Database DocumentationHome Page">Home</a></div>
<div class="tocNode" id="tocPackageDocumentation">
<a class="toc" href="javascript:__tocToggle('tocPackageDocumentation');">[−]</a> <img src="resources/book_obj.gif" class="tocIcon"> Scripts
<!--{{ TOC -->
<div class="tocLeaf"><a href="automatic/vau.itp.html" target="contFrame" title="Voice authentication database plug-in. "
><img src="resources/blank_stc.gif" class="tocIcon"> <img src="resources/lib_obj.gif" class="tocIcon"> vau.itp</a></div>
<!--}} TOC -->
</div>
</div>
</body>
</html>
| Java |
'use strict';
const _ = require('lodash');
const co = require('co');
const Promise = require('bluebird');
const AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
const cloudwatch = Promise.promisifyAll(new AWS.CloudWatch());
const Lambda = new AWS.Lambda();
const START_TIME = new Date('2017-06-07T01:00:00.000Z');
const DAYS = 2;
const ONE_DAY = 24 * 60 * 60 * 1000;
let addDays = (startDt, n) => new Date(startDt.getTime() + ONE_DAY * n);
let getFuncStats = co.wrap(function* (funcName) {
let getStats = co.wrap(function* (startTime, endTime) {
let req = {
MetricName: 'Duration',
Namespace: 'AWS/Lambda',
Period: 60,
Dimensions: [ { Name: 'FunctionName', Value: funcName } ],
Statistics: [ 'Maximum' ],
Unit: 'Milliseconds',
StartTime: startTime,
EndTime: endTime
};
let resp = yield cloudwatch.getMetricStatisticsAsync(req);
return resp.Datapoints.map(dp => {
return {
timestamp: dp.Timestamp,
value: dp.Maximum
};
});
});
let stats = [];
for (let i = 0; i < DAYS; i++) {
// CloudWatch only allows us to query 1440 data points per request, which
// at 1 min period is 24 hours
let startTime = addDays(START_TIME, i);
let endTime = addDays(startTime, 1);
let oneDayStats = yield getStats(startTime, endTime);
stats = stats.concat(oneDayStats);
}
return _.sortBy(stats, s => s.timestamp);
});
let listFunctions = co.wrap(function* (marker, acc) {
acc = acc || [];
let resp = yield Lambda.listFunctions({ Marker: marker, MaxItems: 100 }).promise();
let functions = resp.Functions
.map(f => f.FunctionName)
.filter(fn => fn.includes("aws-coldstart") && !fn.endsWith("run"));
acc = acc.concat(functions);
if (resp.NextMarker) {
return yield listFunctions(resp.NextMarker, acc);
} else {
return acc;
}
});
listFunctions()
.then(co.wrap(function* (funcs) {
for (let func of funcs) {
let stats = yield getFuncStats(func);
stats.forEach(stat => console.log(`${func},${stat.timestamp},${stat.value}`));
}
})); | Java |
from __future__ import absolute_import, division, print_function, unicode_literals
import string
import urllib
try:
from urllib.parse import urlparse, urlencode, urljoin, parse_qsl, urlunparse
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from urlparse import urlparse, urljoin, urlunparse, parse_qsl
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
from random import SystemRandom
try:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters +
string.digits)
except AttributeError:
UNICODE_ASCII_CHARACTERS = (string.ascii_letters.decode('ascii') +
string.digits.decode('ascii'))
def random_ascii_string(length):
random = SystemRandom()
return ''.join([random.choice(UNICODE_ASCII_CHARACTERS) for x in range(length)])
def url_query_params(url):
"""Return query parameters as a dict from the specified URL.
:param url: URL.
:type url: str
:rtype: dict
"""
return dict(parse_qsl(urlparse(url).query, True))
def url_dequery(url):
"""Return a URL with the query component removed.
:param url: URL to dequery.
:type url: str
:rtype: str
"""
url = urlparse(url)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
'',
url.fragment))
def build_url(base, additional_params=None):
"""Construct a URL based off of base containing all parameters in
the query portion of base plus any additional parameters.
:param base: Base URL
:type base: str
::param additional_params: Additional query parameters to include.
:type additional_params: dict
:rtype: str
"""
url = urlparse(base)
query_params = {}
query_params.update(parse_qsl(url.query, True))
if additional_params is not None:
query_params.update(additional_params)
for k, v in additional_params.items():
if v is None:
query_params.pop(k)
return urlunparse((url.scheme,
url.netloc,
url.path,
url.params,
urlencode(query_params),
url.fragment))
| Java |
#!/bin/bash
# data in Empar_paper/data/simul_balanc4GenNonhSSM
#length1000_b100.tar length1000_b150.tar length1000_b200.tar
#length1000_b100_num98.fa
MOD=ssm
ITER=2 # number of data sets
bl=100
#prep output files
OUT_lik='likel_balanced4_gennonh_'$bl'_'$MOD'_E.txt'
OUT_iter='iter_balanced4_gennonh_'$bl'_'$MOD'_E.txt'
OUT_time='time_balanced4_gennonh_'$bl'_'$MOD'_E.txt'
OUT_nc='neg_cases_balanced4_gennonh_'$bl'_'$MOD'_E.txt'
[[ -f $OUT_lik ]] && rm -f $OUT_lik
[[ -f $OUT_iter ]] && rm -f $OUT_iter
[[ -f $OUT_time ]] && rm -f $OUT_time
[[ -f $OUT_nc ]] && rm -f $OUT_nc
touch $OUT_lik
touch $OUT_iter
touch $OUT_time
touch $OUT_nc
# run from within the scripts folder
for i in $(seq 0 1 $ITER)
do
#extract a single file from tar
tar -xvf ../data/simul_balanc4GenNonhSSM/length1000_b$bl.tar length1000_b$bl\_num$i.fa
./main ../data/trees/treeE.tree length1000_b$bl\_num$i.fa $MOD > out.txt
cat out.txt | grep Likelihood | cut -d':' -f2 | xargs >> $OUT_lik
cat out.txt | grep Iter | cut -d':' -f2 | xargs >> $OUT_iter
cat out.txt | grep Time | cut -d':' -f2 | xargs >> $OUT_time
cat out.txt | grep "negative branches" | cut -d':' -f2 | xargs >> $OUT_nc
rm out.txt
# not poluting the folder with single files
rm length1000_b$bl\_num$i.fa
done
mv $OUT_time ../results/ssm/gennonh_data/balanc4GenNonh/.
mv $OUT_lik ../results/ssm/gennonh_data/balanc4GenNonh/.
mv $OUT_iter ../results/ssm/gennonh_data/balanc4GenNonh/.
mv $OUT_nc ../results/ssm/gennonh_data/balanc4GenNonh/.
| Java |
/*
The MIT License (MIT)
Copyright (c) 2014 Banbury & Play-Em
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.
*/
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif
namespace SpritesAndBones.Editor
{
[CustomEditor(typeof(Skin2D))]
public class Skin2DEditor : UnityEditor.Editor
{
private Skin2D skin;
private float baseSelectDistance = 0.1f;
private float changedBaseSelectDistance = 0.1f;
private int selectedIndex = -1;
private Color handleColor = Color.green;
private void OnEnable()
{
skin = (Skin2D)target;
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
EditorGUILayout.Separator();
if (GUILayout.Button("Toggle Mesh Outline"))
{
Skin2D.showMeshOutline = !Skin2D.showMeshOutline;
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Save as Prefab"))
{
skin.SaveAsPrefab();
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Recalculate Bone Weights"))
{
skin.RecalculateBoneWeights();
}
EditorGUILayout.Separator();
handleColor = EditorGUILayout.ColorField("Handle Color", handleColor);
changedBaseSelectDistance = EditorGUILayout.Slider("Handle Size", baseSelectDistance, 0, 1);
if (baseSelectDistance != changedBaseSelectDistance)
{
baseSelectDistance = changedBaseSelectDistance;
EditorUtility.SetDirty(this);
SceneView.RepaintAll();
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Create Control Points"))
{
skin.CreateControlPoints(skin.GetComponent<SkinnedMeshRenderer>());
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Reset Control Points"))
{
skin.ResetControlPointPositions();
}
if (skin.points != null && skin.controlPoints != null && skin.controlPoints.Length > 0
&& selectedIndex != -1 && GUILayout.Button("Reset Selected Control Point"))
{
if (skin.controlPoints[selectedIndex].originalPosition != skin.GetComponent<MeshFilter>().sharedMesh.vertices[selectedIndex])
{
skin.controlPoints[selectedIndex].originalPosition = skin.GetComponent<MeshFilter>().sharedMesh.vertices[selectedIndex];
}
skin.controlPoints[selectedIndex].ResetPosition();
skin.points.SetPoint(skin.controlPoints[selectedIndex]);
}
if (GUILayout.Button("Remove Control Points"))
{
skin.RemoveControlPoints();
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Generate Mesh Asset"))
{
#if UNITY_EDITOR
// Check if the Meshes directory exists, if not, create it.
if (!Directory.Exists("Assets/Meshes"))
{
AssetDatabase.CreateFolder("Assets", "Meshes");
AssetDatabase.Refresh();
}
Mesh mesh = new Mesh();
mesh.name = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.name.Replace(".SkinnedMesh", ".Mesh"); ;
mesh.vertices = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.vertices;
mesh.triangles = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.triangles;
mesh.normals = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.normals;
mesh.uv = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.uv;
mesh.uv2 = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.uv2;
mesh.bounds = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.bounds;
ScriptableObjectUtility.CreateAsset(mesh, "Meshes/" + skin.gameObject.name + ".Mesh");
#endif
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial != null && GUILayout.Button("Generate Material Asset"))
{
#if UNITY_EDITOR
Material material = new Material(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
material.CopyPropertiesFromMaterial(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial = material;
if (!Directory.Exists("Assets/Materials"))
{
AssetDatabase.CreateFolder("Assets", "Materials");
AssetDatabase.Refresh();
}
AssetDatabase.CreateAsset(material, "Assets/Materials/" + material.mainTexture.name + ".mat");
Debug.Log("Created material " + material.mainTexture.name + " for " + skin.gameObject.name);
#endif
}
}
private void OnSceneGUI()
{
if (skin != null && skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null
&& skin.controlPoints != null && skin.controlPoints.Length > 0 && skin.points != null)
{
Event e = Event.current;
Handles.matrix = skin.transform.localToWorldMatrix;
EditorGUI.BeginChangeCheck();
Ray r = HandleUtility.GUIPointToWorldRay(e.mousePosition);
Vector2 mousePos = r.origin;
float selectDistance = HandleUtility.GetHandleSize(mousePos) * baseSelectDistance;
#region Draw vertex handles
Handles.color = handleColor;
for (int i = 0; i < skin.controlPoints.Length; i++)
{
if (Handles.Button(skin.points.GetPoint(skin.controlPoints[i]), Quaternion.identity, selectDistance, selectDistance, Handles.CircleCap))
{
selectedIndex = i;
}
if (selectedIndex == i)
{
EditorGUI.BeginChangeCheck();
skin.controlPoints[i].position = Handles.DoPositionHandle(skin.points.GetPoint(skin.controlPoints[i]), Quaternion.identity);
if (EditorGUI.EndChangeCheck())
{
skin.points.SetPoint(skin.controlPoints[i]);
Undo.RecordObject(skin, "Changed Control Point");
Undo.RecordObject(skin.points, "Changed Control Point");
EditorUtility.SetDirty(this);
}
}
}
#endregion Draw vertex handles
}
}
}
} | Java |
package com.thilko.springdoc;
@SuppressWarnings("all")
public class CredentialsCode {
Integer age;
double anotherValue;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public double getAnotherValue() {
return anotherValue;
}
public void setAnotherValue(double anotherValue) {
this.anotherValue = anotherValue;
}
}
| Java |
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
/* @var $this yii\web\View */
/* @var $searchModel yii2learning\chartbuilder\models\DatasourceSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = Yii::t('app', 'Datasources');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="datasource-index">
<h1><?= Html::encode($this->title) ?></h1>
<?=$this->render('/_menus') ?>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('<i class="glyphicon glyphicon-plus"></i> '.Yii::t('app', 'Create Datasource'), ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'name',
// 'created_at',
// 'updated_at',
// 'created_by',
'updated_by:dateTime',
[
'class' => 'yii\grid\ActionColumn',
'options'=>['style'=>'width:150px;'],
'buttonOptions'=>['class'=>'btn btn-default'],
'template'=>'<div class="btn-group btn-group-sm text-center" role="group">{view} {update} {delete} </div>',
]
],
]); ?>
<?php Pjax::end(); ?></div>
| Java |
module Web::Controllers::Books
class Create
include Web::Action
expose :book
params do
param :book do
param :title, presence: true
param :author, presence: true
end
end
def call(params)
if params.valid?
@book = BookRepository.create(Book.new(params[:book]))
redirect_to routes.books_path
end
end
end
end
| Java |
;idta.asm sets up all the intterupt entry points
extern default_handler
extern idt_ftoi
;error interrupt entry point, we need to only push the error code details to stack
%macro error_interrupt 1
global interrupt_handler_%1
interrupt_handler_%1:
push dword %1
jmp common_handler
%endmacro
;regular interrupt entry point, need to push interrupt number and other data
%macro regular_interrupt 1
global interrupt_handler_%1
interrupt_handler_%1:
push dword 0
push dword %1
jmp common_handler
%endmacro
;common handler for all interrupts, saves all necessary stack data and calls our c intterupt handler
common_handler:
push dword ds
push dword es
push dword fs
push dword gs
pusha
call default_handler
popa
pop dword gs
pop dword fs
pop dword es
pop dword ds
add esp, 8
iret
regular_interrupt 0
regular_interrupt 1
regular_interrupt 2
regular_interrupt 3
regular_interrupt 4
regular_interrupt 5
regular_interrupt 6
regular_interrupt 7
error_interrupt 8
regular_interrupt 9
error_interrupt 10
error_interrupt 11
error_interrupt 12
error_interrupt 13
error_interrupt 14
regular_interrupt 15
regular_interrupt 16
error_interrupt 17
%assign i 18
%rep 12
regular_interrupt i
%assign i i+1
%endrep
error_interrupt 30
%assign i 31
%rep 225
regular_interrupt i
%assign i i+1
%endrep
;interrupt setup, adds all of out interrupt handlers to the idt
global idtsetup
idtsetup:
%assign i 0
%rep 256
push interrupt_handler_%[i]
push i
call idt_ftoi
add esp, 8
%assign i i+1
%endrep
ret
| Java |
// @flow
(require('../../lib/git'): any).rebaseRepoMaster = jest.fn();
import {
_clearCustomCacheDir as clearCustomCacheDir,
_setCustomCacheDir as setCustomCacheDir,
} from '../../lib/cacheRepoUtils';
import {copyDir, mkdirp} from '../../lib/fileUtils';
import {parseDirString as parseFlowDirString} from '../../lib/flowVersion';
import {
add as gitAdd,
commit as gitCommit,
init as gitInit,
setLocalConfig as gitConfig,
} from '../../lib/git';
import {fs, path, child_process} from '../../lib/node';
import {getNpmLibDefs} from '../../lib/npm/npmLibDefs';
import {testProject} from '../../lib/TEST_UTILS';
import {
_determineFlowVersion as determineFlowVersion,
_installNpmLibDefs as installNpmLibDefs,
_installNpmLibDef as installNpmLibDef,
run,
} from '../install';
const BASE_FIXTURE_ROOT = path.join(__dirname, '__install-fixtures__');
function _mock(mockFn) {
return ((mockFn: any): JestMockFn<*, *>);
}
async function touchFile(filePath) {
await fs.close(await fs.open(filePath, 'w'));
}
async function writePkgJson(filePath, pkgJson) {
await fs.writeJson(filePath, pkgJson);
}
describe('install (command)', () => {
describe('determineFlowVersion', () => {
it('infers version from path if arg not passed', () => {
return testProject(async ROOT_DIR => {
const ARBITRARY_PATH = path.join(ROOT_DIR, 'some', 'arbitrary', 'path');
await Promise.all([
mkdirp(ARBITRARY_PATH),
touchFile(path.join(ROOT_DIR, '.flowconfig')),
writePkgJson(path.join(ROOT_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.40.0',
},
}),
]);
const flowVer = await determineFlowVersion(ARBITRARY_PATH);
expect(flowVer).toEqual({
kind: 'specific',
ver: {
major: 0,
minor: 40,
patch: 0,
prerel: null,
},
});
});
});
it('uses explicitly specified version', async () => {
const explicitVer = await determineFlowVersion('/', '0.7.0');
expect(explicitVer).toEqual({
kind: 'specific',
ver: {
major: 0,
minor: 7,
patch: 0,
prerel: null,
},
});
});
it("uses 'v'-prefixed explicitly specified version", async () => {
const explicitVer = await determineFlowVersion('/', 'v0.7.0');
expect(explicitVer).toEqual({
kind: 'specific',
ver: {
major: 0,
minor: 7,
patch: 0,
prerel: null,
},
});
});
});
describe('installNpmLibDefs', () => {
const origConsoleError = console.error;
beforeEach(() => {
(console: any).error = jest.fn();
});
afterEach(() => {
(console: any).error = origConsoleError;
});
it('errors if unable to find a project root (.flowconfig)', () => {
return testProject(async ROOT_DIR => {
const result = await installNpmLibDefs({
cwd: ROOT_DIR,
flowVersion: parseFlowDirString('flow_v0.40.0'),
explicitLibDefs: [],
libdefDir: 'flow-typed',
verbose: false,
overwrite: false,
skip: false,
ignoreDeps: [],
useCacheUntil: 1000 * 60,
});
expect(result).toBe(1);
expect(_mock(console.error).mock.calls).toEqual([
[
'Error: Unable to find a flow project in the current dir or any of ' +
"it's parent dirs!\n" +
'Please run this command from within a Flow project.',
],
]);
});
});
it(
"errors if an explicitly specified libdef arg doesn't match npm " +
'pkgver format',
() => {
return testProject(async ROOT_DIR => {
await touchFile(path.join(ROOT_DIR, '.flowconfig'));
await writePkgJson(path.join(ROOT_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.40.0',
},
});
const result = await installNpmLibDefs({
cwd: ROOT_DIR,
flowVersion: parseFlowDirString('flow_v0.40.0'),
explicitLibDefs: ['INVALID'],
libdefDir: 'flow-typed',
verbose: false,
overwrite: false,
skip: false,
ignoreDeps: [],
useCacheUntil: 1000 * 60,
});
expect(result).toBe(1);
expect(_mock(console.error).mock.calls).toEqual([
[
'ERROR: Package not found from package.json.\n' +
'Please specify version for the package in the format of `foo@1.2.3`',
],
]);
});
},
);
it('warns if 0 dependencies are found in package.json', () => {
return testProject(async ROOT_DIR => {
await Promise.all([
touchFile(path.join(ROOT_DIR, '.flowconfig')),
writePkgJson(path.join(ROOT_DIR, 'package.json'), {
name: 'test',
}),
]);
const result = await installNpmLibDefs({
cwd: ROOT_DIR,
flowVersion: parseFlowDirString('flow_v0.40.0'),
explicitLibDefs: [],
libdefDir: 'flow-typed',
verbose: false,
overwrite: false,
skip: false,
ignoreDeps: [],
useCacheUntil: 1000 * 60,
});
expect(result).toBe(0);
expect(_mock(console.error).mock.calls).toEqual([
["No dependencies were found in this project's package.json!"],
]);
});
});
});
describe('installNpmLibDef', () => {
const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'installNpmLibDef');
const FIXTURE_FAKE_CACHE_REPO_DIR = path.join(
FIXTURE_ROOT,
'fakeCacheRepo',
);
const origConsoleLog = console.log;
beforeEach(() => {
(console: any).log = jest.fn();
});
afterEach(() => {
(console: any).log = origConsoleLog;
});
it('installs scoped libdefs within a scoped directory', () => {
return testProject(async ROOT_DIR => {
const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache');
const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo');
const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj');
const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm');
await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]);
await Promise.all([
copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR),
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.40.0',
},
}),
]);
await gitInit(FAKE_CACHE_REPO_DIR),
await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions');
await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST');
setCustomCacheDir(FAKE_CACHE_DIR);
const availableLibDefs = await getNpmLibDefs(
path.join(FAKE_CACHE_REPO_DIR, 'definitions'),
);
await installNpmLibDef(availableLibDefs[0], FLOWTYPED_DIR, false);
});
});
});
describe('end-to-end tests', () => {
const FIXTURE_ROOT = path.join(BASE_FIXTURE_ROOT, 'end-to-end');
const FIXTURE_FAKE_CACHE_REPO_DIR = path.join(
FIXTURE_ROOT,
'fakeCacheRepo',
);
const origConsoleLog = console.log;
const origConsoleError = console.error;
beforeEach(() => {
(console: any).log = jest.fn();
(console: any).error = jest.fn();
});
afterEach(() => {
(console: any).log = origConsoleLog;
(console: any).error = origConsoleError;
});
async function fakeProjectEnv(runTest) {
return await testProject(async ROOT_DIR => {
const FAKE_CACHE_DIR = path.join(ROOT_DIR, 'fakeCache');
const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo');
const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj');
const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm');
await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]);
await copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR);
await gitInit(FAKE_CACHE_REPO_DIR),
await Promise.all([
gitConfig(FAKE_CACHE_REPO_DIR, 'user.name', 'Test Author'),
gitConfig(FAKE_CACHE_REPO_DIR, 'user.email', 'test@flow-typed.org'),
]);
await gitAdd(FAKE_CACHE_REPO_DIR, 'definitions');
await gitCommit(FAKE_CACHE_REPO_DIR, 'FIRST');
setCustomCacheDir(FAKE_CACHE_DIR);
const origCWD = process.cwd;
(process: any).cwd = () => FLOWPROJ_DIR;
try {
await runTest(FLOWPROJ_DIR);
} finally {
(process: any).cwd = origCWD;
clearCustomCacheDir();
}
});
}
it('installs available libdefs', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
ignoreDeps: [],
explicitLibDefs: [],
});
// Installs libdefs
expect(
await Promise.all([
fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'flow-bin_v0.x.x.js',
),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
]),
).toEqual([true, true]);
// Signs installed libdefs
const fooLibDefContents = await fs.readFile(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
'utf8',
);
expect(fooLibDefContents).toContain('// flow-typed signature: ');
expect(fooLibDefContents).toContain('// flow-typed version: ');
});
});
it('installs available libdefs using PnP', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
installConfig: {
pnp: true,
},
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
// Use local foo for initial install
foo: 'file:./foo',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'foo')),
]);
await writePkgJson(path.join(FLOWPROJ_DIR, 'foo/package.json'), {
name: 'foo',
version: '1.2.3',
});
// Yarn install so PnP file resolves to local foo
await child_process.execP('yarn install', {cwd: FLOWPROJ_DIR});
// Overwrite foo dep so it's like we installed from registry instead
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
installConfig: {
pnp: true,
},
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
});
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
ignoreDeps: [],
explicitLibDefs: [],
});
// Installs libdefs
expect(
await Promise.all([
fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'flow-bin_v0.x.x.js',
),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
]),
).toEqual([true, true]);
// Signs installed libdefs
const fooLibDefRawContents = await fs.readFile(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
);
const fooLibDefContents = fooLibDefRawContents.toString();
expect(fooLibDefContents).toContain('// flow-typed signature: ');
expect(fooLibDefContents).toContain('// flow-typed version: ');
});
});
it('ignores libdefs in dev, bundled, optional or peer dependencies when flagged', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
foo: '1.2.3',
},
peerDependencies: {
'flow-bin': '^0.43.0',
},
optionalDependencies: {
foo: '2.0.0',
},
bundledDependencies: {
bar: '^1.6.9',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'bar')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
ignoreDeps: ['dev', 'optional', 'bundled'],
explicitLibDefs: [],
});
// Installs libdefs
expect(
await Promise.all([
fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'flow-bin_v0.x.x.js',
),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'bar_v1.x.x.js'),
),
]),
).toEqual([true, true, false]);
});
});
it('stubs unavailable libdefs', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
someUntypedDep: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
// Installs a stub for someUntypedDep
expect(
await fs.exists(
path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'someUntypedDep_vx.x.x.js',
),
),
).toBe(true);
});
});
it("doesn't stub unavailable libdefs when --skip is passed", () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
someUntypedDep: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'someUntypedDep')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: true,
explicitLibDefs: [],
});
// Installs a stub for someUntypedDep
expect(
await fs.exists(path.join(FLOWPROJ_DIR, 'flow-typed', 'npm')),
).toBe(true);
});
});
it('overwrites stubs when libdef becomes available (with --overwrite)', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
await fs.writeFile(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'),
'',
);
// Run the install command
await run({
overwrite: true,
verbose: false,
skip: false,
explicitLibDefs: [],
});
// Replaces the stub with the real typedef
expect(
await Promise.all([
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'),
),
fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
]),
).toEqual([false, true]);
});
});
it("doesn't overwrite tweaked libdefs (without --overwrite)", () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
const libdefFilePath = path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'foo_v1.x.x.js',
);
// Tweak the libdef for foo
const libdefFileContent =
(await fs.readFile(libdefFilePath, 'utf8')) + '\n// TWEAKED!';
await fs.writeFile(libdefFilePath, libdefFileContent);
// Run install command again
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
// Verify that the tweaked libdef file wasn't overwritten
expect(await fs.readFile(libdefFilePath, 'utf8')).toBe(
libdefFileContent,
);
});
});
it('overwrites tweaked libdefs when --overwrite is passed', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
explicitLibDefs: [],
});
const libdefFilePath = path.join(
FLOWPROJ_DIR,
'flow-typed',
'npm',
'foo_v1.x.x.js',
);
// Tweak the libdef for foo
const libdefFileContent = await fs.readFile(libdefFilePath, 'utf8');
await fs.writeFile(libdefFilePath, libdefFileContent + '\n// TWEAKED!');
// Run install command again
await run({
overwrite: true,
skip: false,
verbose: false,
explicitLibDefs: [],
});
// Verify that the tweaked libdef file wasn't overwritten
expect(await fs.readFile(libdefFilePath, 'utf8')).toBe(
libdefFileContent,
);
});
});
it('uses flow-bin defined in another package.json', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
writePkgJson(path.join(FLOWPROJ_DIR, '..', 'package.json'), {
name: 'parent',
devDependencies: {
'flow-bin': '^0.45.0',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, '..', 'node_modules', 'flow-bin')),
]);
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
packageDir: path.join(FLOWPROJ_DIR, '..'),
explicitLibDefs: [],
});
// Installs libdef
expect(
await fs.exists(
path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'),
),
).toEqual(true);
});
});
it('uses .flowconfig from specified root directory', () => {
return fakeProjectEnv(async FLOWPROJ_DIR => {
// Create some dependencies
await Promise.all([
mkdirp(path.join(FLOWPROJ_DIR, 'src')),
writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), {
name: 'test',
devDependencies: {
'flow-bin': '^0.43.0',
},
dependencies: {
foo: '1.2.3',
},
}),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')),
mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')),
]);
await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig'));
// Run the install command
await run({
overwrite: false,
verbose: false,
skip: false,
rootDir: path.join(FLOWPROJ_DIR, 'src'),
explicitLibDefs: [],
});
// Installs libdef
expect(
await fs.exists(
path.join(
FLOWPROJ_DIR,
'src',
'flow-typed',
'npm',
'foo_v1.x.x.js',
),
),
).toEqual(true);
});
});
});
});
| Java |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../openssl_sys/fn.BN_exp.html">
</head>
<body>
<p>Redirecting to <a href="../../openssl_sys/fn.BN_exp.html">../../openssl_sys/fn.BN_exp.html</a>...</p>
<script>location.replace("../../openssl_sys/fn.BN_exp.html" + location.search + location.hash);</script>
</body>
</html> | Java |
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { assign } from 'lodash'
import autoBind from '../utils/autoBind'
const styles = {
'ClosedPanelWrapper': {
height: '40px'
},
'PanelWrapper': {
position: 'relative'
},
'Over': {
border: '1px dashed white',
overflowY: 'hidden'
},
'PanelTitle': {
width: '100%',
height: '40px',
lineHeight: '40px',
backgroundColor: '#000',
color: '#fff',
paddingLeft: '10px',
position: 'relative',
whiteSpace: 'nowrap',
overflowX: 'hidden',
textOverflow: 'ellipsis',
paddingRight: '8px',
cursor: 'pointer',
WebkitUserSelect: 'none',
userSelect: 'none'
},
'Handle': {
cursor: '-webkit-grab',
position: 'absolute',
zIndex: '2',
color: 'white',
right: '10px',
fontSize: '16px',
top: '12px'
},
'OpenPanel': {
position: 'relative',
zIndex: '2',
top: '0',
left: '0',
padding: '7px',
paddingTop: '5px',
maxHeight: '30%',
display: 'block'
},
'ClosedPanel': {
height: '0',
position: 'relative',
zIndex: '2',
top: '-1000px',
left: '0',
overflow: 'hidden',
maxHeight: '0',
display: 'none'
}
}
class Panel extends Component {
constructor() {
super()
this.state = {
dragIndex: null,
overIndex: null,
isOver: false
}
autoBind(this, [
'handleTitleClick', 'handleDragStart', 'handleDragOver', 'handleDragEnter',
'handleDragLeave', 'handleDrop', 'handleDragEnd'
])
}
handleTitleClick() {
const { index, isOpen, openPanel } = this.props
openPanel(isOpen ? -1 : index)
}
handleDragStart(e) {
// e.target.style.opacity = '0.4'; // this / e.target is the source node.
e.dataTransfer.setData('index', e.target.dataset.index)
}
handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault() // Necessary. Allows us to drop.
}
return false
}
handleDragEnter(e) {
const overIndex = e.target.dataset.index
if (e.dataTransfer.getData('index') !== overIndex) {
// e.target.classList.add('Over') // e.target is the current hover target.
this.setState({ isOver: true })
}
}
handleDragLeave() {
this.setState({ isOver: false })
// e.target.classList.remove('Over') // e.target is previous target element.
}
handleDrop(e) {
if (e.stopPropagation) {
e.stopPropagation() // stops the browser from redirecting.
}
const dragIndex = e.dataTransfer.getData('index')
const dropIndex = this.props.index.toString()
if (dragIndex !== dropIndex) {
this.props.reorder(dragIndex, dropIndex)
}
return false
}
handleDragEnd() {
this.setState({ isOver: false, dragIndex: null, overIndex: null })
}
render() {
const { isOpen, orderable } = this.props
const { isOver } = this.state
return (
<div
style={assign({}, styles.PanelWrapper, isOpen ? {} : styles.ClosedPanelWrapper, isOver ? styles.Over : {})}
onDragStart={this.handleDragStart}
onDragEnter={this.handleDragEnter}
onDragOver={this.handleDragOver}
onDragLeave={this.handleDragLeave}
onDrop={this.handleDrop}
onDragEnd={this.handleDragEnd}
>
<div
style={styles.PanelTitle}
onClick={this.handleTitleClick}
draggable={orderable}
data-index={this.props.index}
>
{this.props.header}
{orderable && (<i className="fa fa-th" style={styles.Handle}></i>)}
</div>
{
isOpen &&
(
<div style={isOpen ? styles.OpenPanel : styles.ClosedPanel}>
{this.props.children}
</div>
)
}
</div>
)
}
}
Panel.propTypes = {
children: PropTypes.any,
index: PropTypes.any,
openPanel: PropTypes.func,
isOpen: PropTypes.any,
header: PropTypes.any,
orderable: PropTypes.any,
reorder: PropTypes.func
}
Panel.defaultProps = {
isOpen: false,
header: '',
orderable: false
}
export default Panel
| Java |
'use strict';
// src\services\message\hooks\timestamp.js
//
// Use this hook to manipulate incoming or outgoing data.
// For more information on hooks see: http://docs.feathersjs.com/hooks/readme.html
const defaults = {};
module.exports = function(options) {
options = Object.assign({}, defaults, options);
return function(hook) {
const usr = hook.params.user;
const txt = hook.data.text;
hook.data = {
text: txt,
createdBy: usr._id,
createdAt: Date.now()
}
};
};
| Java |
/*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2021, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the following
conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------
*/
/** @file Bitmap.h
* @brief Defines bitmap format helper for textures
*
* Used for file formats which embed their textures into the model file.
*/
#pragma once
#ifndef AI_BITMAP_H_INC
#define AI_BITMAP_H_INC
#ifdef __GNUC__
# pragma GCC system_header
#endif
#include "defs.h"
#include <stdint.h>
#include <cstddef>
struct aiTexture;
namespace Assimp {
class IOStream;
class ASSIMP_API Bitmap {
protected:
struct Header {
uint16_t type;
uint32_t size;
uint16_t reserved1;
uint16_t reserved2;
uint32_t offset;
// We define the struct size because sizeof(Header) might return a wrong result because of structure padding.
// Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field).
static const std::size_t header_size =
sizeof(uint16_t) + // type
sizeof(uint32_t) + // size
sizeof(uint16_t) + // reserved1
sizeof(uint16_t) + // reserved2
sizeof(uint32_t); // offset
};
struct DIB {
uint32_t size;
int32_t width;
int32_t height;
uint16_t planes;
uint16_t bits_per_pixel;
uint32_t compression;
uint32_t image_size;
int32_t x_resolution;
int32_t y_resolution;
uint32_t nb_colors;
uint32_t nb_important_colors;
// We define the struct size because sizeof(DIB) might return a wrong result because of structure padding.
// Moreover, we must use this ugly and error prone syntax because Visual Studio neither support constexpr or sizeof(name_of_field).
static const std::size_t dib_size =
sizeof(uint32_t) + // size
sizeof(int32_t) + // width
sizeof(int32_t) + // height
sizeof(uint16_t) + // planes
sizeof(uint16_t) + // bits_per_pixel
sizeof(uint32_t) + // compression
sizeof(uint32_t) + // image_size
sizeof(int32_t) + // x_resolution
sizeof(int32_t) + // y_resolution
sizeof(uint32_t) + // nb_colors
sizeof(uint32_t); // nb_important_colors
};
static const std::size_t mBytesPerPixel = 4;
public:
static void Save(aiTexture* texture, IOStream* file);
protected:
static void WriteHeader(Header& header, IOStream* file);
static void WriteDIB(DIB& dib, IOStream* file);
static void WriteData(aiTexture* texture, IOStream* file);
};
}
#endif // AI_BITMAP_H_INC
| Java |
# LeadifyTest | Java |
package fr.lteconsulting.pomexplorer.commands;
import fr.lteconsulting.pomexplorer.AppFactory;
import fr.lteconsulting.pomexplorer.Client;
import fr.lteconsulting.pomexplorer.Log;
public class HelpCommand
{
@Help( "gives this message" )
public void main( Client client, Log log )
{
log.html( AppFactory.get().commands().help() );
}
}
| Java |
//
// DORDoneHUD.h
// DORDoneHUD
//
// Created by Pawel Bednorz on 23/09/15.
// Copyright © 2015 Droids on Roids. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface DORDoneHUD : NSObject
+ (void)show:(UIView *)view message:(NSString *)messageText completion:(void (^)(void))completionBlock;
+ (void)show:(UIView *)view message:(NSString *)messageText;
+ (void)show:(UIView *)view;
@end
| Java |
namespace CAAssistant.Models
{
public class ClientFileViewModel
{
public ClientFileViewModel()
{
}
public ClientFileViewModel(ClientFile clientFile)
{
Id = clientFile.Id;
FileNumber = clientFile.FileNumber;
ClientName = clientFile.ClientName;
ClientContactPerson = clientFile.ClientContactPerson;
AssociateReponsible = clientFile.AssociateReponsible;
CaSign = clientFile.CaSign;
DscExpiryDate = clientFile.DscExpiryDate;
FileStatus = clientFile.FileStatus;
}
public string Id { get; set; }
public int FileNumber { get; set; }
public string ClientName { get; set; }
public string ClientContactPerson { get; set; }
public string AssociateReponsible { get; set; }
public string CaSign { get; set; }
public string DscExpiryDate { get; set; }
public string FileStatus { get; set; }
public string UserName { get; set; }
public FileStatusModification InitialFileStatus { get; set; }
}
} | Java |
<?php
/****************************************************************************
* todoyu is published under the BSD License:
* http://www.opensource.org/licenses/bsd-license.php
*
* Copyright (c) 2013, snowflake productions GmbH, Switzerland
* All rights reserved.
*
* This script is part of the todoyu project.
* The todoyu project is free software; you can redistribute it and/or modify
* it under the terms of the BSD License.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD License
* for more details.
*
* This copyright notice MUST APPEAR in all copies of the script.
*****************************************************************************/
/**
* Task asset object
*
* @package Todoyu
* @subpackage Assets
*/
class TodoyuAssetsTaskAsset extends TodoyuAssetsAsset {
/**
* Get task ID
*
* @return Integer
*/
public function getTaskID() {
return $this->getParentID();
}
/**
* Get task object
*
* @return Task
*/
public function getTask() {
return TodoyuProjectTaskManager::getTask($this->getTaskID());
}
}
?> | Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace NewsSystem.Web.Admin
{
public partial class Edit
{
}
}
| Java |
---
title: Stylesheets and JavaScript - Fabricator
layout: 2-column
section: Documentation
---
{{#markdown}}
# Stylesheets and JavaScript
> How to work with CSS and JS within Fabricator
Fabricator comes with little opinion about how you should architect your Stylesheets and JavaScript. Each use case is different, so it's up to you to define what works best.
Out of the box, you'll find a single `.scss` and `.js` file. These are the entry points for Sass compilation and Webpack respectively. It is recommended that you leverage the module importing features of each preprocessor to compile your toolkit down to a single `.css` and `.js` file. Practically speaking, you should be able to drop these two files into any application and have full access to your entire toolkit.
{{/markdown}}
| Java |
<?php
namespace IdeHelper\Test\TestCase\Utility;
use Cake\Core\Configure;
use Cake\TestSuite\TestCase;
use IdeHelper\Utility\Plugin;
class PluginTest extends TestCase {
/**
* @return void
*/
protected function setUp(): void {
parent::setUp();
Configure::delete('IdeHelper.plugins');
}
/**
* @return void
*/
protected function tearDown(): void {
parent::tearDown();
Configure::delete('IdeHelper.plugins');
}
/**
* @return void
*/
public function testAll() {
$result = Plugin::all();
$this->assertArrayHasKey('IdeHelper', $result);
$this->assertArrayHasKey('Awesome', $result);
$this->assertArrayHasKey('MyNamespace/MyPlugin', $result);
$this->assertArrayNotHasKey('FooBar', $result);
Configure::write('IdeHelper.plugins', ['FooBar', '-MyNamespace/MyPlugin']);
$result = Plugin::all();
$this->assertArrayHasKey('FooBar', $result);
$this->assertArrayNotHasKey('MyNamespace/MyPlugin', $result);
}
}
| Java |
# Hubot: hubot-loggly-slack
A hubot script to post alerts from Loggly into a Slack room as an attachment.
An attachment has additional formatting options.
See [`src/loggly-slack.coffee`](src/loggly-slack.coffee) for documentation.
# Installation
npm install hubot-loggly-slack
# Add "hubot-loggly-slack" to external-scripts.json
# Other hubot slack modules
https://github.com/spanishdict/hubot-awssns-slack
https://github.com/spanishdict/hubot-loggly-slack
https://github.com/spanishdict/hubot-scoutapp-slack
| Java |
<?php
/**
* The Initial Developer of the Original Code is
* Tarmo Alexander Sundström <ta@sundstrom.im>.
*
* Portions created by the Initial Developer are
* Copyright (C) 2014 Tarmo Alexander Sundström <ta@sundstrom.im>
*
* All Rights Reserved.
*
* Contributor(s):
*
* 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.
*/
namespace Webvaloa;
use Libvaloa\Db;
use RuntimeException;
/**
* Manage and run plugins.
*/
class Plugin
{
private $db;
private $plugins;
private $runnablePlugins;
private $plugin;
// Objects that plugins can access
public $_properties;
public $ui;
public $controller;
public $request;
public $view;
public $xhtml;
public static $properties = array(
// Vendor tag
'vendor' => 'ValoaApplication',
// Events
'events' => array(
'onAfterFrontControllerInit',
'onBeforeController',
'onAfterController',
'onBeforeRender',
'onAfterRender',
),
// Skip plugins in these controllers
'skipControllers' => array(
'Setup',
),
);
public function __construct($plugin = false)
{
$this->plugin = $plugin;
$this->event = false;
$this->plugins = false;
$this->runnablePlugins = false;
// Plugins can access and modify these
$this->_properties = false;
$this->ui = false;
$this->controller = false;
$this->request = false;
$this->view = false;
$this->xhtml = false;
try {
$this->db = \Webvaloa\Webvaloa::DBConnection();
} catch (Exception $e) {
}
}
public function setEvent($e)
{
if (in_array($e, self::$properties['events'])) {
$this->event = $e;
}
}
public function plugins()
{
if (!method_exists($this->db, 'prepare')) {
// Just bail out
return false;
}
if (method_exists($this->request, 'getMainController') && (in_array($this->request->getMainController(), self::$properties['skipControllers']))) {
return false;
}
$query = '
SELECT id, plugin, system_plugin
FROM plugin
WHERE blocked = 0
ORDER BY ordering ASC';
try {
$stmt = $this->db->prepare($query);
$stmt->execute();
$this->plugins = $stmt->fetchAll();
return $this->plugins;
} catch (PDOException $e) {
}
}
public function pluginExists($name)
{
$name = trim($name);
foreach ($this->plugins as $k => $plugin) {
if ($plugin->plugin == $name) {
return true;
}
}
return false;
}
public function hasRunnablePlugins()
{
// Return runnable plugins if we already gathered them
if ($this->runnablePlugins) {
return $this->runnablePlugins;
}
if (!$this->request) {
throw new RuntimeException('Instance of request is required');
}
if (in_array($this->request->getMainController(), self::$properties['skipControllers'])) {
return false;
}
// Load plugins
if (!$this->plugins) {
$this->plugins();
}
if (!is_array($this->plugins)) {
return false;
}
$controller = $this->request->getMainController();
// Look for executable plugins
foreach ($this->plugins as $k => $plugin) {
if ($controller && strpos($plugin->plugin, $controller) === false
&& strpos($plugin->plugin, 'Plugin') === false) {
continue;
}
$this->runnablePlugins[] = $plugin;
}
return (bool) ($this->runnablePlugins && !empty($this->runnablePlugins)) ? $this->runnablePlugins : false;
}
public function runPlugins()
{
if (!$this->runnablePlugins || empty($this->runnablePlugins)) {
return false;
}
$e = $this->event;
foreach ($this->runnablePlugins as $k => $v) {
$p = '\\'.self::$properties['vendor'].'\Plugins\\'.$v->plugin.'Plugin';
$plugin = new $p();
$plugin->view = &$this->view;
$plugin->ui = &$this->ui;
$plugin->request = &$this->request;
$plugin->controller = &$this->controller;
$plugin->xhtml = &$this->xhtml;
$plugin->_properties = &$this->_properties;
if (method_exists($plugin, $e)) {
$plugin->{$e}();
}
}
}
public static function getPluginStatus($pluginID)
{
$query = '
SELECT blocked
FROM plugin
WHERE system_plugin = 0
AND id = ?';
try {
$db = \Webvaloa\Webvaloa::DBConnection();
$stmt = $db->prepare($query);
$stmt->set((int) $pluginID);
$stmt->execute();
$row = $stmt->fetch();
if (isset($row->blocked)) {
return $row->blocked;
}
return false;
} catch (PDOException $e) {
}
}
public static function setPluginStatus($pluginID, $status = 0)
{
$query = '
UPDATE plugin
SET blocked = ?
WHERE id = ?';
try {
$db = \Webvaloa\Webvaloa::DBConnection();
$stmt = $db->prepare($query);
$stmt->set((int) $status);
$stmt->set((int) $pluginID);
$stmt->execute();
} catch (PDOException $e) {
}
}
public static function setPluginOrder($pluginID, $ordering = 0)
{
$query = '
UPDATE plugin
SET ordering = ?
WHERE id = ?';
try {
$db = \Webvaloa\Webvaloa::DBConnection();
$stmt = $db->prepare($query);
$stmt->set((int) $ordering);
$stmt->set((int) $pluginID);
$stmt->execute();
} catch (PDOException $e) {
}
}
public function install()
{
if (!$this->plugin) {
return false;
}
$installable = $this->discover();
if (!in_array($this->plugin, $installable)) {
return false;
}
$db = \Webvaloa\Webvaloa::DBConnection();
// Install plugin
$object = new Db\Object('plugin', $db);
$object->plugin = $this->plugin;
$object->system_plugin = 0;
$object->blocked = 0;
$object->ordering = 1;
$id = $object->save();
return $id;
}
public function uninstall()
{
if (!$this->plugin) {
return false;
}
$db = \Webvaloa\Webvaloa::DBConnection();
$query = '
DELETE FROM plugin
WHERE system_plugin = 0
AND plugin = ?';
$stmt = $db->prepare($query);
try {
$stmt->set($this->plugin);
$stmt->execute();
return true;
} catch (Exception $e) {
}
return false;
}
public function discover()
{
// Installed plugins
$tmp = $this->plugins();
foreach ($tmp as $v => $plugin) {
$plugins[] = $plugin->plugin;
}
// Discovery paths
$paths[] = LIBVALOA_INSTALLPATH.DIRECTORY_SEPARATOR.self::$properties['vendor'].DIRECTORY_SEPARATOR.'Plugins';
$paths[] = LIBVALOA_EXTENSIONSPATH.DIRECTORY_SEPARATOR.self::$properties['vendor'].DIRECTORY_SEPARATOR.'Plugins';
$skip = array(
'.',
'..',
);
$plugins = array_merge($plugins, $skip);
// Look for new plugins
foreach ($paths as $path) {
if ($handle = opendir($path)) {
while (false !== ($entry = readdir($handle))) {
if ($entry == '.' || $entry == '..') {
continue;
}
if (substr($entry, -3) != 'php') {
continue;
}
$pluginName = str_replace('Plugin.php', '', $entry);
if (!isset($installablePlugins)) {
$installablePlugins = array();
}
if (!in_array($pluginName, $plugins) && !in_array($pluginName, $installablePlugins)) {
$installablePlugins[] = $pluginName;
}
}
closedir($handle);
}
}
if (isset($installablePlugins)) {
return $installablePlugins;
}
return array();
}
}
| Java |
const electron = window.require('electron');
const events = window.require('events');
const {
ipcRenderer
} = electron;
const {
EventEmitter
} = events;
class Emitter extends EventEmitter {}
window.Events = new Emitter();
module.exports = () => {
let settings = window.localStorage.getItem('settings');
if (settings === null) {
const defaultSettings = {
general: {
launch: true,
clipboard: true
},
images: {
copy: false,
delete: true
},
notifications: {
enabled: true
}
};
window.localStorage.setItem('settings', JSON.stringify(defaultSettings));
settings = defaultSettings;
}
ipcRenderer.send('settings', JSON.parse(settings));
};
| Java |
---
title: 'Production applications updated 9.1.2018 10:05 - 10:54'
lang: en
ref: 2018-01-09-release
image:
published: true
categories: en News
traffictypes:
- Road
tags:
- APIs
- Admin
---
Digitraffic production applications have been updated.
Changelog:
TIE
- DPO-336 - LAM binääritietovirta jakautuu kahdeksi LOTJU 2.5 versiossa
- Ei vaikuta datan formaattiin. Reaaliaika-asemien tiedot ovat nyt tuoreempia.
- DPO-399 - CameraStationsStatusMetadataUpdateJob ei käsittele obsolete tietoa oikein
We apologize for any inconvenience.
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using BohFoundation.ApplicantsRepository.Repositories.Implementations;
using BohFoundation.AzureStorage.TableStorage.Implementations.Essay.Entities;
using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay;
using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay.Helpers;
using BohFoundation.Domain.Dtos.Applicant.Essay;
using BohFoundation.Domain.Dtos.Applicant.Notifications;
using BohFoundation.Domain.Dtos.Common.AzureQueuryObjects;
using BohFoundation.Domain.EntityFrameworkModels.Applicants;
using BohFoundation.Domain.EntityFrameworkModels.Common;
using BohFoundation.Domain.EntityFrameworkModels.Persons;
using BohFoundation.EntityFrameworkBaseClass;
using BohFoundation.TestHelpers;
using EntityFramework.Extensions;
using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BohFoundation.ApplicantsRepository.Tests.IntegrationTests
{
[TestClass]
public class ApplicantsEssayRepositoryIntegrationTests
{
private static IEssayRowKeyGenerator _rowKeyGenerator;
private static IAzureEssayRepository _azureAzureEssayRepository;
private static ApplicantsEssayRepository _applicantsEssayRepository;
private static ApplicantsesNotificationRepository _applicantsesNotification;
[ClassInitialize]
public static void InitializeClass(TestContext ctx)
{
Setup();
FirstTestOfNotifications();
FirstUpsert();
SecondUpsert();
SecondTestOfNotifications();
}
#region SettingUp
private static void Setup()
{
TestHelpersCommonFields.InitializeFields();
TestHelpersCommonFakes.InitializeFakes();
ApplicantsGuid = Guid.NewGuid();
Prompt = "prompt" + ApplicantsGuid;
TitleOfEssay = "title" + ApplicantsGuid;
_azureAzureEssayRepository = A.Fake<IAzureEssayRepository>();
_rowKeyGenerator = A.Fake<IEssayRowKeyGenerator>();
CreateEssayTopicAndApplicant();
SetupFakes();
_applicantsesNotification = new ApplicantsesNotificationRepository(TestHelpersCommonFields.DatabaseName,
TestHelpersCommonFakes.ClaimsInformationGetters, TestHelpersCommonFakes.DeadlineUtilities);
_applicantsEssayRepository = new ApplicantsEssayRepository(TestHelpersCommonFields.DatabaseName,
TestHelpersCommonFakes.ClaimsInformationGetters, _azureAzureEssayRepository, _rowKeyGenerator);
}
private static void CreateEssayTopicAndApplicant()
{
var random = new Random();
GraduatingYear = random.Next();
var subject = new EssayTopic
{
EssayPrompt = Prompt,
TitleOfEssay = TitleOfEssay,
RevisionDateTime = DateTime.UtcNow
};
var subject2 = new EssayTopic
{
EssayPrompt = Prompt + 2,
TitleOfEssay = TitleOfEssay + 2,
RevisionDateTime = DateTime.UtcNow
};
var subject3 = new EssayTopic
{
EssayPrompt = "SHOULD NOT SHOW UP IN LIST",
TitleOfEssay = "REALLY SHOULDN't SHOW up",
RevisionDateTime = DateTime.UtcNow,
};
var graduatingYear = new GraduatingClass
{
GraduatingYear = GraduatingYear,
EssayTopics = new List<EssayTopic> { subject, subject2 }
};
var applicant = new Applicant
{
Person = new Person { Guid = ApplicantsGuid, DateCreated = DateTime.UtcNow },
ApplicantPersonalInformation =
new ApplicantPersonalInformation
{
GraduatingClass = graduatingYear,
Birthdate = DateTime.UtcNow,
LastUpdated = DateTime.UtcNow
}
};
using (var context = GetRootContext())
{
context.EssayTopics.Add(subject3);
context.GraduatingClasses.Add(graduatingYear);
context.Applicants.Add(applicant);
context.EssayTopics.Add(subject);
context.SaveChanges();
EssayTopicId = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt).Id;
EssayTopicId2 = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt + 2).Id;
}
}
private static int EssayTopicId2 { get; set; }
private static void SetupFakes()
{
RowKey = "THISISTHEROWKEYFORTHEAPPLICANT";
A.CallTo(() => TestHelpersCommonFakes.ClaimsInformationGetters.GetApplicantsGraduatingYear())
.Returns(GraduatingYear);
A.CallTo(() => TestHelpersCommonFakes.ClaimsInformationGetters.GetUsersGuid()).Returns(ApplicantsGuid);
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).Returns(RowKey);
}
private static string RowKey { get; set; }
private static int GraduatingYear { get; set; }
private static string TitleOfEssay { get; set; }
private static string Prompt { get; set; }
private static Guid ApplicantsGuid { get; set; }
#endregion
#region FirstNotifications
private static void FirstTestOfNotifications()
{
FirstNotificationResult = _applicantsesNotification.GetApplicantNotifications();
}
private static ApplicantNotificationsDto FirstNotificationResult { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_Should_Have_Two_EssayTopics()
{
Assert.AreEqual(2, FirstNotificationResult.EssayNotifications.Count);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_No_LastUpdated()
{
foreach (var essayTopic in FirstNotificationResult.EssayNotifications)
{
Assert.IsNull(essayTopic.RevisionDateTime);
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_EssayTopic()
{
foreach (var essayTopic in FirstNotificationResult.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay);
}
else
{
Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_Ids()
{
foreach (var essayTopic in FirstNotificationResult.EssayNotifications)
{
Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId);
}
}
#endregion
#region FirstUpsert
private static void FirstUpsert()
{
Essay = "Essay";
var dto = new EssayDto {Essay = Essay + 1, EssayPrompt = Prompt, EssayTopicId = EssayTopicId};
_applicantsEssayRepository.UpsertEssay(dto);
using (var context = GetRootContext())
{
EssayUpsertResult1 =
context.Essays.First(
essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid);
}
}
private static Essay EssayUpsertResult1 { get; set; }
private static string Essay { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_6_Characters()
{
Assert.AreEqual(6, EssayUpsertResult1.CharacterLength);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_RecentUpdated()
{
TestHelpersTimeAsserts.RecentTime(EssayUpsertResult1.RevisionDateTime);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_Correct_RowKey()
{
Assert.AreEqual(RowKey, EssayUpsertResult1.RowKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_Correct_PartitionKey()
{
Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult1.PartitionKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Positive_Id()
{
TestHelpersCommonAsserts.IsGreaterThanZero(EssayUpsertResult1.Id);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Call_CreateRowKey()
{
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Call_UpsertEssay()
{
//Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did.
A.CallTo(() => _azureAzureEssayRepository.UpsertEssay(A<EssayAzureTableEntityDto>
.That.Matches(x =>
x.Essay == Essay + 1 &&
x.EssayPrompt == Prompt &&
x.EssayTopicId == EssayTopicId &&
x.PartitionKey == GraduatingYear.ToString() &&
x.RowKey == RowKey
))).MustHaveHappened();
}
#endregion
#region SecondUpsert
private static void SecondUpsert()
{
var dto = new EssayDto {Essay = Essay + Essay + Essay, EssayPrompt = Prompt, EssayTopicId = EssayTopicId};
_applicantsEssayRepository.UpsertEssay(dto);
using (var context = GetRootContext())
{
EssayUpsertResult2 =
context.Essays.First(
essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid);
}
}
private static Essay EssayUpsertResult2 { get; set; }
private static int EssayTopicId { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_15_Characters()
{
Assert.AreEqual(15, EssayUpsertResult2.CharacterLength);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_RecentUpdated_More_Recent_Than_First()
{
TestHelpersTimeAsserts.IsGreaterThanOrEqual(EssayUpsertResult2.RevisionDateTime,
EssayUpsertResult1.RevisionDateTime);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_Correct_RowKey()
{
Assert.AreEqual(RowKey, EssayUpsertResult2.RowKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_Correct_PartitionKey()
{
Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult2.PartitionKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Equal_Id_To_First()
{
Assert.AreEqual(EssayUpsertResult1.Id, EssayUpsertResult2.Id);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Call_CreateRowKey()
{
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId))
.MustHaveHappened(Repeated.AtLeast.Times(3));
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Call_UpsertEssay()
{
//Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did.
A.CallTo(() => _azureAzureEssayRepository.UpsertEssay(A<EssayAzureTableEntityDto>
.That.Matches(x =>
x.Essay == Essay + Essay + Essay &&
x.EssayPrompt == Prompt &&
x.EssayTopicId == EssayTopicId &&
x.PartitionKey == GraduatingYear.ToString() &&
x.RowKey == RowKey
))).MustHaveHappened();
}
#endregion
#region SecondNotifications
private static void SecondTestOfNotifications()
{
SecondNotificationResult = _applicantsesNotification.GetApplicantNotifications();
}
private static ApplicantNotificationsDto SecondNotificationResult { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_Should_Have_Two_EssayTopics()
{
Assert.AreEqual(2, SecondNotificationResult.EssayNotifications.Count);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_No_LastUpdated()
{
foreach (var essayTopic in SecondNotificationResult.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(EssayUpsertResult2.RevisionDateTime, essayTopic.RevisionDateTime);
}
else
{
Assert.IsNull(essayTopic.RevisionDateTime);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_EssayTopic()
{
foreach (var essayTopic in SecondNotificationResult.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay);
}
else
{
Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_Ids()
{
foreach (var essayTopic in SecondNotificationResult.EssayNotifications)
{
Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId);
}
}
#endregion
#region Utilities
private static DatabaseRootContext GetRootContext()
{
return new DatabaseRootContext(TestHelpersCommonFields.DatabaseName);
}
[ClassCleanup]
public static void CleanDb()
{
using (var context = new DatabaseRootContext(TestHelpersCommonFields.DatabaseName))
{
context.Essays.Where(essay => essay.Id > 0).Delete();
context.EssayTopics.Where(essayTopic => essayTopic.Id > 0).Delete();
context.ApplicantPersonalInformations.Where(info => info.Id > 0).Delete();
context.GraduatingClasses.Where(gradClass => gradClass.Id > 0).Delete();
}
}
#endregion
#region GetEssay
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_GetEssay_Should_Call_CreateRowKeyForEssay()
{
GetEssay();
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_GetEssay_Should_Call_AzureEssayRepository()
{
GetEssay();
A.CallTo(
() =>
_azureAzureEssayRepository.GetEssay(
A<AzureTableStorageEntityKeyDto>.That.Matches(
x => x.PartitionKey == GraduatingYear.ToString() && x.RowKey == RowKey))).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_GetEssay_Should_Return_Whatever_TheAzureRepoReturns()
{
var essayDto = new EssayDto();
A.CallTo(() => _azureAzureEssayRepository.GetEssay(A<AzureTableStorageEntityKeyDto>.Ignored))
.Returns(essayDto);
Assert.AreSame(essayDto, GetEssay());
}
private EssayDto GetEssay()
{
return _applicantsEssayRepository.GetEssay(EssayTopicId);
}
#endregion
}
}
| Java |
class AddAuthorAndSubjectToClaimStateTransitions < ActiveRecord::Migration[4.2]
def change
add_column :claim_state_transitions, :author_id, :integer
add_column :claim_state_transitions, :subject_id, :integer
end
end
| Java |
# Using a compact OS
FROM registry.dataos.io/library/nginx
MAINTAINER Golfen Guo <golfen.guo@daocloud.io>
# Install Nginx
# Add 2048 stuff into Nginx server
COPY . /usr/share/nginx/html
EXPOSE 80
| Java |
require 'test_helper'
require 'cache_value/util'
class UtilTest < Test::Unit::TestCase
include CacheValue::Util
context 'hex_digest' do
should 'return the same digest for identical hashes' do
hex_digest({ :ha => 'ha'}).should == hex_digest({ :ha => 'ha'})
end
end
end
| Java |
# This migration comes from thinkspace_resource (originally 20150502000000)
class AddFingerprintToFile < ActiveRecord::Migration
def change
add_column :thinkspace_resource_files, :file_fingerprint, :string
end
end
| Java |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_04_01;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Tags object for patch operations.
*/
public class TagsObject {
/**
* Resource tags.
*/
@JsonProperty(value = "tags")
private Map<String, String> tags;
/**
* Get resource tags.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set resource tags.
*
* @param tags the tags value to set
* @return the TagsObject object itself.
*/
public TagsObject withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
}
| Java |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* 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.
*/
package org.spongepowered.common.mixin.core.server.network;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.login.server.S00PacketDisconnect;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.management.ServerConfigurationManager;
import net.minecraft.server.network.NetHandlerLoginServer;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.util.IChatComponent;
import org.apache.logging.log4j.Logger;
import org.spongepowered.api.event.cause.NamedCause;
import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.event.SpongeEventFactory;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.event.network.ClientConnectionEvent;
import org.spongepowered.api.network.RemoteConnection;
import org.spongepowered.api.text.Text;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.common.interfaces.IMixinNetHandlerLoginServer;
import org.spongepowered.common.text.SpongeTexts;
import java.net.SocketAddress;
import java.util.Optional;
@Mixin(NetHandlerLoginServer.class)
public abstract class MixinNetHandlerLoginServer implements IMixinNetHandlerLoginServer {
@Shadow private static Logger logger;
@Shadow public NetworkManager networkManager;
@Shadow private MinecraftServer server;
@Shadow private com.mojang.authlib.GameProfile loginGameProfile;
@Shadow public abstract String getConnectionInfo();
@Shadow public abstract com.mojang.authlib.GameProfile getOfflineProfile(com.mojang.authlib.GameProfile profile);
@Redirect(method = "tryAcceptPlayer", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/management/ServerConfigurationManager;"
+ "allowUserToConnect(Ljava/net/SocketAddress;Lcom/mojang/authlib/GameProfile;)Ljava/lang/String;"))
public String onAllowUserToConnect(ServerConfigurationManager confMgr, SocketAddress address, com.mojang.authlib.GameProfile profile) {
return null; // We handle disconnecting
}
private void closeConnection(IChatComponent reason) {
try {
logger.info("Disconnecting " + this.getConnectionInfo() + ": " + reason.getUnformattedText());
this.networkManager.sendPacket(new S00PacketDisconnect(reason));
this.networkManager.closeChannel(reason);
} catch (Exception exception) {
logger.error("Error whilst disconnecting player", exception);
}
}
private void disconnectClient(Optional<Text> disconnectMessage) {
IChatComponent reason = null;
if (disconnectMessage.isPresent()) {
reason = SpongeTexts.toComponent(disconnectMessage.get());
} else {
reason = new ChatComponentTranslation("disconnect.disconnected");
}
this.closeConnection(reason);
}
@Override
public boolean fireAuthEvent() {
Optional<Text> disconnectMessage = Optional.of(Text.of("You are not allowed to log in to this server."));
ClientConnectionEvent.Auth event = SpongeEventFactory.createClientConnectionEventAuth(Cause.of(NamedCause.source(this.loginGameProfile)),
disconnectMessage, disconnectMessage, (RemoteConnection) this.networkManager, (GameProfile) this.loginGameProfile);
SpongeImpl.postEvent(event);
if (event.isCancelled()) {
this.disconnectClient(event.getMessage());
}
return event.isCancelled();
}
@Inject(method = "processLoginStart", at = @At(value = "FIELD", target = "Lnet/minecraft/server/network/NetHandlerLoginServer;"
+ "currentLoginState:Lnet/minecraft/server/network/NetHandlerLoginServer$LoginState;",
opcode = Opcodes.PUTFIELD, ordinal = 1), cancellable = true)
public void fireAuthEventOffline(CallbackInfo ci) {
// Move this check up here, so that the UUID isn't null when we fire the event
if (!this.loginGameProfile.isComplete()) {
this.loginGameProfile = this.getOfflineProfile(this.loginGameProfile);
}
if (this.fireAuthEvent()) {
ci.cancel();
}
}
}
| Java |
from otp.ai.AIBaseGlobal import *
import DistributedCCharBaseAI
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.task import Task
import random
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
import CharStateDatasAI
class DistributedGoofySpeedwayAI(DistributedCCharBaseAI.DistributedCCharBaseAI):
notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoofySpeedwayAI')
def __init__(self, air):
DistributedCCharBaseAI.DistributedCCharBaseAI.__init__(self, air, TTLocalizer.Goofy)
self.fsm = ClassicFSM.ClassicFSM('DistributedGoofySpeedwayAI', [State.State('Off', self.enterOff, self.exitOff, ['Lonely', 'TransitionToCostume', 'Walk']),
State.State('Lonely', self.enterLonely, self.exitLonely, ['Chatty', 'Walk', 'TransitionToCostume']),
State.State('Chatty', self.enterChatty, self.exitChatty, ['Lonely', 'Walk', 'TransitionToCostume']),
State.State('Walk', self.enterWalk, self.exitWalk, ['Lonely', 'Chatty', 'TransitionToCostume']),
State.State('TransitionToCostume', self.enterTransitionToCostume, self.exitTransitionToCostume, ['Off'])], 'Off', 'Off')
self.fsm.enterInitialState()
self.handleHolidays()
def delete(self):
self.fsm.requestFinalState()
DistributedCCharBaseAI.DistributedCCharBaseAI.delete(self)
self.lonelyDoneEvent = None
self.lonely = None
self.chattyDoneEvent = None
self.chatty = None
self.walkDoneEvent = None
self.walk = None
return
def generate(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.generate(self)
name = self.getName()
self.lonelyDoneEvent = self.taskName(name + '-lonely-done')
self.lonely = CharStateDatasAI.CharLonelyStateAI(self.lonelyDoneEvent, self)
self.chattyDoneEvent = self.taskName(name + '-chatty-done')
self.chatty = CharStateDatasAI.CharChattyStateAI(self.chattyDoneEvent, self)
self.walkDoneEvent = self.taskName(name + '-walk-done')
if self.diffPath == None:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self)
else:
self.walk = CharStateDatasAI.CharWalkStateAI(self.walkDoneEvent, self, self.diffPath)
return
def walkSpeed(self):
return ToontownGlobals.GoofySpeed
def start(self):
self.fsm.request('Lonely')
def __decideNextState(self, doneStatus):
if self.transitionToCostume == 1:
curWalkNode = self.walk.getDestNode()
if simbase.air.holidayManager:
if ToontownGlobals.HALLOWEEN_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.HALLOWEEN_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
elif ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES]:
simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].triggerSwitch(curWalkNode, self)
self.fsm.request('TransitionToCostume')
else:
self.notify.warning('transitionToCostume == 1 but no costume holiday')
else:
self.notify.warning('transitionToCostume == 1 but no holiday Manager')
if doneStatus['state'] == 'lonely' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'chatty' and doneStatus['status'] == 'done':
self.fsm.request('Walk')
elif doneStatus['state'] == 'walk' and doneStatus['status'] == 'done':
if len(self.nearbyAvatars) > 0:
self.fsm.request('Chatty')
else:
self.fsm.request('Lonely')
def enterOff(self):
pass
def exitOff(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.exitOff(self)
def enterLonely(self):
self.lonely.enter()
self.acceptOnce(self.lonelyDoneEvent, self.__decideNextState)
def exitLonely(self):
self.ignore(self.lonelyDoneEvent)
self.lonely.exit()
def __goForAWalk(self, task):
self.notify.debug('going for a walk')
self.fsm.request('Walk')
return Task.done
def enterChatty(self):
self.chatty.enter()
self.acceptOnce(self.chattyDoneEvent, self.__decideNextState)
def exitChatty(self):
self.ignore(self.chattyDoneEvent)
self.chatty.exit()
def enterWalk(self):
self.notify.debug('going for a walk')
self.walk.enter()
self.acceptOnce(self.walkDoneEvent, self.__decideNextState)
def exitWalk(self):
self.ignore(self.walkDoneEvent)
self.walk.exit()
def avatarEnterNextState(self):
if len(self.nearbyAvatars) == 1:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Chatty')
else:
self.notify.debug('avatarEnterNextState: in walk state')
else:
self.notify.debug('avatarEnterNextState: num avatars: ' + str(len(self.nearbyAvatars)))
def avatarExitNextState(self):
if len(self.nearbyAvatars) == 0:
if self.fsm.getCurrentState().getName() != 'Walk':
self.fsm.request('Lonely')
def handleHolidays(self):
DistributedCCharBaseAI.DistributedCCharBaseAI.handleHolidays(self)
if hasattr(simbase.air, 'holidayManager'):
if ToontownGlobals.APRIL_FOOLS_COSTUMES in simbase.air.holidayManager.currentHolidays:
if simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES] != None and simbase.air.holidayManager.currentHolidays[ToontownGlobals.APRIL_FOOLS_COSTUMES].getRunningState():
self.diffPath = TTLocalizer.Donald
return
def getCCLocation(self):
if self.diffPath == None:
return 1
else:
return 0
return
def enterTransitionToCostume(self):
pass
def exitTransitionToCostume(self):
pass
| Java |
<?php
namespace Rmc\Core\StaticPageBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('rmc_core_static_page');
$rootNode
->children()
->arrayNode('static_page')
->children()
->scalarNode('is_enabled')->end()
->scalarNode('source')->end()
->scalarNode('entity_manager_name')->end()
->scalarNode('entity_class')->end()
->scalarNode('local_feed_path')->defaultFalse()->end()
->end()
->end()
->end();
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| Java |
<!--?xml version="1.0"?--><html><head></head><body></body></html> | Java |
import React from 'react';
import {
Link
} from 'react-router';
import HotdotActions from '../actions/HotdotActions';
import HotdotObjStore from '../stores/HotdotObjStore';
import MyInfoNavbar from './MyInfoNavbar';
import Weixin from './Weixin';
class Hotdot extends React.Component {
constructor(props) {
super(props);
this.state = HotdotObjStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
HotdotActions.getHotdotDatas();
$(".month-search").hide();
$(".navbar-hotdot").on("touchend",function(){
var index = $(this).index();
if(index==0){
//本周
$(".month-search").hide();
$(".week-search").show();
}else{
//本月
$(".month-search").show();
$(".week-search").hide();
}
});
HotdotObjStore.listen(this.onChange);
Weixin.getUrl();
Weixin.weixinReady();
}
componentWillUnmount() {
HotdotObjStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
getUpOrDown(curData,preData,isWeek){
var preDataItem = isWeek ? preData.week:preData.month;
if(preData==false || preData == [] || preDataItem==undefined){
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span>
<span className="badge">{curData.value}</span></span>);
}else{
for(var i = 0;i < preDataItem.length;i++){
if(preDataItem[i].word == curData.word){
if(preDataItem[i].value < curData.value){
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span>
<span className="badge">{curData.value}</span></span>);
}else{
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-down"></span>
<span className="badge" style={{backgroundColor:"#4F81E3"}}>{curData.value}</span></span>);
}
}
}
}
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span>
<span className="badge">{curData.value}</span></span>);
}
render() {
var hotdotData = (this.state.data);
var firstHotData = hotdotData[0];
var preHotData ;
if(hotdotData.length > 7){
preHotData = hotdotData[7];
}else{
preHotData = [];
}
if(firstHotData){
var weekList = firstHotData.week.map((weekItem,i)=>(
<li className="list-group-item" key={i}>
{this.getUpOrDown(weekItem,preHotData,true)}
{weekItem.word}
</li>
));
if(weekList.length==0){
weekList = <div className = "noData">数据还没有准备好,要不去其他页面瞅瞅?</div>
}
var monthList = firstHotData.month.map((monthItem,i)=>(
<li className="list-group-item" key={i}>
{this.getUpOrDown(monthItem,preHotData,false)}
{monthItem.word}
</li>
));
if(monthList.length==0){
monthList = <div className = "noData">Whops,这个页面的数据没有准备好,去其他页面瞅瞅?</div>
}
}else{
var weekList = (<span>正在构建,敬请期待...</span>);
var monthList = (<span>正在构建,敬请期待...</span>);
}
return (<div>
<div className="content-container">
<div className="week-search">
<div className="panel panel-back">
<div className="panel-heading">
<span className="panel-title">本周关键字排行榜</span>
<div className="navbar-key-container">
<span className="navbar-hotdot navbar-week navbar-hotdot-active">本周</span>
<span className="navbar-hotdot navbar-month">本月</span>
</div>
</div>
<div className="panel-body">
<ul className="list-group">
{weekList}
</ul>
</div>
</div>
</div>
<div className="month-search">
<div className="panel panel-back">
<div className="panel-heading">
<span className="panel-title">本月关键字排行榜</span>
<div className="navbar-key-container">
<span className="navbar-hotdot navbar-week">本周</span>
<span className="navbar-hotdot navbar-month navbar-hotdot-active">本月</span>
</div>
</div>
<div className="panel-body">
<ul className="list-group">
{monthList}
</ul>
</div>
</div>
</div>
</div>
</div>);
}
}
export default Hotdot; | Java |
// Copyright (c) 2013-2014 PropCoin Developers
#ifndef CLIENTVERSION_H
#define CLIENTVERSION_H
//
// client versioning and copyright year
//
// These need to be macros, as version.cpp's and bitcoin-qt.rc's voodoo requires it
#define CLIENT_VERSION_MAJOR 1
#define CLIENT_VERSION_MINOR 5
#define CLIENT_VERSION_REVISION 1
#define CLIENT_VERSION_BUILD 0
// Set to true for release, false for prerelease or test build
#define CLIENT_VERSION_IS_RELEASE true
// Copyright year (2009-this)
// Todo: update this when changing our copyright comments in the source
#define COPYRIGHT_YEAR 2014
// Converts the parameter X to a string after macro replacement on X has been performed.
// Don't merge these into one macro!
#define STRINGIZE(X) DO_STRINGIZE(X)
#define DO_STRINGIZE(X) #X
#endif // CLIENTVERSION_H
| Java |
varnish
=======
Varnish to run EOL site
sudo docker run -v /eol/varnish/default.vcl:/etc/varnish/default.vcl \
-p 80:80 eoldocker/varnish:v3.0.5
| Java |
<?php
namespace PayU\Api\Response\Builder;
use PayU\Api\Request\RequestInterface;
use PayU\Api\Response\AbstractResponse;
use Psr\Http\Message\ResponseInterface;
/**
* Interface BuilderInterface
*
* Provides a common interface to build response objects based on request context
*
* @package PayU\Api\Response\Builder
* @author Lucas Mendes <devsdmf@gmail.com>
*/
interface BuilderInterface
{
/**
* Build a response object
*
* @param RequestInterface $request
* @param ResponseInterface $response
* @param string $context
* @return AbstractResponse
*/
public function build(RequestInterface $request, ResponseInterface $response, $context = null);
} | Java |
using SolrExpress.Search.Parameter;
using System;
using System.Globalization;
using System.Linq;
using System.Text;
namespace SolrExpress.Utility
{
/// <summary>
/// Helper class used to extract information inside parameters
/// </summary>
internal static class ParameterUtil
{
/// <summary>
/// Get the sort type and direction
/// </summary>
/// <param name="solrFacetSortType">Type used in match</param>
/// <param name="typeName">Type name</param>
/// <param name="sortName">Sort direction</param>
public static void GetFacetSort(FacetSortType solrFacetSortType, out string typeName, out string sortName)
{
switch (solrFacetSortType)
{
case FacetSortType.IndexAsc:
typeName = "index";
sortName = "asc";
break;
case FacetSortType.IndexDesc:
typeName = "index";
sortName = "desc";
break;
case FacetSortType.CountAsc:
typeName = "count";
sortName = "asc";
break;
case FacetSortType.CountDesc:
typeName = "count";
sortName = "desc";
break;
default:
throw new ArgumentException(nameof(solrFacetSortType));
}
}
/// <summary>
/// Calculate and returns spatial formule
/// </summary>
/// <param name="fieldName">Field name</param>
/// <param name="functionType">Function used in spatial filter</param>
/// <param name="centerPoint">Center point to spatial filter</param>
/// <param name="distance">Distance from center point</param>
/// <returns>Spatial formule</returns>
internal static string GetSpatialFormule(string fieldName, SpatialFunctionType functionType, GeoCoordinate centerPoint, decimal distance)
{
var functionTypeStr = functionType.ToString().ToLower();
var latitude = centerPoint.Latitude.ToString("G", CultureInfo.InvariantCulture);
var longitude = centerPoint.Longitude.ToString("G", CultureInfo.InvariantCulture);
var distanceStr = distance.ToString("G", CultureInfo.InvariantCulture);
return $"{{!{functionTypeStr} sfield={fieldName} pt={latitude},{longitude} d={distanceStr}}}";
}
/// <summary>
/// Get the field with excludes
/// </summary>
/// <param name="excludes">Excludes tags</param>
/// <param name="aliasName">Alias name</param>
/// <param name="fieldName">Field name</param>
internal static string GetFacetName(string[] excludes, string aliasName, string fieldName)
{
var sb = new StringBuilder();
var needsBraces = (excludes?.Any() ?? false) || !string.IsNullOrWhiteSpace(aliasName);
if (needsBraces)
{
sb.Append("{!");
}
if (excludes?.Any() ?? false)
{
sb.Append($"ex={string.Join(",", excludes)}");
}
if (sb.Length > 2)
{
sb.Append(" ");
}
if (!string.IsNullOrWhiteSpace(aliasName))
{
sb.Append($"key={aliasName}");
}
if (needsBraces)
{
sb.Append("}");
}
sb.Append(fieldName);
return sb.ToString();
}
/// <summary>
/// Get the filter with tag
/// </summary>
/// <param name="query">Query value</param>
/// <param name="aliasName">Alias name</param>
public static string GetFilterWithTag(string query, string aliasName)
{
return !string.IsNullOrWhiteSpace(aliasName) ? $"{{!tag={aliasName}}}{query}" : query;
}
}
}
| Java |
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import ReactDOM from 'react-dom';
import React from 'react';
import FastClick from 'fastclick';
import Router from './routes';
import Location from './core/Location';
import { addEventListener, removeEventListener } from './core/DOMUtils';
import { ApolloClient, createNetworkInterface } from 'react-apollo';
function getCookie(name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
const networkInterface = createNetworkInterface('/graphql', {
credentials: 'same-origin',
uri: '/graphql',
headers: {
Cookie: getCookie("id_token")
}
});
const client = new ApolloClient({
connectToDevTools: true,
networkInterface: networkInterface,
});
let cssContainer = document.getElementById('css');
const appContainer = document.getElementById('app');
const context = {
insertCss: styles => styles._insertCss(),
onSetTitle: value => (document.title = value),
onSetMeta: (name, content) => {
// Remove and create a new <meta /> tag in order to make it work
// with bookmarks in Safari
const elements = document.getElementsByTagName('meta');
Array.from(elements).forEach((element) => {
if (element.getAttribute('name') === name) {
element.parentNode.removeChild(element);
}
});
const meta = document.createElement('meta');
meta.setAttribute('name', name);
meta.setAttribute('content', content);
document
.getElementsByTagName('head')[0]
.appendChild(meta);
},
client
};
// Google Analytics tracking. Don't send 'pageview' event after the first
// rendering, as it was already sent by the Html component.
let trackPageview = () => (trackPageview = () => window.ga('send', 'pageview'));
function render(state) {
Router.dispatch(state, (newState, component) => {
ReactDOM.render( component, appContainer,
() => {
// Restore the scroll position if it was saved into the state
if (state.scrollY !== undefined) {
window.scrollTo(state.scrollX, state.scrollY);
} else {
window.scrollTo(0, 0);
}
trackPageview();
// Remove the pre-rendered CSS because it's no longer used
// after the React app is launched
if (cssContainer) {
cssContainer.parentNode.removeChild(cssContainer);
cssContainer = null;
}
});
});
}
function run() {
let currentLocation = null;
let currentState = null;
// Make taps on links and buttons work fast on mobiles
FastClick.attach(document.body);
// Re-render the app when window.location changes
const unlisten = Location.listen(location => {
currentLocation = location;
currentState = Object.assign({}, location.state, {
path: location.pathname,
query: location.query,
state: location.state,
context,
});
render(currentState);
});
// Save the page scroll position into the current location's state
const supportPageOffset = window.pageXOffset !== undefined;
const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');
const setPageOffset = () => {
currentLocation.state = currentLocation.state || Object.create(null);
if (supportPageOffset) {
currentLocation.state.scrollX = window.pageXOffset;
currentLocation.state.scrollY = window.pageYOffset;
} else {
currentLocation.state.scrollX = isCSS1Compat ?
document.documentElement.scrollLeft : document.body.scrollLeft;
currentLocation.state.scrollY = isCSS1Compat ?
document.documentElement.scrollTop : document.body.scrollTop;
}
};
addEventListener(window, 'scroll', setPageOffset);
addEventListener(window, 'pagehide', () => {
removeEventListener(window, 'scroll', setPageOffset);
unlisten();
});
}
// Run the application when both DOM is ready and page content is loaded
if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) {
run();
} else {
document.addEventListener('DOMContentLoaded', run, false);
}
| Java |
var $M = require("@effectful/debugger"),
$x = $M.context,
$ret = $M.ret,
$unhandled = $M.unhandled,
$brk = $M.brk,
$lset = $M.lset,
$mcall = $M.mcall,
$m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", {
__webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__
}, null),
$s$1 = [{
e: [1, "1:9-1:10"]
}, null, 0],
$s$2 = [{}, $s$1, 1],
$m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-4:0", 32, function ($, $l, $p) {
for (;;) switch ($.state = $.goto) {
case 0:
$lset($l, 1, $m$1($));
$.goto = 2;
continue;
case 1:
$.goto = 2;
return $unhandled($.error);
case 2:
return $ret($.result);
default:
throw new Error("Invalid state");
}
}, null, null, 0, [[0, "1:0-3:1", $s$1], [16, "4:0-4:0", $s$1], [16, "4:0-4:0", $s$1]]),
$m$1 = $M.fun("m$1", "e", null, $m$0, [], 0, 2, "1:0-3:1", 0, function ($, $l, $p) {
for (;;) switch ($.state = $.goto) {
case 0:
$.goto = 1;
$brk();
$.state = 1;
case 1:
$.goto = 2;
$p = ($x.call = eff)(1);
$.state = 2;
case 2:
$l[1] = $p;
$.goto = 3;
$p = ($x.call = eff)(2);
$.state = 3;
case 3:
$.goto = 4;
$mcall("log", console, $l[1] + $p);
$.state = 4;
case 4:
$.goto = 6;
$brk();
continue;
case 5:
$.goto = 6;
return $unhandled($.error);
case 6:
return $ret($.result);
default:
throw new Error("Invalid state");
}
}, null, null, 1, [[4, "2:2-2:31", $s$2], [2, "2:14-2:20", $s$2], [2, "2:23-2:29", $s$2], [2, "2:2-2:30", $s$2], [36, "3:1-3:1", $s$2], [16, "3:1-3:1", $s$2], [16, "3:1-3:1", $s$2]]);
$M.moduleExports(); | Java |
# INTRODUCTION
Triplie is an AI bot based on 2nd up to 5th order Markov model. It uses an
SQLite database for storage.
Triplie learns by creating
1. a dictionary of words
2. a graph representing valid 5-grams (consecutive groups of 5 words)
encountered in the text
3. a graph of associations between words from sentences formed according to the
Hebbian rule
To respond to a user, triplie extracts keywords from the user's text, finds
their most appropriate associated keywords in the Hebbian association network,
and generates replies that contain the associated keywords using multiple
breadth-first-search Markov chains algorithm.
For more information on installing and configuring read below
You can join the project's IRC channel too:
[#triplie on irc.freenode.net](irc://irc.freenode.net/#triplie)
# Install
## Prerequisites
Download and install [node.js](http://nodejs.org/) for your system.
Its recommended to build node from source. If you don't do that, make
sure that npm is also installed alongside with node and that the
node binary is called "node"
Then from a terminal run:
npm install -g triplie
This will install the `triplie` command on your system.
Configure the bot as explained below before running!
# CONFIGURATION
If running the bot for the first time and its not configured,
you should create a new directory and run:
triplie config.yaml --init
to create the initial config file
### Edit config.yaml
config.yaml is already pre-filled with some default for your bot. You will want
to change some of these settings.
The configuration file is really well commented. Open it and edit it according
to the instructions contained inside. Once you run the bot however, the
instructions will disappear the moment you change a setting by giving a command
to the bot.
# RUNNING
After you edited the config file, to run the bot use the command:
triplie config.yaml
# IMPORT EXISTING TEXT
If called with the argument `--feed` triplie will receive data from stdin,
parse it using a regular expression then feed the database.
Example:
cat log.txt | triplie config.yaml --feed --regex '(?<year>\d+)-(?<month>\d+)-(?<day>)T(?<hour>\d+):(?<minute>\d+):(?<second>\d+)Z\s+(?<nick>.+):\s+(?<text>.+)'
will work for a `log.txt` that has lines in the format:
2013-04-04T13:15:00Z someuser: I wrote some text
The syntax is XRegExp and uses named groups. See
[the XRegExp readme](https://npmjs.org/package/xregexp) for more info
Currently, supported named captures are:
* year
* month
* day
* hour
* minute
* second
* timestamp - unix timestamp in seconds, used instead of the date captures
* timestampms - unix timestamp in miliseconds, used instead of both above.
* text - the text content
Timestamp example:
cat log.txt | triplie config.yaml --feed --regex '(?<timestamp>\d+) (?<text>.+)
will match `log.txt` containing lines in the format:
1234567890 example text here
All captures except text are optional - the time is optional and if left out
the feeder will generate reasonable "fake" timestamps.
cat log.txt | triplie config.yaml --feed --regex '(?<text>.+)'
# COMMANDS
List of triplie's commands (assuming "!" is the cmdchar)
1. !join #channel - causes the bot to join and remember the channel
2. !part #channel - part and forget channel
3. !reload - causes reload of the bot code, useful for development
4. !set path value - set a config setting to the specified value. Examples
!set ai.sleep.1 10 - Set the upper sleep limit to 10 seconds
!set ai.sleep [2,3] - Set both sleep limits. Value musn't contain space.
5. !get path - get the config value at the specified path
6. !db stats - triplie will output database statistics
!cmd will return results via private notice
!!cmd returns results via public message
# LICENCE & AUTHOR
See LICENCE and AUTHORS (if present)

| Java |
<!DOCTYPE html>
<html>
<head>
<!-- meta information -->
<meta charset="utf-8">
<meta name="description"
content="http://feedproxy.google.com/~r/geledes/~3/EdmSLCOQs3o/" >
<meta name="author" content="Kinho">
<!-- Enable responsiveness on mobile devices-->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<!-- title -->
<title>My post · Entropista</title>
<!-- icons -->
<link rel="shortcut icon" href="/public/images/favicon.ico" />
<!-- stylesheets -->
<link rel="stylesheet" href="/public/css/responsive.gs.12col.css">
<link rel="stylesheet" href="/public/css/animate.min.css">
<link rel="stylesheet" href="/public/css/main.css">
<!-- Google fonts -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,400italic&subset=latin-ext">
<!-- feed links -->
<link rel="alternate" href="/feed.xml" type="application/rss+xml" title="">
</head>
<body>
<div class="container amber">
<header class="top row gutters">
<div class="col span_2 center">
<!-- TODO: add baseurl to the logo link -->
<a href="" id="logo" title="Entropista"
style="background-image: url(/public/images/logo.png);"></a>
</div>
<nav class="col span_10 top-navbar">
<a href="/" title="Home"
>Home</a>
<a href="/about" title="About"
>About</a>
<a href="/NormasDeComunicaçãoViolenta" title="N.C.V."
>N.C.V.</a>
<a href="/Táticas" title="Táticas"
>Táticas</a>
<a href="/NovelaFuturista" title="Livro"
>Livro</a>
</nav>
</header>
<article class="single row gutters">
<time class="published" datetime="2015-10-12">12 October 2015</time>
<h2>My post</h2>
<p>http://feedproxy.google.com/~r/geledes/~3/EdmSLCOQs3o/</p>
</article>
<footer>
<p>
This work is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/deed.en_US">Creative Commons Attribution-NonCommercial 4.0 International License</a>.
</p>
</footer>
</div>
</body>
</html>
| Java |
module Shiphawk
module Api
# Company API
#
# @see https://shiphawk.com/api-docs
#
# The following API actions provide the CRUD interface to managing a shipment's tracking.
#
module ShipmentsStatus
def shipments_status_update options
put_request status_path, options
end
end
end
end
| Java |
import "bootstrap-slider";
import "bootstrap-switch";
export module profile {
function onInfoSubmit() {
var params: { [key: string]: string } = {};
$("#info-container .info-field").each(function() {
let name: string = this.getAttribute("name");
if (name == null) {
return;
}
let value: string = $(this).val();
if ($(this).hasClass("info-slider")) {
let valueTokens: string[] = this.getAttribute("data-value").split(",");
name = name.substring(0, 1).toUpperCase() + name.substring(1);
params["min" + name] = valueTokens[0];
params["max" + name] = valueTokens[1];
return;
} else if (this.getAttribute("type") == "checkbox") {
value = (this.checked ? 1 : 0).toString();
}
params[name] = value;
});
$.post("/office/post/update-profile", params, function(data) {
$("#errors").addClass("hidden");
$("#success").removeClass("hidden");
window.scrollTo(0, 0);
}, "json").fail(function(err) {
$("#success").addClass("hidden");
$("#errors").text(`Error code ${err.status} occurred. Please contact a developer.`);
$("#errors").removeClass("hidden");
window.scrollTo(0, 0);
});
}
$(document).ready(function() {
(<any>$("#hours-slider")).bootstrapSlider({});
$("input.info-field[type='text']").on("keydown", function(evt) {
if (evt.which == 13) {
onInfoSubmit.apply(this);
}
});
$("input.info-field[type='checkbox']").each(function(index: number, element: HTMLElement) {
let $element: JQuery = $(element);
$element.bootstrapSwitch({
"state": $element.prop("checked")
});
});
$("button.iu-button[type='submit']").on("click", onInfoSubmit);
});
}
| Java |
// Copyright (c) 2020 Uber Technologies, Inc.
//
// 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.
package main
import (
"context"
"os"
"testing"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/uber-go/dosa"
"github.com/uber-go/dosa/mocks"
)
func TestQuery_ServiceDefault(t *testing.T) {
tcs := []struct {
serviceName string
expected string
}{
// service = "" -> default
{
expected: _defServiceName,
},
// service = "foo" -> foo
{
serviceName: "foo",
expected: "foo",
},
}
for _, tc := range tcs {
for _, cmd := range []string{"read", "range"} {
os.Args = []string{
"dosa",
"--service", tc.serviceName,
"query",
cmd,
"--namePrefix", "foo",
"--scope", "bar",
"--path", "../../testentity",
"TestEntity",
"StrKey:eq:foo",
}
main()
assert.Equal(t, tc.expected, options.ServiceName)
}
}
}
func TestQuery_Read_Happy(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mc := mocks.NewMockConnector(ctrl)
mc.EXPECT().Read(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
Do(func(_ context.Context, ei *dosa.EntityInfo, keys map[string]dosa.FieldValue, minimumFields []string) {
assert.NotNil(t, ei)
assert.Equal(t, dosa.FieldValue("foo"), keys["strkey"])
assert.Equal(t, []string{"strkey", "int64key"}, minimumFields)
}).Return(map[string]dosa.FieldValue{}, nil).MinTimes(1)
mc.EXPECT().Shutdown().Return(nil)
table, err := dosa.FindEntityByName("../../testentity", "TestEntity")
assert.NoError(t, err)
reg, err := newSimpleRegistrar(scope, namePrefix, table)
assert.NoError(t, err)
provideClient := func(opts GlobalOptions, scope, prefix, path, structName string) (ShellQueryClient, error) {
return newShellQueryClient(reg, mc), nil
}
queryRead := QueryRead{
QueryCmd: &QueryCmd{
QueryOptions: &QueryOptions{
Fields: "StrKey,Int64Key",
},
Scope: scopeFlag("scope"),
NamePrefix: "foo",
Path: "../../testentity",
provideClient: provideClient,
},
}
queryRead.Args.EntityName = "TestEntity"
queryRead.Args.Queries = []string{"StrKey:eq:foo"}
err = queryRead.Execute([]string{})
assert.NoError(t, err)
}
func TestQuery_Range_Happy(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mc := mocks.NewMockConnector(ctrl)
mc.EXPECT().Range(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).
Do(func(_ context.Context, ei *dosa.EntityInfo, columnConditions map[string][]*dosa.Condition, minimumFields []string, token string, limit int) {
assert.NotNil(t, ei)
assert.Len(t, columnConditions, 1)
assert.Len(t, columnConditions["int64key"], 1)
assert.Equal(t, []string{"strkey", "int64key"}, minimumFields)
}).Return([]map[string]dosa.FieldValue{{"key": "value"}}, "", nil)
mc.EXPECT().Shutdown().Return(nil)
table, err := dosa.FindEntityByName("../../testentity", "TestEntity")
assert.NoError(t, err)
reg, err := newSimpleRegistrar(scope, namePrefix, table)
assert.NoError(t, err)
provideClient := func(opts GlobalOptions, scope, prefix, path, structName string) (ShellQueryClient, error) {
return newShellQueryClient(reg, mc), nil
}
queryRange := QueryRange{
QueryCmd: &QueryCmd{
QueryOptions: &QueryOptions{
Fields: "StrKey,Int64Key",
},
Scope: scopeFlag("scope"),
NamePrefix: "foo",
Path: "../../testentity",
provideClient: provideClient,
},
}
queryRange.Args.EntityName = "TestEntity"
queryRange.Args.Queries = []string{"Int64Key:lt:200"}
err = queryRange.Execute([]string{})
assert.NoError(t, err)
}
func TestQuery_NewQueryObj(t *testing.T) {
qo := newQueryObj("StrKey", "eq", "foo")
assert.NotNil(t, qo)
assert.Equal(t, "StrKey", qo.fieldName)
assert.Equal(t, "eq", qo.op)
assert.Equal(t, "foo", qo.valueStr)
}
func TestQuery_ScopeRequired(t *testing.T) {
for _, cmd := range []string{"read", "range"} {
c := StartCapture()
exit = func(r int) {}
os.Args = []string{
"dosa",
"query",
cmd,
"--namePrefix", "foo",
"--path", "../../testentity",
"TestEntity",
"StrKey:eq:foo",
}
main()
assert.Contains(t, c.stop(true), "-s, --scope' was not specified")
}
}
func TestQuery_PrefixRequired(t *testing.T) {
for _, cmd := range []string{"read", "range"} {
c := StartCapture()
exit = func(r int) {}
os.Args = []string{
"dosa",
"query",
cmd,
"--scope", "foo",
"--path", "../../testentity",
"TestEntity",
"StrKey:eq:foo",
}
main()
assert.Contains(t, c.stop(true), "--namePrefix' was not specified")
}
}
func TestQuery_PathRequired(t *testing.T) {
for _, cmd := range []string{"read", "range"} {
c := StartCapture()
exit = func(r int) {}
os.Args = []string{
"dosa",
"query",
cmd,
"--scope", "foo",
"--namePrefix", "foo",
"StrKey:eq:foo",
}
main()
assert.Contains(t, c.stop(true), "--path' was not specified")
}
}
func TestQuery_NoEntityFound(t *testing.T) {
for _, cmd := range []string{"read", "range"} {
c := StartCapture()
exit = func(r int) {}
os.Args = []string{
"dosa",
"query",
cmd,
"--scope", "foo",
"--namePrefix", "foo",
"--path", "../../testentity",
"TestEntity1",
"StrKey:eq:foo",
}
main()
assert.Contains(t, c.stop(true), "no entity named TestEntity1 found")
}
}
| Java |
# MUSCA
a flyweight CA
## Installation
| Java |
<?php
// This file is an extension of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
defined('MOODLE_INTERNAL') || die();
/**
* Plugin details
*
* @package filter
* @subpackage podlille
* @copyright 2014-2016 Gaël Mifsud / SEMM Université Lille1
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later / MIT / Public Domain
*/
$plugin->component = 'filter_podlille1'; // Full name of the plugin (used for diagnostics)
$plugin->version = 2016011101; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2013111800; // Requires this Moodle version
$plugin->release = '1.0.3'; // Human-friendly version name http://docs.moodle.org/dev/Releases
$plugin->maturity = MATURITY_STABLE; // This version's maturity level
| Java |
<?php
$this->load->Model('exam/Exam_manager_model');
$this->load->model('Branch/Course_model');
$exams = $this->Exam_manager_model->exam_details();
$exam_type = $this->Exam_manager_model->get_all_exam_type();
$branch = $this->Course_model->order_by_column('c_name');
?>
<div class="row">
<div class=col-lg-12>
<!-- col-lg-12 start here -->
<div class="panel-default toggle panelMove panelClose panelRefresh"></div>
<div class=panel-body>
<?php echo form_open(base_url() . 'exam/internal_create', array('class' => 'form-horizontal form-groups-bordered validate', 'role' => 'form', 'id' => 'examform', 'target' => '_top')); ?>
<div class="padded">
<div class="form-group">
<label class="col-sm-4 control-label"><?php echo ucwords("Branch"); ?><span style="color:red">*</span></label>
<div class="col-sm-8">
<select class="form-control" name="course" id="course">
<?php foreach ($branch as $course): ?>
<option value="<?php echo $course->course_id; ?>"><?php echo $course->c_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><?php echo ucwords("Semester"); ?><span style="color:red">*</span></label>
<div class="col-sm-8">
<select class="form-control" name="semester" id="semester">
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><?php echo ucwords("Subejct"); ?><span style="color:red">*</span></label>
<div class="col-sm-8">
<select class="form-control" name="subject" id="subject">
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><?php echo ucwords("Title"); ?><span style="color:red">*</span></label>
<div class="col-sm-8">
<input type="text" class="form-control" name="exam_name" id="exam_name"
value="<?php echo set_value('exam_name'); ?>"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label"><?php echo ucwords("Total Marks"); ?><span style="color:red">*</span></label>
<div class="col-sm-8">
<input type="number" class="form-control" name="total_marks" id="total_marks" min="0"
value="<?php echo set_value('total_marks'); ?>"/>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" class="btn btn-info vd_bg-green"><?php echo ucwords("Add"); ?></button>
</div>
</div>
<?php echo form_close(); ?>
</div>
</div>
<!-- End .panel -->
</div>
<!-- col-lg-12 end here -->
</div>
<script>
$(document).ready(function () {
var js_date_format = '<?php echo js_dateformat(); ?>';
var date = '';
var start_date = '';
$('#edit_start_date').datepicker({
format: js_date_format,
startDate: new Date(),
autoclose: true,
todayHighlight: true,
});
$('#edit_start_date').on('change', function () {
date = new Date($(this).val());
start_date = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
console.log(start_date);
setTimeout(function () {
$("#edit_end_date_time").datepicker({
format: js_date_format,
autoclose: true,
startDate: start_date
});
}, 700);
});
})
</script>
<script type="text/javascript">
$.validator.setDefaults({
submitHandler: function (form) {
form.submit();
}
});
$().ready(function () {
$("#examform").validate({
rules: {
course: "required",
semester: "required",
subject:"required",
exam_name:"required",
total_marks: "required"
},
messages: {
course: "Select branch",
semester: "Select semester",
subject:"Select subject",
exam_name:"Enter title",
total_marks: "Enter total marks",
}
});
});
</script>
<script>
$(document).ready(function () {
//course by degree
$('#degree').on('change', function () {
var course_id = $('#course').val();
var degree_id = $(this).val();
//remove all present element
$('#course').find('option').remove().end();
$('#course').append('<option value="">Select</option>');
var degree_id = $(this).val();
$.ajax({
url: '<?php echo base_url(); ?>branch/department_branch/' + degree_id,
type: 'get',
success: function (content) {
var course = jQuery.parseJSON(content);
$.each(course, function (key, value) {
$('#course').append('<option value=' + value.course_id + '>' + value.c_name + '</option>');
})
}
})
batch_from_degree_and_course(degree_id, course_id);
});
//batch from course and degree
$('#course').on('change', function () {
var course_id = $(this).val();
get_semester_from_branch(course_id);
})
//find batch from degree and course
function batch_from_degree_and_course(degree_id, course_id) {
//remove all element from batch
$('#batch').find('option').remove().end();
$.ajax({
url: '<?php echo base_url(); ?>batch/department_branch_batch/' + degree_id + '/' + course_id,
type: 'get',
success: function (content) {
$('#batch').append('<option value="">Select</option>');
var batch = jQuery.parseJSON(content);
console.log(batch);
$.each(batch, function (key, value) {
$('#batch').append('<option value=' + value.b_id + '>' + value.b_name + '</option>');
})
}
})
}
function get_subject_from_branch_semester(course_id,semester_id)
{
$('#subject').find('option').remove().end();
$.ajax({
url: '<?php echo base_url(); ?>subject/subejct_list_branch_sem/' + course_id +'/'+semester_id,
type: 'get',
success: function (content) {
$('#subject').append('<option value="">Select</option>');
var subject = jQuery.parseJSON(content);
$.each(subject, function (key, value) {
$('#subject').append('<option value=' + value.sm_id + '>' + value.subject_name + '</option>');
})
}
})
}
//get semester from brach
function get_semester_from_branch(branch_id) {
$('#semester').find('option').remove().end();
$.ajax({
url: '<?php echo base_url(); ?>semester/semester_branch/' + branch_id,
type: 'get',
success: function (content) {
$('#semester').append('<option value="">Select</option>');
var semester = jQuery.parseJSON(content);
$.each(semester, function (key, value) {
$('#semester').append('<option value=' + value.s_id + '>' + value.s_name + '</option>');
})
}
})
}
$("#semester").change(function(){
var course_id = $("#course").val();
var semester_id = $(this).val();
get_subject_from_branch_semester(course_id,semester_id);
});
})
</script>
<script>
$(document).ready(function () {
$('#total_marks').on('blur', function () {
var total_marks = $(this).val();
$('#passing_marks').attr('max', total_marks);
$('#passing_marks').attr('required', '');
});
$('#passing_marks').on('focus', function () {
var total_marks = $('#total_marks').val();
$(this).attr('max', total_marks);
})
})
</script>
<script>
$(document).ready(function () {
var date = '';
var start_date = '';
$("#date").datepicker({
format: ' MM dd, yyyy',
startDate: new Date(),
todayHighlight: true,
autoclose: true
});
$('#date').on('change', function () {
date = new Date($(this).val());
start_date = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
console.log(start_date);
setTimeout(function () {
$("#end_date_time").datepicker({
format: ' MM dd, yyyy',
todayHighlight: true,
startDate: start_date,
autoclose: true,
});
}, 700);
});
})
</script> | Java |


[](https://github.com/apple/swift-package-manager)
[](https://github.com/Carthage/Carthage)
[](https://opensource.org/licenses/MIT)

Introductory Video: [The Value in Trees (from dotSwift 2017)](http://www.thedotpost.com/2017/01/drew-mccormack-the-value-in-trees)
Impeller is a Distributed Value Store (DVS) written in Swift. It was inspired by successful Distributed Version Control Systems (DVCSes) like Git and Mercurial, and appropriates the concept and terminology for use with application data, rather than source code files.
With Impeller, you compose a data model from Swift value types (`struct`s), and persist them locally in a store like SQlite. Values can be _pushed_ to services like CloudKit, and _pulled_ down to other devices, to facilitate sync across devices, and with web apps.
At this juncture, Impeller is largely experimental. It evolves rapidly, and — much like Swift itself — there is no attempt made to sustain backward compatibility. It is not currently recommended for production projects.
## Introduction
### Objectives
Impeller was inspired by the notion that a persistent store, in the vein of Core Data and Realm, could be based on value types, rather than the usual reference types (classes). Additionally, such a store could be designed from day one to work globally, across devices, much like a DVCS such as Git.
Value types like `struct`s and `enum`s play an important role in Swift development, and have a number of advantages over classes for model data. Because they are generally stored in stack memory, they don't incur the cost of allocation and deallocation associated with heap memory. They also do not have to be garbage collected or reference counted, which adds to the performance benefits.
Perhaps even more important than performance, value types offer greater safety guarantees than mutable reference types like objects. Because each value gets copied when passed into a function or assigned to a variable, each value can be treated in isolation, and the risk of race conditions and other concurrency issues is greatly reduced. The ability of a developer to reason about a value is also greatly enhanced when there is a guarantee it will not be modified via an unrelated scope.
While the initial objective for Impeller is to develop a working value store that syncs, the longer term goal is much more ambitious: Impeller should evolve into an abstraction that can push and pull values from a wide variety of backends (_e.g_ CloudKit, SQL databases), and populate arbitrary frontend modelling frameworks (_e.g._ Core Data, Realm). In effect, middleware that couples any supported client framework with any supported cloud service.
If achieved, this would facilitate much simpler migration between services and frameworks, as well as heterogenous combinations which currently require a large investment of time and effort to realize. For example, imagine an iOS app based on Core Data syncing automatically with Apple's CloudKit, which in turn exchanges data with an Android app utilizing SQlite storage.
### Philosophy
Frameworks like Core Data are mature, and very extensive. To really master such a framework takes years. In return, it gives you an easy way to begin, and takes care of a lot details for you. Caching data, merging conflicts, relationship maintenance, and deletion propagation are all features that help you from day one, and which you can generally forget are operating on your behalf.
But there is a downside to having so much 'magic' in a framework, and you usually encounter that as soon as a project goes beyond the basics. At some point, you realize you don't need the data to be cached, or retain cycles are causing objects to hang around that you would like to be deallocated, or data fetches are scaling badly. The magic that was originally working in your favor is now technical debt, and you start to have to pay it back. You have to learn more and more about how the framework is working internally, often reverse engineering or experimenting to understand private implementation details. The short term gain of not having to know the details demands that you learn those details — and more — in the long term.
This philosophical difference is evident in web frameworks as well. Frameworks like Ruby on Rails took this Core Data approach, making it very easy to step in and get started. But as you came up against performance bottlenecks, you were forced to learn more and more about how the Rails magic was actually working, and — in the long term — this often resulted in even more effort than just doing the hard work upfront.
In contrast, Node.js positions itself at the opposite end of the spectrum. There is as little hidden magic as possible. It is made up of lightweight modules, which you combine to build a web app. You won't get fancy caching unless you explicitly bring in a module to do that for you. In essence, the developer is in charge. Getting started is a little more difficult, but at each step, you understand the technologies you are using, and there is less technical debt as a result.
Our objective with Impeller is that it should fall firmly in the _lightweight_ category with Node.js, contrasting with Core Data and Rails. It should work more like a toolkit that is used to build a modeling layer for your app, rather than a monolithic system. And there should be as little magic as possible. If you need three-way merging for conflict resolution, you can add it, but, in doing so, will be aware of the tradeoffs you are making. If you want in-memory caching, you can add it, and understand the tradeoffs.
## Installation
### Requirements
Impeller is currently only available for iOS. It is a Swift module, requiring Swift 3.
### Carthage
Add Impeller to your _Cartfile_ to have it installed by Carthage.
github "mentalfaculty/impeller" ~> 0.1
Build using `carthage update`, and drag `Impeller.framework` into Xcode.
### Manual
To install Impeller manually
1. Drag the `Impeller.xcodeproj` into your Xcode project.
2. Select your project's _Target_, and open the _General_ tab.
3. Click the + button in the _Embedded Binaries_ section, and choose `Impeller.framework`.
### Examples
Examples of usage are included in the _Examples_ directory. The _Listless_ project is a good place to begin. It is a simple iPhone task management app which syncs via CloudKit.
Other examples of usage can be found in the various _Tests_ folders.
## Usage
### Making a Model
Unlike most data modelling frameworks (_e.g._ Core Data), Impeller is based on value types (`struct`s). There is no modeling tool, or model file; you simply create your own `struct`s.
#### Repositable Protocol
You need to make your `struct`s conform to the `Repositable` protocol.
```Swift
struct Task: Repositable {
```
The `Repositable` protocol looks like this.
```Swift
public protocol Repositable {
var metadata: Metadata { get set }
static var repositedType: RepositedType { get }
init?(readingFrom reader:PropertyReader)
mutating func write(to writer:PropertyWriter)
}
```
#### Metadata
Your new type must supply a property for metadata storage.
```Swift
struct Task: Repositable {
var metadata = Metadata()
```
The `metadata` property is used internally by the framework, and you should generally refrain from modifying it.
One exception to this rule is the `uniqueIdentifier`, which is a global identifier for your value, and is used to store it and fetch it from repositories (persistent stores and cloud storage). By default, a _UUID_ will be generated for new values, but you can override this and set metadata with a carefully chosen `uniqueIdentifier`. You might do this in order to make shared values that appear on all devices, such as with a global settings struct. Setting a custom `uniqueIdentifer` is analogous to creating a singleton in your app.
#### Properties
The properties of your `struct` can be anything supported by Swift. Properties are not persisted to a repository by default, so you can also include properties that you don't wish to have stored.
```Swift
struct Task: Repositable {
...
var text = ""
var tagList = TagList()
var isComplete = false
```
#### Loading Data
You save and load data with Impeller in much the same way you do when using the `NSCoding` protocol included in the `Foundation` framework. You need to implement
1. An initializer which creates a new struct value from data that is loaded from a repository.
2. A function to write the `struct` data into a repository for saving.
The initializer might look like this
```Swift
init?(readingFrom reader:PropertyReader) {
text = reader.read("text")!
tagList = reader.read("tagList")!
isComplete = reader.read("isComplete")!
}
```
The keys passed in are conventionally named the same as your properties, but this is not a necessity. You might find it useful to create an `enum` with `String` raw values to define these keys, rather than using literal values.
#### Which Data Types are Supported?
The `PropertyReader` protocol provides methods to read a variety of data types, including
- Built-in types like `Int`, `Float`, `String`, and `Data`, which are called _primitive types_
- Optional variants of primitive types (_e.g._ `Int?`)
- Arrays of simple built-in types (_e.g._ `[Float]`)
- Other `Repositable` types (_e.g._ `TagList`, where `TagList` is a `struct` conforming to `Repositable`)
- Optional variants of `Repositable` types (_e.g._ `TagList?`)
- Arrays of `Repositable` types (_e.g._ `[TagList]`)
These types are the only ones supported by repositories, but this does not mean your `struct`s cannot include other types. You simply convert to and from these primitive types when storing and loading data, just as you do when using `NSCoding`. For example, if a `struct` includes a `Set`, you would simply convert the `Set` to an `Array` for storage. (It would be wise to sort the `Array`, to prevent unnecessary updates to the repository when the set is unchanged.)
#### Storing Data
The function for storing data into a repository makes use of methods in the `PropertyWriter`.
```Swift
mutating func write(to writer:PropertyWriter) {
writer.write(text, for: "text")
writer.write(&tagList, for: "tagList")
writer.write(isComplete, for: "isComplete")
}
```
This is the inverse of loading data, so the keys used must correspond to the keys used in the initializer above.
### Repositories
Places where data gets stored are referred to as _repositories_, in keeping with the terminology of DVCSes. This also emphasizes the distributed nature of the framework, with repositories spread across devices, and in the cloud.
#### Creating a Repository
Each repository type has a different setup. Typically, you simply initialize the repository, and store it in an instance variable on a controller object.
```Swift
let localRepository = MonolithicRepository()
```
#### Storing Changes
There is no central managing object in Impeller, like the `NSManagedObjectContext` of Core Data. Instead, when you want to save a `Repositable` type, you simply ask the repository to commit it.
```Swift
localRepository.commit(&task)
```
This commits the whole value, which includes any sub-types in the value tree which descend from `task`.
Note that the `commit` function takes an `inout` parameter, meaning you must pass in a variable, not a constant. The reason for this is that when storing into a repository, the metadata of the stored types (_e.g._ timestamps) get updated to mirror the latest state in the repository. In addition, the value passed in may be merged with data in the store, and thus updated by the commit.
### Exchanges
You can use Impeller as a local store, but most modern apps need to sync data across devices, or with the cloud. You can couple two or more repositories using an _Exchange_.
#### Creating an Exchange
Like the repositories, you usually create an _Exchange_ just after your app launches, and you have created all repositories. You could also do it using a lazy property, like this
```Swift
lazy var exchange: Exchange = {
Exchange(coupling: [self.localRepository, self.cloudRepository], pathForSavedState: nil)
}()
```
#### Exchanging Data
To trigger an exchange of the recent changes between repositories, simply call the `exchange` function.
```Swift
exchange.exchange { error in
if let error = error {
print("Error during exchange: \(error)")
}
else {
// Refresh UI here
}
}
```
The `exchange` function is asynchronous, with a completion callback, because it typically involves 'slow' network requests.
### Merging
When committing changes to a repository, it is possible that the repository value has been changed by another commit or exchange since the value was originally fetched. It is important to detect this eventuality, so that changes are not overwritten by the stale values in memory. There are plans to offer powerful merging in future, but at the moment only very primitive support is available.
You can implement
```Swift
func resolvedValue(forConflictWith newValue:Repositable, context: Any?) -> Self
```
from the `Repositable` protocol in your `struct`. By default, this function will do a generic merge, favoring the values in `self`, thus giving the values currently in memory precedence. You can override that behavior to return a different `struct` value, which will be what gets stored in the repository (...and returned from the `commit` function).
### Gotchas
A value store is quite a different beast to a store based on reference types (_e.g._ Core Data). Some aspects become more straightforward when using values (_e.g._ passing values between threads), but other behaviors may surprise you at first. This section covers a few of the more major differences.
#### Advantages of Value Types
In addition to the unexpected behaviors that come with using value types, there are a number of welcome surprises. Here are a few of the advantages of using a value store:
- Value types are often stored on the stack, and don't incur the cost of heap allocation and deallocation.
- There is no need for reference counting or garbage collection, making creation and cleanup much faster.
- Value types are copied when assigned or passed to a function, making data contention much less likely.
- Value types can be passed between threads with little risk, because each thread gets a separate copy.
- There is no need to define complex deletion rules. Deletion is handled naturally by the ownership hierarchy of the `struct`s.
- Keeping a history of changes is as simple as keeping an array of root values. This is very useful for features such as undo.
#### Uniquing
Uniquing is a feature of class-based frameworks like Core Data. It ensures that when you fetch from a store, you do not end up with two objects representing the same stored entity. The framework checks first if an object already exists in memory for the data in question, and returns that whenever you attempt to fetch that data entity again.
In a value store, uniquing would make no sense, because every value gets copied numerous times. Creating a copy is as simple as assigning to a variable, or passing it to a function.
At first, this may seem problematic to a seasoned Core Data developer, but it just requires a minor shift in expectations. When working with Impeller, you have to recognize that the copy of the value you are working with is not unique, that there may be other values representing the same stored entity, and that they may all be in different states. A value is temporal, and only influences other values when it is committed to a repository.
#### Relationship Cycles
When you develop a data model from `struct`s, you form _value trees_. A `struct` can contain other `struct`s, and the entirety forms a tree in memory.
Frameworks like Core Data are based around related entities, which can create arbitrary graphs. This is flexible, but has some downsides. For example, Core Data models form retain cycles which lead to memory leaks unless active steps are taken to break them (_e.g._ resetting the context).
As mentioned early, `struct`s are stack types, and do not have any issues with retain cycles. They are cleaned up automatically when exiting a scope. The price paid for this is that Impeller cannot be used to directly model arbitrary graphs of data.
With Impeller, you build your model out of one or more value trees, but if you need relationships between trees, you can mimic them using so-called _weak relationships_. A weak relationship simply involves storing the `uniqueIdentifier` of another object in a property. When you need to use the related object, you just fetch it from the store.
While it is not possible to create cyclic graphs of related values, you can use weak relationships to achieve very similar behavior. In this respect, using Impeller need not be so different to other frameworks, and the relationship cycles — where they exist — should be much more evident.
#### Copying Sub-Values
Repositable `struct`s can contain other repositable values, forming a tree, but there is nothing to stop you from copying a sub-value into a different variable. For example
```Swift
struct Child: Repositable {
...
}
struct Person: Repositable {
...
var child: Child
}
var dave = Person()
var child = dave.child
child.name = "Tom"
repository.commit(&child)
```
In this code, the `Child` of the value `dave` gets copied into a separate variable, altered, and then committed. It is important to realize that — as far as the repository is concerned — this is the same as changing the `child` property of `dave` directly and committing that. The two copies of the `Child` have the same `uniqueIdentifier`, and represent the same data in the repository.
If the intention was to make a new, independent child, it would be necessary to reset the metadata, like this
```Swift
var dave = Person()
var child = dave.child
child.metadata = Metadata()
child.name = "Tom"
repository.commit(&child)
```
This code would create a whole new `Child` value in the repository, which would be unrelated to the original `Person`.
#### Trees with Variable Depth
In theory you can create trees of variable depth using `struct`s and `protocol`s. For example, it would be possible to create an `AnyRepositable` `struct` that forwards all function calls to a wrapped value of a concrete `Repositable` type.
At this point, it is unclear if Impeller can be made to work with such types. It is an area of investigation.
## Progress
### State of the Union
The project is still in a very early stage, and not much more than a concept prototype. The following features are in place:
- In-memory repository
- CloudKit repository
- Exchange
- Single timestamp for each `Repositable` value. Used in exchanging.
### Imminent Projects
There are many plans for improving on this. Here are some of the projects that have a high priority. If you would like to contribute, fork the project, and issue pull requests, or get involved in issue discussion.
- Atomic persistence of in-memory repository (_e.g._ JSON, Property List)
- SQLite repository
- Timestamps for individual properties, for more granular merging
- Option to use three-way merging, with originally fetched value, newly fetched value, and in-memory value
- Decoupling of Impeller `Repositable` types, and the underlying value trees, to facilitate other front-ends (_e.g._ Core Data)
| Java |
<?php
namespace Augwa\QuickBooks\Model;
/**
* Master Account is the list of accounts in the master list. The master
* list is the complete list of accounts prescribed by the French
* Government. These accounts can be created in the company on a need
* basis. The account create API needs to be used to create an account.
*
* Class MasterAccountModel
* @package Augwa\QuickBooks\Model
*/
class MasterAccountModel
extends AccountModel
{
/**
* @var bool
*/
private $AccountExistsInCompany;
/**
* Product: ALL
* Specifies whether the account has been created in the company.
*
* @return bool
*/
public function getAccountExistsInCompany()
{
return $this->AccountExistsInCompany;
}
/**
* Product: ALL
* Specifies whether the account has been created in the company.
*
* @param bool $AccountExistsInCompany
*
* @return MasterAccountModel
*/
public function setAccountExistsInCompany(
$AccountExistsInCompany
)
{
$this->AccountExistsInCompany = $AccountExistsInCompany;
return $this;
}
} | Java |
/**
* Entry point for CSS.
*/
.foo {
color: black;
}
| Java |
require 'spec_helper'
module Gisele
module Compiling
describe Gisele2Gts, "on_task_def" do
before do
subject
subject.ith_state(0).initial!
end
subject do
code = <<-GIS.strip
task Main
Hello
end
GIS
Gisele2Gts.compile(code, :root => :task_def)
end
let :expected do
Gts.new do
add_state :kind =>:event, :initial => true
add_state :kind => :fork
add_state :kind => :event
add_state :kind => :listen, :accepting => true
add_state :kind => :event
add_state :kind => :end, :accepting => true
add_state :kind => :join, :accepting => true
add_state :kind => :event
add_state :kind => :end, :accepting => true
connect 0, 1, :symbol => :start, :event_args => [ "Main" ]
connect 1, 2, :symbol => :"(forked)"
connect 2, 3, :symbol => :start, :event_args => [ "Hello" ]
connect 3, 4, :symbol => :ended
connect 4, 5, :symbol => :end, :event_args => [ "Hello" ]
connect 5, 6, :symbol => :"(notify)"
connect 1, 6, :symbol => :"(wait)"
connect 6, 7, :symbol => nil
connect 7, 8, :symbol => :end, :event_args => [ "Main" ]
end
end
it 'generates an equivalent transition system' do
subject.bytecode_equivalent!(expected).should be_true
end
end
end
end
| Java |
// This file is automatically generated.
package adila.db;
/*
* Motorola Cliq-XT
*
* DEVICE: zeppelin
* MODEL: MB501
*/
final class zeppelin_mb501 {
public static final String DATA = "Motorola|Cliq-XT|";
}
| Java |
#include "transactiondesc.h"
#include "guiutil.h"
#include "lusocoinunits.h"
#include "main.h"
#include "wallet.h"
#include "db.h"
#include "ui_interface.h"
#include "base58.h"
#include <string>
QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
if (!wtx.IsFinal())
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
return tr("Open for %n more block(s)", "", wtx.nLockTime - nBestHeight + 1);
else
return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
}
else
{
int nDepth = wtx.GetDepthInMainChain();
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
return tr("%1/offline").arg(nDepth);
else if (nDepth < 6)
return tr("%1/unconfirmed").arg(nDepth);
else
return tr("%1 confirmations").arg(nDepth);
}
}
QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx)
{
QString strHTML;
{
LOCK(wallet->cs_wallet);
strHTML.reserve(4000);
strHTML += "<html><font face='verdana, arial, helvetica, sans-serif'>";
int64 nTime = wtx.GetTxTime();
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
strHTML += "<b>" + tr("Status") + ":</b> " + FormatTxStatus(wtx);
int nRequests = wtx.GetRequestCount();
if (nRequests != -1)
{
if (nRequests == 0)
strHTML += tr(", has not been successfully broadcast yet");
else if (nRequests > 0)
strHTML += tr(", broadcast through %n node(s)", "", nRequests);
}
strHTML += "<br>";
strHTML += "<b>" + tr("Date") + ":</b> " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "<br>";
//
// From
//
if (wtx.IsCoinBase())
{
strHTML += "<b>" + tr("Source") + ":</b> " + tr("Generated") + "<br>";
}
else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
{
// Online transaction
strHTML += "<b>" + tr("From") + ":</b> " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "<br>";
}
else
{
// Offline transaction
if (nNet > 0)
{
// Credit
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (wallet->IsMine(txout))
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
{
if (wallet->mapAddressBook.count(address))
{
strHTML += "<b>" + tr("From") + ":</b> " + tr("unknown") + "<br>";
strHTML += "<b>" + tr("To") + ":</b> ";
strHTML += GUIUtil::HtmlEscape(CLusocoinAddress(address).ToString());
if (!wallet->mapAddressBook[address].empty())
strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
else
strHTML += " (" + tr("own address") + ")";
strHTML += "<br>";
}
}
break;
}
}
}
}
//
// To
//
if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
{
// Online transaction
std::string strAddress = wtx.mapValue["to"];
strHTML += "<b>" + tr("To") + ":</b> ";
CTxDestination dest = CLusocoinAddress(strAddress).Get();
if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " ";
strHTML += GUIUtil::HtmlEscape(strAddress) + "<br>";
}
//
// Amount
//
if (wtx.IsCoinBase() && nCredit == 0)
{
//
// Coinbase
//
int64 nUnmatured = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
nUnmatured += wallet->GetCredit(txout);
strHTML += "<b>" + tr("Credit") + ":</b> ";
if (wtx.IsInMainChain())
strHTML += LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
else
strHTML += "(" + tr("not accepted") + ")";
strHTML += "<br>";
}
else if (nNet > 0)
{
//
// Credit
//
strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nNet) + "<br>";
}
else
{
bool fAllFromMe = true;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
fAllFromMe = fAllFromMe && wallet->IsMine(txin);
bool fAllToMe = true;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
fAllToMe = fAllToMe && wallet->IsMine(txout);
if (fAllFromMe)
{
//
// Debit
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (wallet->IsMine(txout))
continue;
if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
{
// Offline transaction
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
strHTML += "<b>" + tr("To") + ":</b> ";
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
strHTML += GUIUtil::HtmlEscape(CLusocoinAddress(address).ToString());
strHTML += "<br>";
}
}
strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -txout.nValue) + "<br>";
}
if (fAllToMe)
{
// Payment to self
int64 nChange = wtx.GetChange();
int64 nValue = nCredit - nChange;
strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -nValue) + "<br>";
strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nValue) + "<br>";
}
int64 nTxFee = nDebit - wtx.GetValueOut();
if (nTxFee > 0)
strHTML += "<b>" + tr("Transaction fee") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -nTxFee) + "<br>";
}
else
{
//
// Mixed debit transaction
//
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if (wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -wallet->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, wallet->GetCredit(txout)) + "<br>";
}
}
strHTML += "<b>" + tr("Net amount") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, nNet, true) + "<br>";
//
// Message
//
if (wtx.mapValue.count("message") && !wtx.mapValue["message"].empty())
strHTML += "<br><b>" + tr("Message") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "<br>";
if (wtx.mapValue.count("comment") && !wtx.mapValue["comment"].empty())
strHTML += "<br><b>" + tr("Comment") + ":</b><br>" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "<br>";
strHTML += "<b>" + tr("Transaction ID") + ":</b> " + wtx.GetHash().ToString().c_str() + "<br>";
if (wtx.IsCoinBase())
strHTML += "<br>" + tr("Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "<br>";
//
// Debug view
//
if (fDebug)
{
strHTML += "<hr><br>" + tr("Debug information") + "<br><br>";
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
if(wallet->IsMine(txin))
strHTML += "<b>" + tr("Debit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, -wallet->GetDebit(txin)) + "<br>";
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if(wallet->IsMine(txout))
strHTML += "<b>" + tr("Credit") + ":</b> " + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, wallet->GetCredit(txout)) + "<br>";
strHTML += "<br><b>" + tr("Transaction") + ":</b><br>";
strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);
strHTML += "<br><b>" + tr("Inputs") + ":</b>";
strHTML += "<ul>";
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
COutPoint prevout = txin.prevout;
CCoins prev;
if(pcoinsTip->GetCoins(prevout.hash, prev))
{
if (prevout.n < prev.vout.size())
{
strHTML += "<li>";
const CTxOut &vout = prev.vout[prevout.n];
CTxDestination address;
if (ExtractDestination(vout.scriptPubKey, address))
{
if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
strHTML += QString::fromStdString(CLusocoinAddress(address).ToString());
}
strHTML = strHTML + " " + tr("Amount") + "=" + LusocoinUnits::formatWithUnit(LusocoinUnits::LUC, vout.nValue);
strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) ? tr("true") : tr("false")) + "</li>";
}
}
}
}
strHTML += "</ul>";
}
strHTML += "</font></html>";
}
return strHTML;
}
| Java |
LIBEVENT_VERSION="2.1.11-stable"
LIBEVENT_SHA256SUM="a65bac6202ea8c5609fd5c7e480e6d25de467ea1917c08290c521752f147283d"
rm -fR libevent*
getpkg https://github.com/libevent/libevent/releases/download/release-${LIBEVENT_VERSION}/libevent-${LIBEVENT_VERSION}.tar.gz $LIBEVENT_SHA256SUM
tar zxvf libevent-${LIBEVENT_VERSION}.tar.gz
cd libevent-${LIBEVENT_VERSION}
./configure --prefix=$VENV
$PMAKE
make install
| Java |
<?php
/**
* Orinoco Framework - A lightweight PHP framework.
*
* Copyright (c) 2008-2015 Ryan Yonzon, http://www.ryanyonzon.com/
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
namespace Orinoco\Framework;
use RuntimeException;
class View
{
// layout name
public $layout;
// Orinoco\Framework\Http class
private $http;
// Orinoco\Framework\Route class
private $route;
// Passed controller's variables (to be used by view template)
private $variables;
// explicit view page
private $page_view;
/**
* Constructor
*
* @param Http object $http
* @param Route object $route
* @return void
*/
public function __construct(Http $http, Route $route)
{
$this->http = $http;
$this->route = $route;
}
/**
* Getter method
*
* @param Variable name $var_name
* @return Variable value
*/
public function __get($var_name)
{
if (isset($this->variables[$var_name])) {
return $this->variables[$var_name];
}
return false;
}
/**
* Set HTML layout
*
* @param Layout name
* @return void
*/
public function setLayout($layout_name)
{
$this->layout = $layout_name;
}
/**
* Set page/view template to use
*
* @param Page/view name Array or String
* @return void
*/
public function setPage($page_view)
{
// initialize default page view/template
$page = array(
'controller' => $this->route->getController(),
'action' => $this->route->getAction()
);
// check if passed parameter is an array
if (is_array($page_view)) {
if (isset($page_view['controller'])) {
$page['controller'] = $page_view['controller'];
}
if (isset($page_view['action'])) {
$page['action'] = $page_view['action'];
}
// string
} else if (is_string($page_view)) {
$exploded = explode('#', $page_view); // use '#' as separator (we can also use '/')
if (count($exploded) > 1) {
if (isset($exploded[0])) {
$page['controller'] = $exploded[0];
}
if (isset($exploded[1])) {
$page['action'] = $exploded[1];
}
} else {
$page['action'] = $page_view;
}
}
$this->page_view = (object) $page;
}
/**
* Render view template/page (including layout)
*
* @param $page_view Explicit page view/template file
* @param $obj_vars Variables to be passed to the layout and page template
* @return void
*/
public function render($page_view = null, $obj_vars = array())
{
if (isset($page_view)) {
$this->setPage($page_view);
}
// store variables (to be passed to the layout and page template)
// accessible via '__get' method
$this->variables = $obj_vars;
// check if layout is defined
if(isset($this->layout)) {
$layout_file = APPLICATION_LAYOUT_DIR . str_replace(PHP_FILE_EXTENSION, '', $this->layout) . PHP_FILE_EXTENSION;
if (!file_exists($layout_file)) {
$this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500);
if (DEVELOPMENT) {
throw new RuntimeException('It seems that "' . str_replace(ROOT_DIR, '', $layout_file) . '" does not exists.');
} else {
$this->renderErrorPage(500);
}
} else {
require $layout_file;
}
} else {
$default_layout = $this->getDefaultLayout();
if (file_exists($default_layout)) {
require $default_layout;
} else {
$this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500);
if (DEVELOPMENT) {
throw new RuntimeException('It seems that "' . str_replace(ROOT_DIR, '', $default_layout) . '" does not exists.');
} else {
$this->renderErrorPage(500);
}
}
}
}
/**
* Render error page
*
* @param Error code (e.g. 404, 500, etc)
* @return void
*/
public function renderErrorPage($error_code = null)
{
if (defined('ERROR_' . $error_code . '_PAGE')) {
$error_page = constant('ERROR_' . $error_code . '_PAGE');
$error_page_file = APPLICATION_ERROR_PAGE_DIR . str_replace(PHP_FILE_EXTENSION, '', $error_page) . PHP_FILE_EXTENSION;
if (file_exists($error_page_file)) {
require $error_page_file;
} else {
// error page not found? show this error message
$this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500);
$this->setContent('500 - Internal Server Error (Unable to render ' . $error_code . ' error page)');
}
} else {
// error page not found? show this error message
$this->http->setHeader($this->http->getValue('SERVER_PROTOCOL') . ' 500 Internal Server Error', true, 500);
$this->setContent('500 - Internal Server Error (Unable to render ' . $error_code . ' error page)');
}
}
/**
* Get action (presentation) content
*
* @return bool; whether or not content file exists
*/
public function getContent()
{
// check if page view is specified or not
if (!isset($this->page_view)) {
$content_view = APPLICATION_PAGE_DIR . $this->route->getController() . '/' . $this->route->getAction() . PHP_FILE_EXTENSION;
} else {
$content_view = APPLICATION_PAGE_DIR . $this->page_view->controller . '/' . $this->page_view->action . PHP_FILE_EXTENSION;
}
/**
* @todo Should we render an error page, saying something like "the page template aren't found"?
*/
if(!file_exists($content_view)) {
// No verbose
return false;
}
require $content_view;
}
/**
* Get partial (presentation) content
*
* @param String Partial name/path $partial_name
* @return bool; whether or not partial file exists
*/
public function getPartial($partial_name)
{
$partial_view = APPLICATION_PARTIAL_DIR . $partial_name . PHP_FILE_EXTENSION;
if(!file_exists($partial_view)) {
// No verbose
return false;
}
require $partial_view;
}
/**
* Clear output buffer content
*
* @return void
*/
public function clearContent()
{
ob_clean();
}
/**
* Print out passed content
*
* @return void
*/
public function setContent($content = null)
{
print($content);
}
/**
* Flush output buffer content
*
* @return void
*/
public function flush()
{
ob_flush();
}
/**
* Return the default layout path
*
* @return string
*/
private function getDefaultLayout()
{
return APPLICATION_LAYOUT_DIR . DEFAULT_LAYOUT . PHP_FILE_EXTENSION;
}
/**
* Construct JSON string (and also set HTTP header as 'application/json')
*
* @param $data Array
* @return void
*/
public function renderJSON($data = array())
{
$json = json_encode($data);
$this->http->setHeader(array(
'Content-Length' => strlen($json),
'Content-type' => 'application/json;'
));
$this->setContent($json);
}
/**
* Redirect using header
*
* @param string|array $mixed
* @param Use 'refresh' instead of 'location' $use_refresh
* @param Time to refresh $refresh_time
* @return void
*/
public function redirect($mixed, $use_refresh = false, $refresh_time = 3)
{
$url = null;
if (is_string($mixed)) {
$url = trim($mixed);
} else if (is_array($mixed)) {
$controller = $this->route->getController();
$action = null;
if (isset($mixed['controller'])) {
$controller = trim($mixed['controller']);
}
$url = '/' . $controller;
if (isset($mixed['action'])) {
$action = trim($mixed['action']);
}
if (isset($action)) {
$url .= '/' . $action;
}
if (isset($mixed['query'])) {
$query = '?';
foreach ($mixed['query'] as $k => $v) {
$query .= $k . '=' . urlencode($v) . '&';
}
$query[strlen($query) - 1] = '';
$query = trim($query);
$url .= $query;
}
}
if (!$use_refresh) {
$this->http->setHeader('Location: ' . $url);
} else {
$this->http->setHeader('refresh:' . $refresh_time . ';url=' . $url);
}
// exit normally
exit(0);
}
}
| Java |
/* ==========================================================================
Table of Contents
========================================================================== */
/*
0. Normalize
1. Icons
2. General
3. Utilities
4. General
5. Single Post
6. Tag Archive
7. Third Party Elements
8. Pagination
9. Footer
10. Media Queries (Tablet)
11. Media Queries (Mobile)
12. Animations
*/
/* ==========================================================================
0. Normalize.css v2.1.3 | MIT License | git.io/normalize | (minified)
========================================================================== */
article, aside, details,
figcaption, figure,
footer, header, hgroup,
main, nav, section,
summary { display: block; }
audio, canvas, video { display: inline-block; }
audio:not([controls]) { display: none; height: 0; }
[hidden], template { display: none; }
html {
font-family: sans-serif;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
body { margin: 0; }
a { background: transparent; }
a:focus { outline: thin dotted; }
a:active, a:hover { outline: 0; }
h1 { font-size: 2em; margin: 0.67em 0; }
abbr[title] { border-bottom: 1px dotted; }
b, strong { font-weight: 700; }
dfn { font-style: italic; }
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
mark { background: #FF0; color: #000; }
code, kbd, pre,
samp { font-family: monospace, serif; font-size: 1em; }
pre { white-space: pre-wrap; }
q { quotes: "\201C" "\201D" "\2018" "\2019"; }
small { font-size: 80%; }
sub, sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup { top: -0.5em; }
sub { bottom: -0.25em; }
img { border: 0; }
svg:not(:root) { overflow: hidden; }
figure { margin: 0; }
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
legend { border: 0; padding: 0; }
button, input, select,
textarea { font-family: inherit; font-size: 100%; margin: 0; }
button, input { line-height: normal; }
button, select { text-transform: none; }
button, html input[type="button"],
input[type="reset"], input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled], html input[disabled] { cursor: default; }
input[type="checkbox"],
input[type="radio"] { box-sizing: border-box; padding: 0; }
input[type="search"] {
-webkit-appearance: textfield;
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration { -webkit-appearance: none; }
button::-moz-focus-inner,
input::-moz-focus-inner { border: 0; padding: 0; }
textarea { overflow: auto; vertical-align: top; }
table { border-collapse: collapse; border-spacing: 0; }
/* ==========================================================================
1. Icons - Sets up the icon font and respective classes
========================================================================== */
/* Import the font file with the icons in it */
@font-face {
font-family: "casper-icons";
src:url("../fonts/casper-icons.eot");
src:url("../fonts/casper-icons.eot?#iefix") format("embedded-opentype"),
url("../fonts/casper-icons.woff") format("woff"),
url("../fonts/casper-icons.ttf") format("truetype"),
url("../fonts/casper-icons.svg#icons") format("svg");
font-weight: normal;
font-style: normal;
}
/* Apply these base styles to all icons */
[class^="icon-"]:before, [class*=" icon-"]:before {
font-family: "casper-icons", "Open Sans", sans-serif;
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
text-decoration: none !important;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Each icon is created by inserting the correct character into the
content of the :before pseudo element. Like a boss. */
.icon-ghost:before {
content: "\f600";
}
.icon-feed:before {
content: "\f601";
}
.icon-twitter:before {
content: "\f602";
font-size: 1.1em;
}
.icon-google-plus:before {
content: "\f603";
}
.icon-facebook:before {
content: "\f604";
}
.icon-arrow-left:before {
content: "\f605";
}
.icon-stats:before {
content: "\f606";
}
.icon-location:before {
content: "\f607";
margin-left: -3px; /* Tracking fix */
}
.icon-link:before {
content: "\f608";
}
/* ==========================================================================
2. General - Setting up some base styles
========================================================================== */
html {
height: 100%;
max-height: 100%;
font-size: 62.5%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
height: 100%;
max-height: 100%;
font-family: "Merriweather", serif;
letter-spacing: 0.01rem;
font-size: 1.8rem;
line-height: 1.75em;
color: #3A4145;
-webkit-font-feature-settings: 'kern' 1;
-moz-font-feature-settings: 'kern' 1;
-o-font-feature-settings: 'kern' 1;
}
::-moz-selection {
background: #D6EDFF;
}
::selection {
background: #D6EDFF;
}
h1, h2, h3,
h4, h5, h6 {
-webkit-font-feature-settings: 'dlig' 1, 'liga' 1, 'lnum' 1, 'kern' 1;
-moz-font-feature-settings: 'dlig' 1, 'liga' 1, 'lnum' 1, 'kern' 1;
-o-font-feature-settings: 'dlig' 1, 'liga' 1, 'lnum' 1, 'kern' 1;
color: #2E2E2E;
line-height: 1.15em;
margin: 0 0 0.4em 0;
font-family: "Open Sans", sans-serif;
}
h1 {
font-size: 5rem;
letter-spacing: -2px;
text-indent: -3px;
}
h2 {
font-size: 3.6rem;
letter-spacing: -1px;
}
h3 {
font-size: 3rem;
}
h4 {
font-size: 2.5rem;
}
h5 {
font-size: 2rem;
}
h6 {
font-size: 2rem;
}
a {
color: #4A4A4A;
transition: color ease 0.3s;
}
a:hover {
color: #111;
}
p, ul, ol, dl {
-webkit-font-feature-settings: 'liga' 1, 'onum' 1, 'kern' 1;
-moz-font-feature-settings: 'liga' 1, 'onum' 1, 'kern' 1;
-o-font-feature-settings: 'liga' 1, 'onum' 1, 'kern' 1;
margin: 0 0 1.75em 0;
}
ol, ul {
padding-left: 3rem;
}
ol ol, ul ul,
ul ol, ol ul {
margin: 0 0 0.4em 0;
padding-left: 2em;
}
dl dt {
float: left;
width: 180px;
overflow: hidden;
clear: left;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 700;
margin-bottom: 1em;
}
dl dd {
margin-left: 200px;
margin-bottom: 1em
}
li {
margin: 0.4em 0;
}
li li {
margin: 0;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: #EFEFEF 1px solid;
margin: 3.2em 0;
padding: 0;
}
blockquote {
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 1.75em 0 1.75em -2.2em;
padding: 0 0 0 1.75em;
border-left: #4A4A4A 0.4em solid;
}
blockquote p {
margin: 0.8em 0;
font-style: italic;
}
blockquote small {
display: inline-block;
margin: 0.8em 0 0.8em 1.5em;
font-size: 0.9em;
color: #CCC;
}
blockquote small:before { content: "\2014 \00A0"; }
blockquote cite {
font-weight: 700;
}
blockquote cite a { font-weight: normal; }
mark {
background-color: #FFC336;
}
code, tt {
padding: 1px 3px;
font-family: Inconsolata, monospace, sans-serif;
font-size: 0.85em;
white-space: pre-wrap;
border: #E3EDF3 1px solid;
background: #F7FAFB;
border-radius: 2px;
}
pre {
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 0 0 1.75em 0;
border: #E3EDF3 1px solid;
width: 100%;
padding: 10px;
font-family: Inconsolata, monospace, sans-serif;
font-size: 0.9em;
white-space: pre;
overflow: auto;
background: #F7FAFB;
border-radius: 3px;
}
pre code, tt {
font-size: inherit;
white-space: -moz-pre-wrap;
white-space: pre-wrap;
background: transparent;
border: none;
padding: 0;
}
kbd {
display: inline-block;
margin-bottom: 0.4em;
padding: 1px 8px;
border: #CCC 1px solid;
color: #666;
text-shadow: #FFF 0 1px 0;
font-size: 0.9em;
font-weight: 700;
background: #F4F4F4;
border-radius: 4px;
box-shadow:
0 1px 0 rgba(0, 0, 0, 0.2),
0 1px 0 0 #fff inset;
}
table {
-moz-box-sizing: border-box;
box-sizing: border-box;
margin: 1.75em 0;
width: 100%;
max-width: 100%;
background-color: transparent;
}
table th,
table td {
padding: 8px;
line-height: 20px;
text-align: left;
vertical-align: top;
border-top: #EFEFEF 1px solid;
}
table th { color: #000; }
table caption + thead tr:first-child th,
table caption + thead tr:first-child td,
table colgroup + thead tr:first-child th,
table colgroup + thead tr:first-child td,
table thead:first-child tr:first-child th,
table thead:first-child tr:first-child td {
border-top: 0;
}
table tbody + tbody { border-top: #EFEFEF 2px solid; }
table table table { background-color: #FFF; }
table tbody > tr:nth-child(odd) > td,
table tbody > tr:nth-child(odd) > th {
background-color: #F6F6F6;
}
table.plain tbody > tr:nth-child(odd) > td,
table.plain tbody > tr:nth-child(odd) > th {
background: transparent;
}
iframe, .fluid-width-video-wrapper {
display: block;
margin: 1.75em 0;
}
/* When a video is inside the fitvids wrapper, drop the
margin on the iframe, cause it breaks stuff. */
.fluid-width-video-wrapper iframe {
margin: 0;
}
/* ==========================================================================
3. Utilities - These things get used a lot
========================================================================== */
/* Clears shit */
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after { clear: both; }
.clearfix { *zoom: 1; }
/* Hides shit */
.hidden {
text-indent: -9999px;
visibility: hidden;
display: none;
}
/* Creates a responsive wrapper that makes our content scale nicely */
.inner {
position: relative;
width: 80%;
max-width: 710px;
margin: 0 auto;
}
/* Centres vertically yo. (IE8+) */
.vertical {
display: table-cell;
vertical-align: middle;
}
/* ==========================================================================
4. General - The main styles for the the theme
========================================================================== */
/* Big cover image on the home page */
.main-header {
position: relative;
display: table;
width: 100%;
height: 100%;
margin-bottom: 5rem;
text-align: center;
background: #222 no-repeat center center;
background-size: cover;
overflow: hidden;
}
.main-header .inner {
width: 80%;
}
.main-nav {
position: relative;
padding: 35px 40px;
margin: 0 0 30px 0;
}
.main-nav a {
text-decoration: none;
font-family: 'Open Sans', sans-serif;
}
/* Create a bouncing scroll-down arrow on homepage with cover image */
.scroll-down {
display: block;
position: absolute;
z-index: 100;
bottom: 45px;
left: 50%;
margin-left: -16px;
width: 34px;
height: 34px;
font-size: 34px;
text-align: center;
text-decoration: none;
color: rgba(255,255,255,0.7);
-webkit-transform: rotate(-90deg);
transform: rotate(-90deg);
-webkit-animation: bounce 4s 2s infinite;
animation: bounce 4s 2s infinite;
}
/* Stop it bouncing and increase contrast when hovered */
.scroll-down:hover {
color: #fff;
-webkit-animation: none;
animation: none;
}
/* Put a semi-opaque radial gradient behind the icon to make it more visible
on photos which happen to have a light background. */
.home-template .main-header:after {
display: block;
content: " ";
width: 150px;
height: 130px;
border-radius: 100%;
position: absolute;
bottom: 0;
left: 50%;
margin-left: -75px;
background: -moz-radial-gradient(center, ellipse cover, rgba(0,0,0,0.15) 0%, rgba(0,0,0,0) 70%, rgba(0,0,0,0) 100%);
background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,rgba(0,0,0,0.15)), color-stop(70%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0)));
background: -webkit-radial-gradient(center, ellipse cover, rgba(0,0,0,0.15) 0%,rgba(0,0,0,0) 70%,rgba(0,0,0,0) 100%);
background: radial-gradient(ellipse at center, rgba(0,0,0,0.15) 0%,rgba(0,0,0,0) 70%,rgba(0,0,0,0) 100%);
}
/* Hide when there's no cover image or on page2+ */
.no-cover .scroll-down,
.no-cover.main-header:after,
.archive-template .scroll-down,
.archive-template .main-header:after {
display: none
}
/* Appears in the top right corner of your home page */
.blog-logo {
display: block;
float: left;
background: none !important;
border: none !important;
}
.blog-logo img {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display: block;
height: 38px;
padding: 1px 0 5px 0;
width: auto;
}
.back-button {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display: inline-block;
float: left;
height: 38px;
padding: 0 15px 0 10px;
border: transparent 1px solid;
color: #9EABB3;
text-align: center;
font-size: 12px;
text-transform: uppercase;
line-height: 35px;
border-radius: 3px;
background: rgba(0,0,0,0.1);
transition: all ease 0.3s;
}
.back-button:before {
position: relative;
bottom: -2px;
font-size: 13px;
line-height: 0;
margin-right: 8px;
}
.subscribe-button {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display: inline-block;
float: right;
height: 38px;
padding: 0 20px;
border: transparent 1px solid;
color: #9EABB3;
text-align: center;
font-size: 12px;
text-transform: uppercase;
line-height: 35px;
white-space: nowrap;
border-radius: 3px;
background: rgba(0,0,0,0.1);
transition: all ease 0.3s;
}
.subscribe-button:before {
font-size: 9px;
margin-right: 6px;
}
/* Special styles when overlaid on an image*/
.main-nav.overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 70px;
border: none;
background: -moz-linear-gradient(top, rgba(0,0,0,0.2) 0%, rgba(0,0,0,0) 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(0,0,0,0.2)), color-stop(100%,rgba(0,0,0,0)));
background: -webkit-linear-gradient(top, rgba(0,0,0,0.2) 0%,rgba(0,0,0,0) 100%);
background: linear-gradient(to bottom, rgba(0,0,0,0.2) 0%,rgba(0,0,0,0) 100%);
}
.no-cover .main-nav.overlay,
.no-cover .back-button,
.no-cover .subscribe-button {
background: none;
}
.main-nav.overlay a {
color: #fff;
}
.main-nav.overlay .back-button,
.main-nav.overlay .subscribe-button {
border-color: rgba(255,255,255,0.6);
}
.main-nav.overlay a:hover {
color: #222;
border-color: #fff;
background: #fff;
transition: all 0.1s ease;
}
/* Add a border to the buttons on hover */
.back-button:hover,
.subscribe-button:hover {
border-color: #bfc8cd;
color: #9EABB3;
}
/* The details of your blog. Defined in ghost/settings/ */
.page-title {
margin: 10px 0 10px 0;
font-size: 5rem;
letter-spacing: -1px;
font-weight: 700;
font-family: "Open Sans", sans-serif;
color: #fff;
}
.page-description {
margin: 0;
font-size: 2rem;
line-height: 1.5em;
font-weight: 400;
font-family: "Merriweather", serif;
letter-spacing: 0.01rem;
color: rgba(255,255,255,0.8);
}
.no-cover.main-header {
min-height: 160px;
max-height: 40%;
background: #f5f8fa;
}
.no-cover .page-title {
color: rgba(0,0,0,0.8);
}
.no-cover .page-description {
color: rgba(0,0,0,0.5);
}
.no-cover .main-nav.overlay .back-button,
.no-cover .main-nav.overlay .subscribe-button {
color: rgba(0,0,0,0.4);
border-color: rgba(0,0,0,0.3);
}
/* Add subtle load-in animation for content on the home page */
.home-template .page-title {
-webkit-animation: fade-in-down 0.6s;
animation: fade-in-down 0.6s;
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s;
}
.home-template .page-description {
-webkit-animation: fade-in-down 0.9s;
animation: fade-in-down 0.9s;
-webkit-animation-delay: 0.1s;
animation-delay: 0.1s;
}
/* Every post, on every page, gets this style on its <article> tag */
.post {
position: relative;
width: 80%;
max-width: 710px;
margin: 4rem auto;
padding-bottom: 4rem;
word-break: break-word;
hyphens: auto;
}
body:not(.post-template) .post-title {
font-size: 3.6rem;
}
.post-title a {
text-decoration: none;
}
.post-excerpt p {
margin: 0;
font-size: 0.9em;
line-height: 1.7em;
}
.read-more {
text-decoration: none;
}
.post-meta {
display: block;
margin: 1.75rem 0 0 0;
font-family: "Open Sans", sans-serif;
font-size: 1.5rem;
line-height: 2.2rem;
color: #9EABB3;
}
.author-thumb {
width: 24px;
height: 24px;
float: left;
margin-right: 9px;
border-radius: 100%;
}
.post-meta a {
color: #9EABB3;
text-decoration: none;
}
.post-meta a:hover {
text-decoration: underline;
}
.user-meta {
position: relative;
padding: 0.3rem 40px 0 100px;
min-height: 77px;
}
.post-date {
display: inline-block;
margin-left: 8px;
padding-left: 12px;
border-left: #d5dbde 1px solid;
text-transform: uppercase;
font-size: 1.3rem;
white-space: nowrap;
}
.user-image {
position: absolute;
top: 0;
left: 0;
}
.user-name {
display: block;
font-weight: 700;
}
.user-bio {
display: block;
max-width: 440px;
font-size: 1.4rem;
line-height: 1.5em;
}
.publish-meta {
position: absolute;
top: 0;
right: 0;
padding: 4.3rem 0 4rem 0;
text-align: right;
}
.publish-heading {
display: block;
font-weight: 700;
}
.publish-date {
display: block;
font-size: 1.4rem;
line-height: 1.5em;
}
/* ==========================================================================
5. Single Post - When you click on an individual post
========================================================================== */
.post-template .post-header {
margin-bottom: 3.4rem;
}
.post-template .post-title {
margin-bottom: 0;
}
.post-template .post-meta {
margin: 0;
}
.post-template .post-date {
padding: 0;
margin: 0;
border: none;
}
/* Stop .full-img from creating horizontal scroll - slight hack due to
imperfections with browser width % calculations and rounding */
.post-template .content {
overflow: hidden;
}
/* Tweak the .post wrapper style */
.post-template .post {
margin-top: 0;
border-bottom: none;
padding-bottom: 0;
}
/* Kill that stylish little circle that was on the border, too */
.post-template .post:after {
display: none;
}
/* Keep images centred and within the bounds of the post-width */
.post-content img {
display: block;
max-width: 100%;
height: auto;
margin: 0 auto;
padding: 0.6em 0;
}
/* Break out larger images to be wider than the main text column
the class is applied with jQuery */
.post-content .full-img {
width: 126%;
max-width: none;
margin: 0 -13%;
}
/* The author credit area after the post */
.author-footer {
position: relative;
margin: 6rem 0;
padding: 4rem 4rem 2rem 4rem;
border-top: #EBF2F6 1px solid;
word-break: break-word;
hyphens: auto;
}
.post-footer h4,
.author-footer h4 {
font-size: 1.8rem;
margin: 0;
}
.author-footer p {
margin: 1rem 0;
font-size: 1.4rem;
line-height: 1.75em;
}
/* list of author links - location / url */
.author-meta {
padding: 0;
margin: 0;
list-style: none;
font-size: 1.4rem;
line-height: 1;
font-style: italic;
color: #9EABB3;
}
.author-meta a {
color: #9EABB3;
}
.author-meta a:hover {
color: #111;
}
/* Create some space to the right for the share links */
.author-footer .author {
float: left;
}
.author-footer h4 a {
color: #2e2e2e;
text-decoration: none;
}
.author-footer h4 a:hover {
text-decoration: underline;
}
/* Drop the share links in the space to the right.
Doing it like this means it's easier for the author bio
to be flexible at smaller screen sizes while the share
links remain at a fixed width the whole time */
.author-footer .connect {
position: absolute;
top: 4rem;
right: 0;
width: 140px;
}
.post-footer .share a,
.author-footer .connect a {
font-size: 1.8rem;
display: inline-block;
margin: 1rem 1.6rem 1.6rem 0;
color: #999;
text-decoration: none;
}
.post-footer .share a:hover,
.author-footer .connect a:hover {
color: #111;
}
.social {
float: right;
}
.social .icon {
margin: 1rem 1.6rem 1.6rem 0;
color: #999;
text-decoration: none;
}
.social .icon:hover {
color: #111;
}
.share {
float: left;
}
/* The subscribe icon on the footer */
.subscribe {
width: 28px;
height: 28px;
position: absolute;
top: -14px;
left: 50%;
margin-left: -15px;
border: #EBF2F6 1px solid;
text-align: center;
line-height: 2.4rem;
border-radius: 50px;
background: #FFF;
transition: box-shadow 0.5s;
}
/* The RSS icon, inserted via icon font */
.subscribe:before {
color: #D2DEE3;
font-size: 10px;
position: absolute;
top: 2px;
left: 9px;
font-weight: 700;
transition: color 0.5s ease;
}
/* Add a box shadow to on hover */
.subscribe:hover {
box-shadow: rgba(0,0,0,0.05) 0 0 0 3px;
transition: box-shadow 0.25s;
}
.subscribe:hover:before {
color: #50585D;
}
/* CSS tooltip saying "Subscribe!" - initially hidden */
.tooltip {
opacity: 0;
display: block;
width: 53px;
padding: 4px 8px 5px 8px;
position:absolute;
top: -23px;
left: -21px;
color: rgba(255,255,255,0.9);
font-size: 1.1rem;
line-height: 1em;
text-align: center;
background: #50585D;
border-radius: 20px;
box-shadow: 0 1px 4px rgba(0,0,0,0.1);
transition: opacity 0.3s ease, top 0.3s ease;
}
/* The little chiclet arrow under the tooltip, pointing down */
.tooltip:after {
content: " ";
border-width: 5px 5px 0 5px;
border-style: solid;
border-color: #50585D transparent;
display: block;
position: absolute;
bottom: -4px;
left: 50%;
margin-left: -5px;
z-index: 220;
width: 0;
}
/* On hover, show the tooltip! */
.subscribe:hover .tooltip {
opacity: 1;
top: -33px;
}
/* ==========================================================================
6. Author profile
========================================================================== */
.post-head.main-header {
height: 65%;
min-height: 180px;
}
.no-cover.post-head.main-header {
height: 85px;
min-height: 0;
margin-bottom: 0;
background: transparent;
}
.tag-head.main-header {
height: 40%;
min-height: 180px;
}
.author-head.main-header {
height: 40%;
min-height: 180px;
}
.no-cover.author-head.main-header {
height: 10%;
min-height: 100px;
background: transparent;
}
.author-profile {
padding: 0 15px 5rem 15px;
border-bottom: #EBF2F6 1px solid;
text-align: center;
}
/* Add a little circle in the middle of the border-bottom */
.author-profile:after {
display: block;
content: "";
width: 7px;
height: 7px;
border: #E7EEF2 1px solid;
position: absolute;
bottom: -5px;
left: 50%;
margin-left: -5px;
background: #FFF;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
border-radius: 100%;
box-shadow: #FFF 0 0 0 5px;
}
.author-image {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
display: block;
position: absolute;
top: -40px;
left: 50%;
margin-left: -40px;
width: 80px;
height: 80px;
border-radius: 100%;
overflow: hidden;
padding: 6px;
background: #fff;
z-index: 2;
box-shadow: #E7EEF2 0 0 0 1px;
}
.author-image .img {
position: relative;
display: block;
width: 100%;
height: 100%;
background-size: cover;
background-position: center center;
border-radius: 100%;
}
.author-profile .author-image {
position: relative;
left: auto;
top: auto;
width: 120px;
height: 120px;
padding: 3px;
margin: -100px auto 0 auto;
box-shadow: none;
}
.author-title {
margin: 1.5rem 0 1rem;
}
.author-bio {
font-size: 1.8rem;
line-height: 1.5em;
font-weight: 200;
color: #50585D;
letter-spacing: 0;
text-indent: 0;
}
.author-meta {
margin: 1.6rem 0;
}
/* Location, website, and link */
.author-profile .author-meta {
margin: 2rem 0;
font-family: "Merriweather", serif;
letter-spacing: 0.01rem;
font-size: 1.7rem;
}
.author-meta span {
display: inline-block;
margin: 0 2rem 1rem 0;
word-wrap: break-word;
}
.author-meta a {
text-decoration: none;
}
/* Turn off meta for page2+ to make room for extra
pagination prev/next links */
.archive-template .author-profile .author-meta {
display: none;
}
/* ==========================================================================
7. Third Party Elements - Embeds from other services
========================================================================== */
/* Github */
.gist table {
margin: 0;
font-size: 1.4rem;
}
.gist .line-number {
min-width: 25px;
font-size: 1.1rem;
}
/* ==========================================================================
8. Pagination - Tools to let you flick between pages
========================================================================== */
/* The main wrapper for our pagination links */
.pagination {
position: relative;
width: 80%;
max-width: 710px;
margin: 4rem auto;
font-family: "Open Sans", sans-serif;
font-size: 1.3rem;
color: #9EABB3;
text-align: center;
}
.pagination a {
color: #9EABB3;
transition: all 0.2s ease;
}
/* Push the previous/next links out to the left/right */
.older-posts,
.newer-posts {
position: absolute;
display: inline-block;
padding: 0 15px;
border: #bfc8cd 1px solid;
text-decoration: none;
border-radius: 4px;
transition: border ease 0.3s;
}
.older-posts {
right: 0;
}
.page-number {
display: inline-block;
padding: 2px 0;
min-width: 100px;
}
.newer-posts {
left: 0;
}
.older-posts:hover,
.newer-posts:hover {
color: #889093;
border-color: #98a0a4;
}
.extra-pagination {
display: none;
border-bottom: #EBF2F6 1px solid;
}
.extra-pagination:after {
display: block;
content: "";
width: 7px;
height: 7px;
border: #E7EEF2 1px solid;
position: absolute;
bottom: -5px;
left: 50%;
margin-left: -5px;
background: #FFF;
-webkit-border-radius: 100%;
-moz-border-radius: 100%;
border-radius: 100%;
box-shadow: #FFF 0 0 0 5px;
}
.extra-pagination .pagination {
width: auto;
}
/* On page2+ make all the headers smaller */
.archive-template .main-header {
max-height: 30%;
}
/* On page2+ show extra pagination controls at the top of post list */
.archive-template .extra-pagination {
display: block;
}
/* ==========================================================================
9. Footer - The bottom of every page
========================================================================== */
.site-footer {
position: relative;
margin: 8rem 0 0 0;
padding: 0.5rem 15px;
border-top: #EBF2F6 1px solid;
font-family: "Open Sans", sans-serif;
font-size: 1rem;
line-height: 1.75em;
color: #BBC7CC;
}
.site-footer a {
color: #BBC7CC;
text-decoration: none;
font-weight: bold;
}
.site-footer a:hover {
color: #50585D;
}
.poweredby {
display: block;
width: 45%;
float: right;
text-align: right;
}
.copyright {
display: block;
width: 45%;
float: left;
}
/* ==========================================================================
10. Media Queries - Smaller than 900px
========================================================================== */
@media only screen and (max-width: 900px) {
.main-nav {
padding: 15px;
}
blockquote {
margin-left: 0;
}
.main-header {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
height: auto;
min-height: 240px;
height: 60%;
padding: 15% 0;
}
.scroll-down,
.home-template .main-header:after { display: none; }
.archive-template .main-header {
min-height: 180px;
padding: 10% 0;
}
.blog-logo img {
padding: 4px 0;
}
.page-title {
font-size: 4rem;
letter-spacing: -1px;
}
.page-description {
font-size: 1.8rem;
line-height: 1.5em;
}
.post {
font-size: 0.95em
}
body:not(.post-template) .post-title {
font-size: 3.2rem;
}
hr {
margin: 2.4em 0;
}
ol, ul {
padding-left: 2em;
}
h1 {
font-size: 4.5rem;
text-indent: -2px;
}
h2 {
font-size: 3.6rem;
}
h3 {
font-size: 3.1rem;
}
h4 {
font-size: 2.5rem;
}
h5 {
font-size: 2.2rem;
}
h6 {
font-size: 1.8rem;
}
.author-profile {
padding-bottom: 4rem;
}
.author-profile .author-bio {
font-size: 1.6rem;
}
.author-meta span {
display: block;
margin: 1.5rem 0;
}
.author-profile .author-meta span {
font-size: 1.6rem;
}
.post-head.main-header {
height:45%;
}
.tag-head.main-header,
.author-head.main-header {
height: 30%;
}
.no-cover.post-head.main-header {
height: 55px;
padding: 0;
}
.no-cover.author-head.main-header {
padding: 0;
}
}
/* ==========================================================================
11. Media Queries - Smaller than 500px
========================================================================== */
@media only screen and (max-width: 500px) {
.main-header {
margin-bottom: 15px;
height: 40%;
}
.no-cover.main-header {
height: 30%;
}
.archive-template .main-header {
max-height: 20%;
min-height: 160px;
padding: 10% 0;
}
.main-nav {
padding: 0;
margin-bottom: 2rem;
border-bottom: #e0e4e7 1px solid;
}
.blog-logo {
padding: 10px 10px;
}
.blog-logo img {
height: 26px;
}
.back-button,
.subscribe-button {
height: 44px;
line-height: 41px;
border-radius: 0;
color: #2e2e2e;
background: transparent;
}
.back-button:hover,
.subscribe-button:hover {
border-color: #ebeef0;
color: #2e2e2e;
background: #ebeef0;
}
.back-button {
padding: 0 15px 0 10px;
}
.subscribe-button {
padding: 0 12px;
}
.main-nav.overlay a:hover {
color: #fff;
border-color: transparent;
background: transparent;
}
.no-cover .main-nav.overlay {
background: none;
}
.no-cover .main-nav.overlay .back-button,
.no-cover .main-nav.overlay .subscribe-button {
border: none;
}
.main-nav.overlay .back-button,
.main-nav.overlay .subscribe-button {
border-color: transparent;
}
.blog-logo img {
max-height: 80px;
}
.inner,
.pagination {
width: auto;
margin: 2rem auto;
}
.post {
width: auto;
margin-top: 2rem;
margin-bottom: 2rem;
margin-left: 16px;
margin-right: 16px;
padding-bottom: 2rem;
line-height: 1.65em;
}
.post-date {
display: none;
}
.post-template .post-header {
margin-bottom: 2rem;
}
.post-template .post-date {
display: inline-block;
}
hr {
margin: 1.75em 0;
}
p, ul, ol, dl {
font-size: 0.95em;
margin: 0 0 2.5rem 0;
}
.page-title {
font-size: 3rem;
}
.post-excerpt p {
font-size: 0.85em;
}
.page-description {
font-size: 1.6rem;
}
h1, h2, h3,
h4, h5, h6 {
margin: 0 0 0.3em 0;
}
h1 {
font-size: 2.8rem;
letter-spacing: -1px;
}
h2 {
font-size: 2.4rem;
letter-spacing: 0;
}
h3 {
font-size: 2.1rem;
}
h4 {
font-size: 1.9rem;
}
h5 {
font-size: 1.8rem;
}
h6 {
font-size: 1.8rem;
}
body:not(.post-template) .post-title {
font-size: 2.5rem;
}
.post-template .post {
padding-bottom: 0;
margin-bottom: 0;
}
.post-template .site-footer {
margin-top: 0;
}
.post-content img {
padding: 0;
}
.post-content .full-img {
width: auto;
width: calc(100% + 32px); /* expand with to image + margins */
margin: 0 -16px; /* get rid of margins */
min-width: 0;
max-width: 112%; /* fallback when calc doesn't work */
}
.post-meta {
font-size: 1.3rem;
margin-top: 1rem;
}
.author-footer {
padding: 5rem 0 3rem 0;
text-align: center;
}
.author-footer .author {
margin: 0 1rem 2rem 1rem;
padding: 0 0 1.6rem 0;
border-bottom: #EBF2F6 1px dashed;
}
.author-footer .connect {
position: static;
width: auto;
}
.author-footer .connect a {
margin: 1.4rem 0.8rem 0 0.8rem;
}
.author-meta li {
float: none;
margin: 0;
line-height: 1.75em;
}
.author-meta li:before {
display: none;
}
.older-posts,
.newer-posts {
position: static;
margin: 10px 0;
}
.page-number {
display: block;
}
.site-footer {
margin-top: 3rem;
}
.author-profile {
padding-bottom: 2rem;
}
.post-head.main-header {
height: 30%;
}
.tag-head.main-header,
.author-head.main-header {
height: 20%;
}
.author-profile .author-image {
margin-top: -70px;
}
.author-profile .author-meta span {
font-size: 1.4rem;
}
.archive-template .main-header .page-description {
display: none;
}
.author-footer {
margin-bottom: 0;
}
.author-footer .social {
float: none;
}
}
/* ==========================================================================
12. Animations
========================================================================== */
/* Used to fade in title/desc on the home page */
@-webkit-keyframes fade-in-down {
0% {
opacity: 0;
-webkit-transform: translateY(-10px);
transform: translateY(-10px);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
transform: translateY(0);
}
}
@keyframes fade-in-down {
0% {
opacity: 0;
-webkit-transform: translateY(-10px);
transform: translateY(-10px);
}
100% {
opacity: 1;
-webkit-transform: translateY(0);
transform: translateY(0);
}
}
/* Used to bounce .scroll-down on home page */
@-webkit-keyframes bounce {
0%, 10%, 25%, 40%, 50% {
-webkit-transform: translateY(0) rotate(-90deg);
transform: translateY(0) rotate(-90deg);
}
20% {
-webkit-transform: translateY(-10px) rotate(-90deg);
transform: translateY(-10px) rotate(-90deg);
}
30% {
-webkit-transform: translateY(-5px) rotate(-90deg);
transform: translateY(-5px) rotate(-90deg);
}
}
@keyframes bounce {
0%, 20%, 50%, 80%, 100% {
-webkit-transform: translateY(0) rotate(-90deg);
transform: translateY(0) rotate(-90deg);
}
40% {
-webkit-transform: translateY(-10px) rotate(-90deg);
transform: translateY(-10px) rotate(-90deg);
}
60% {
-webkit-transform: translateY(-5px) rotate(-90deg);
transform: translateY(-5px) rotate(-90deg);
}
}
/* ==========================================================================
End of file. Animations should be the last thing here. Do not add stuff
below this point, or it will probably fuck everything up.
========================================================================== */
| Java |
<?php namespace ibrss\Http\Requests;
class RegisterRequest extends Request {
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:8',
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
}
| Java |
package util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Taken from
* http://www.javaworld.com/article/2077578/learn-java/java-tip-76--an-alternative-to-the-deep-copy-technique.html
*
* @author David Miller (maybe)
*/
public class ObjectCloner
{
// so that nobody can accidentally create an ObjectCloner object
private ObjectCloner() {
}
// returns a deep copy of an object
static public Object deepCopy(Object oldObj) throws Exception
{
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try
{
ByteArrayOutputStream bos =
new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B
// serialize and pass the object
oos.writeObject(oldObj); // C
oos.flush(); // D
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F
// return the new object
return ois.readObject(); // G
} catch (Exception e)
{
System.out.println("Exception in ObjectCloner = " + e);
throw (e);
} finally
{
oos.close();
ois.close();
}
}
} | Java |
import java.awt.*;
public class ListFonts
{
public static void main(String[] args)
{
String[] fontNames = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
for (int i = 0; i < fontNames.length; i++)
System.out.println(fontNames[i]);
}
}
| Java |
import { Event } from "../events/Event"
import { EventDispatcher } from "../events/EventDispatcher"
import { Browser } from "../utils/Browser"
import { Byte } from "../utils/Byte"
/**
* 连接建立成功后调度。
* @eventType Event.OPEN
* */
/*[Event(name = "open", type = "laya.events.Event")]*/
/**
* 接收到数据后调度。
* @eventType Event.MESSAGE
* */
/*[Event(name = "message", type = "laya.events.Event")]*/
/**
* 连接被关闭后调度。
* @eventType Event.CLOSE
* */
/*[Event(name = "close", type = "laya.events.Event")]*/
/**
* 出现异常后调度。
* @eventType Event.ERROR
* */
/*[Event(name = "error", type = "laya.events.Event")]*/
/**
* <p> <code>Socket</code> 封装了 HTML5 WebSocket ,允许服务器端与客户端进行全双工(full-duplex)的实时通信,并且允许跨域通信。在建立连接后,服务器和 Browser/Client Agent 都能主动的向对方发送或接收文本和二进制数据。</p>
* <p>要使用 <code>Socket</code> 类的方法,请先使用构造函数 <code>new Socket</code> 创建一个 <code>Socket</code> 对象。 <code>Socket</code> 以异步方式传输和接收数据。</p>
*/
export class Socket extends EventDispatcher {
/**
* <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p>
* <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p>
* <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。</p>
*/
static LITTLE_ENDIAN: string = "littleEndian";
/**
* <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p>
* <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。有时也称之为网络字节序。</p>
* <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p>
*/
static BIG_ENDIAN: string = "bigEndian";
/**@internal */
_endian: string;
/**@private */
protected _socket: any;
/**@private */
private _connected: boolean;
/**@private */
private _addInputPosition: number;
/**@private */
private _input: any;
/**@private */
private _output: any;
/**
* 不再缓存服务端发来的数据,如果传输的数据为字符串格式,建议设置为true,减少二进制转换消耗。
*/
disableInput: boolean = false;
/**
* 用来发送和接收数据的 <code>Byte</code> 类。
*/
private _byteClass: new () => any;
/**
* <p>子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组。必须在调用 connect 或者 connectByUrl 之前进行赋值,否则无效。</p>
* <p>指定后,只有当服务器选择了其中的某个子协议,连接才能建立成功,否则建立失败,派发 Event.ERROR 事件。</p>
* @see https://html.spec.whatwg.org/multipage/comms.html#dom-websocket
*/
protocols: any = [];
/**
* 缓存的服务端发来的数据。
*/
get input(): any {
return this._input;
}
/**
* 表示需要发送至服务端的缓冲区中的数据。
*/
get output(): any {
return this._output;
}
/**
* 表示此 Socket 对象目前是否已连接。
*/
get connected(): boolean {
return this._connected;
}
/**
* <p>主机字节序,是 CPU 存放数据的两种不同顺序,包括小端字节序和大端字节序。</p>
* <p> LITTLE_ENDIAN :小端字节序,地址低位存储值的低位,地址高位存储值的高位。</p>
* <p> BIG_ENDIAN :大端字节序,地址低位存储值的高位,地址高位存储值的低位。</p>
*/
get endian(): string {
return this._endian;
}
set endian(value: string) {
this._endian = value;
if (this._input != null) this._input.endian = value;
if (this._output != null) this._output.endian = value;
}
/**
* <p>创建新的 Socket 对象。默认字节序为 Socket.BIG_ENDIAN 。若未指定参数,将创建一个最初处于断开状态的套接字。若指定了有效参数,则尝试连接到指定的主机和端口。</p>
* @param host 服务器地址。
* @param port 服务器端口。
* @param byteClass 用于接收和发送数据的 Byte 类。如果为 null ,则使用 Byte 类,也可传入 Byte 类的子类。
* @param protocols 子协议名称。子协议名称字符串,或由多个子协议名称字符串构成的数组
* @see laya.utils.Byte
*/
constructor(host: string|null = null, port: number = 0, byteClass: new () => any = null, protocols: any[]|null = null) {
super();
this._byteClass = byteClass ? byteClass : Byte;
this.protocols = protocols;
this.endian = Socket.BIG_ENDIAN;
if (host && port > 0 && port < 65535) this.connect(host, port);
}
/**
* <p>连接到指定的主机和端口。</p>
* <p>连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。</p>
* @param host 服务器地址。
* @param port 服务器端口。
*/
connect(host: string, port: number): void {
var url: string = "ws://" + host + ":" + port;
this.connectByUrl(url);
}
/**
* <p>连接到指定的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。</p>
* <p>连接成功派发 Event.OPEN 事件;连接失败派发 Event.ERROR 事件;连接被关闭派发 Event.CLOSE 事件;接收到数据派发 Event.MESSAGE 事件; 除了 Event.MESSAGE 事件参数为数据内容,其他事件参数都是原生的 HTML DOM Event 对象。</p>
* @param url 要连接的服务端 WebSocket URL。 URL 类似 ws://yourdomain:port。
*/
connectByUrl(url: string): void {
if (this._socket != null) this.close();
this._socket && this.cleanSocket();
if (!this.protocols || this.protocols.length == 0) {
this._socket = new Browser.window.WebSocket(url);
} else {
this._socket = new Browser.window.WebSocket(url, this.protocols);
}
this._socket.binaryType = "arraybuffer";
this._output = new this._byteClass();
this._output.endian = this.endian;
this._input = new this._byteClass();
this._input.endian = this.endian;
this._addInputPosition = 0;
this._socket.onopen = (e: any) => {
this._onOpen(e);
};
this._socket.onmessage = (msg: any): void => {
this._onMessage(msg);
};
this._socket.onclose = (e: any): void => {
this._onClose(e);
};
this._socket.onerror = (e: any): void => {
this._onError(e);
};
}
/**
* 清理Socket:关闭Socket链接,关闭事件监听,重置Socket
*/
cleanSocket(): void {
this.close();
this._connected = false;
this._socket.onopen = null;
this._socket.onmessage = null;
this._socket.onclose = null;
this._socket.onerror = null;
this._socket = null;
}
/**
* 关闭连接。
*/
close(): void {
if (this._socket != null) {
try {
this._socket.close();
} catch (e) {
}
}
}
/**
* @private
* 连接建立成功 。
*/
protected _onOpen(e: any): void {
this._connected = true;
this.event(Event.OPEN, e);
}
/**
* @private
* 接收到数据处理方法。
* @param msg 数据。
*/
protected _onMessage(msg: any): void {
if (!msg || !msg.data) return;
var data: any = msg.data;
if (this.disableInput && data) {
this.event(Event.MESSAGE, data);
return;
}
if (this._input.length > 0 && this._input.bytesAvailable < 1) {
this._input.clear();
this._addInputPosition = 0;
}
var pre: number = this._input.pos;
!this._addInputPosition && (this._addInputPosition = 0);
this._input.pos = this._addInputPosition;
if (data) {
if (typeof (data) == 'string') {
this._input.writeUTFBytes(data);
} else {
this._input.writeArrayBuffer(data);
}
this._addInputPosition = this._input.pos;
this._input.pos = pre;
}
this.event(Event.MESSAGE, data);
}
/**
* @private
* 连接被关闭处理方法。
*/
protected _onClose(e: any): void {
this._connected = false;
this.event(Event.CLOSE, e)
}
/**
* @private
* 出现异常处理方法。
*/
protected _onError(e: any): void {
this.event(Event.ERROR, e)
}
/**
* 发送数据到服务器。
* @param data 需要发送的数据,可以是String或者ArrayBuffer。
*/
send(data: any): void {
this._socket.send(data);
}
/**
* 发送缓冲区中的数据到服务器。
*/
flush(): void {
if (this._output && this._output.length > 0) {
var evt: any;
try {
this._socket && this._socket.send(this._output.__getBuffer().slice(0, this._output.length));
} catch (e) {
evt = e;
}
this._output.endian = this.endian;
this._output.clear();
if (evt) this.event(Event.ERROR, evt);
}
}
}
| Java |
'use strict';
module.exports = require('./is-implemented')() ?
Array.prototype.concat : require('./shim');
| Java |
#!/bin/bash
# this causes the script to exit if any line causes an error. if there are badly-behaved bits of script that you want to ignore, you can run "set +e" and then "set -e" again afterwards.
set -e
# setting the variable stylefile to be the string on the RHS of =. you can't have spaces around the =, annoyingly.
# strings are either with double-quotes "" or single quotes ''. the difference is that the double quotes will substitute variables, e.g: if stylefile="x" then "foo_${stylefile}" is "foo_x", but 'foo_${stylefile}' is just 'foo_${stylefile}'
stylefile="targeted-editing/scripts/default.style"
# what i'm trying to do here is make it so that we can run the script as if we typed: import_db.sh database input query1 query2 ... queryN
# and the variables in the script get set as: dbname="database" inputfile="input" and $*="query1 query2 ... queryN"
# $1, $2, etc... are the first, second ... arguments to the script
dbname=$1 # array[1]
inputfile=$2 # array[2]
# shift offsets the arguments, so that after running "shift 2", what used to be $3 is now $1, what used to be $4 is now $2, and so forth
shift 2
# these are totally equivalent:
# dropdb --if-exists $dbname;
# dropdb --if-exists "$dbname";
# dropdb --if-exists ${dbname};
# dropdb --if-exists "${dbname}";
dropdb --if-exists $dbname;
# replace "user" below with your user name
createdb -E UTF-8 -O user $dbname;
psql -c "create extension postgis; create extension hstore; create extension btree_gist" $dbname;
# replace "user" below with your user name and adjust the amount of RAM you wish to allocate up or down from 12000(MB)
osm2pgsql -S $stylefile -d $dbname -C 12000 -s -G -x -k -K -U user -H /tmp $inputfile;
# for (var i = 0; i < array.length; i++) {
# var query = array[i];
for query in $*; do
echo "QUERY $query against database $dbname";
# `` is like a subselect, everything between the `` characters gets executed and replaced by whatever they output
# basename is a function which returns the file part of the filename, rather than the full path. so we can write "$(basename /very/long/path/with/lots/of/slashes.txt)" and it returns "slashes.txt"
query_base=`echo "$(basename $query)" | sed 's/\.sql//'`;
# execute the query and put its results ('>') in the file called "${dbname}_${query_base}.txt", so for a database called "new_york" and a query file called "fitness.sql", the output file would be "new_york_fitness.txt"
psql -f $query --quiet -t --no-align -F , $dbname | sed "s/^/${dbname},${query_base},/" > ${dbname}_${query_base}.txt;
done
| Java |
import React from "react";
import { Link } from "@curi/react-dom";
import {
TitledPlainSection,
HashSection,
Paragraph,
CodeBlock,
Note,
IJS
} from "../../components/guide/common";
let meta = {
title: "Apollo Integration"
};
let setupMeta = {
title: "Setup",
hash: "setup"
};
let looseMeta = {
title: "Loose Pairing",
hash: "loose-pairing"
};
let prefetchMeta = {
title: "Prefetching",
hash: "prefetch"
};
let tightMeta = {
title: "Tight Pairing",
hash: "tight-pairing",
children: [prefetchMeta]
};
let contents = [setupMeta, looseMeta, tightMeta];
function ApolloGuide() {
return (
<React.Fragment>
<TitledPlainSection title={meta.title}>
<Paragraph>
<a href="https://apollographql.com">Apollo</a> is a great solution for
managing an application's data using{" "}
<a href="http://graphql.org">GraphQL</a>.
</Paragraph>
<Paragraph>
There are a few different implementation strategies for integrating
Apollo and Curi based on how tightly you want them to be paired.
</Paragraph>
<Note>
<Paragraph>
This guide only covers integration between Curi and Apollo. If you
are not already familiar with how to use Apollo, you will want to
learn that first.
</Paragraph>
<Paragraph>
Also, this guide will only be referencing Apollo's React
implementation, but the principles are the same no matter how you
render your application.
</Paragraph>
</Note>
</TitledPlainSection>
<HashSection meta={setupMeta} tag="h2">
<Paragraph>
Apollo's React package provides an <IJS>ApolloProvider</IJS> component
for accessing your Apollo client throughout the application. The{" "}
<IJS>Router</IJS> (or whatever you name the root Curi component)
should be a descendant of the <IJS>ApolloProvider</IJS> because we
don't need to re-render the <IJS>ApolloProvider</IJS> for every new
response.
</Paragraph>
<CodeBlock lang="jsx">
{`import { ApolloProvider } from "react-apollo";
import { createRouterComponent } from "@curi/react-dom";
let Router = createRouterComponent(router);
ReactDOM.render((
<ApolloProvider client={client}>
<Router>
<App />
</Router>
</ApolloProvider>
), holder);`}
</CodeBlock>
</HashSection>
<HashSection meta={looseMeta} tag="h2">
<Paragraph>
Apollo and Curi don't actually have to know about each other. Curi can
create a response without doing any data fetching and let Apollo
handle that with its <IJS>Query</IJS> component.
</Paragraph>
<CodeBlock>
{`// routes.js
import Noun from "./pages/Noun";
// nothing Apollo related in here
let routes = prepareRoutes([
{
name: 'Noun',
path: 'noun/:word',
respond: () => {
return {
body: Noun
};
}
}
]);`}
</CodeBlock>
<Paragraph>
Any location data that a query needs can be taken from the response
object. The best way to access this is to read the current{" "}
<IJS>response</IJS> from the context. This can either be done in the
component or the response can be passed down from the root app.
</Paragraph>
<CodeBlock lang="jsx">
{`import { useResponse } from "@curi/react-dom";
function App() {
let { response } = useResponse();
let { body:Body } = response;
return <Body response={response} />;
}`}
</CodeBlock>
<Paragraph>
Because we pass the <IJS>response</IJS> to the route's <IJS>body</IJS>{" "}
component, we can pass a <IJS>Query</IJS> the response's location
params using <IJS>props.response.params</IJS>.
</Paragraph>
<CodeBlock lang="jsx">
{`// pages/Nouns.js
import { Query } from "react-apollo";
let GET_NOUN = gql\`
query noun(\$word: String!) {
noun(word: $word) {
word,
type,
definition
}
}
\`;
// use the "word" param from the response props
// to query the correct data
let Noun = ({ response }) => (
<Query
query={GET_NOUN}
variables={{ word: response.params.word }}
>
{({ loading, error, data }) => {
if (loading) {
return <Loading />;
}
// ...
return (
<article>
<h1>{data.noun.word}</h1>
<Paragraph>{data.noun.definition}</Paragraph>
</article>
)
}}
</Query>
);`}
</CodeBlock>
</HashSection>
<HashSection meta={tightMeta} tag="h2">
<Paragraph>
You can use your Apollo client instance to call queries in a route's{" "}
<IJS>resolve</IJS> function. <IJS>resolve</IJS> is expected to return
a Promise, which is exactly what <IJS>client.query</IJS> returns.
Tightly pairing Curi and Apollo is mostly center around using{" "}
<IJS>resolve</IJS> to return a <IJS>client.query</IJS> call. This will
delay navigation until after a route's GraphQL data has been loaded by
Apollo.
</Paragraph>
<Paragraph>
The <IJS>external</IJS> option can be used when creating the router to
make the Apollo client accessible from routes.
</Paragraph>
<CodeBlock>
{`import client from "./apollo";
let router = createRouter(browser, routes, {
external: { client }
});`}
</CodeBlock>
<CodeBlock>
{`import { EXAMPLE_QUERY } from "./queries";
let routes = prepareRoutes([
{
name: "Example",
path: "example/:id",
resolve({ params }, external) {
return external.client.query({
query: EXAMPLE_QUERY,
variables: { id: params.id }
});
}
}
]);`}
</CodeBlock>
<Paragraph>There are two strategies for doing this.</Paragraph>
<Paragraph>
The first approach is to avoid the <IJS>Query</IJS> altogether.
Instead, you can use a route's <IJS>response</IJS> property to attach
the data fetched by Apollo directly to a response through its{" "}
<IJS>data</IJS> property.
</Paragraph>
<Paragraph>
While we know at this point that the query has executed, we should
also check <IJS>error</IJS> in the <IJS>respond</IJS> function to
ensure that the query was executed successfully.
</Paragraph>
<CodeBlock>
{`// routes.js
import GET_VERB from "./queries";
import Verb from "./pages/Verb";
export default [
{
name: "Verb",
path: "verb/:word",
resolve({ params }, external) {
return external.client.query({
query: GET_VERB,
variables: { word: params.word }
});
},
respond({ error, resolved }) {
if (error) {
// handle failed queries
}
return {
body: Verb,
data: resolved.verb.data
}
}
}
];`}
</CodeBlock>
<Paragraph>
When rendering, you can access the query data through the{" "}
<IJS>response</IJS>'s <IJS>data</IJS> property.
</Paragraph>
<CodeBlock lang="jsx">
{`// pages/Verb.js
let Verb = ({ response }) => (
<article>
<h1>{response.data.verb.word}</h1>
<Paragraph>
{response.data.verb.definition}
</Paragraph>
</article>
)`}
</CodeBlock>
<Paragraph>
The second approach is to use the <IJS>resolve</IJS> function as a way
to cache the data, but also use <IJS>Query</IJS>. With this approach,
we do not have to attach the query data to the response; we are
relying on the fact that Apollo will execute and cache the results
prior to navigation.
</Paragraph>
<CodeBlock>
{`// routes.js
import { GET_VERB } from "./queries";
export default [
{
name: "Verb",
path: "verb/:word",
resolve({ params, external }) {
// load the data so it is cached by
// your Apollo client
return external.client.query({
query: GET_VERB,
variables: { word: params.word }
});
}
}
];`}
</CodeBlock>
<Paragraph>
The route's component will render a <IJS>Query</IJS> to also call the
query. Because the query has already been executed, Apollo will grab
the data from its cache instead of re-sending a request to your
server.
</Paragraph>
<CodeBlock lang="jsx">
{`// pages/Verb.js
import { GET_VERB } from "../queries";
let Verb = ({ response }) => (
<Query
query={GET_VERB}
variables={{ word: response.params.word }}
>
{({ loading, error, data }) => {
// ...
return (
<article>
<h1>{data.verb.word}</h1>
<Paragraph>
{data.verb.definition}
</Paragraph>
</article>
);
}}
</Query>
)`}
</CodeBlock>
<HashSection meta={prefetchMeta} tag="h3">
<Paragraph>
One additional benefit of adding queries to routes using{" "}
<IJS>resolve</IJS> is that you can prefetch data for a route.
</Paragraph>
<Paragraph>
The{" "}
<Link
name="Package"
params={{ package: "interactions", version: "v2" }}
hash="prefetch"
>
<IJS>prefetch</IJS>
</Link>{" "}
interaction lets you programmatically fetch the data for a route
prior to navigating to a location.
</Paragraph>
<CodeBlock>
{`// index.js
import { prefetch } from "@curi/router";
let routes = prepareRoutes([
{
name: "Example",
path: "example/:id",
resolve({ params }, external) {
return external.client.query({
query: GET_EXAMPLES,
variables: { id: params.id }
});
}
}
]);
let router = createRouter(browser, routes);
// this will call the GET_EXAMPLES query
// and Apollo will cache the results
let exampleRoute = router.route("Example");
prefetch(exampleRoute, { params: { id: 2 }});`}
</CodeBlock>
</HashSection>
</HashSection>
</React.Fragment>
);
}
export { ApolloGuide as component, contents };
| Java |
require 'net/http'
require 'net/https'
require 'active_merchant/billing/response'
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
#
# == Description
# The Gateway class is the base class for all ActiveMerchant gateway implementations.
#
# The standard list of gateway functions that most concrete gateway subclasses implement is:
#
# * <tt>purchase(money, creditcard, options = {})</tt>
# * <tt>authorize(money, creditcard, options = {})</tt>
# * <tt>capture(money, authorization, options = {})</tt>
# * <tt>void(identification, options = {})</tt>
# * <tt>credit(money, identification, options = {})</tt>
#
# Some gateways include features for recurring billing
#
# * <tt>recurring(money, creditcard, options = {})</tt>
#
# Some gateways also support features for storing credit cards:
#
# * <tt>store(creditcard, options = {})</tt>
# * <tt>unstore(identification, options = {})</tt>
#
# === Gateway Options
# The options hash consists of the following options:
#
# * <tt>:order_id</tt> - The order number
# * <tt>:ip</tt> - The IP address of the customer making the purchase
# * <tt>:customer</tt> - The name, customer number, or other information that identifies the customer
# * <tt>:invoice</tt> - The invoice number
# * <tt>:merchant</tt> - The name or description of the merchant offering the product
# * <tt>:description</tt> - A description of the transaction
# * <tt>:email</tt> - The email address of the customer
# * <tt>:currency</tt> - The currency of the transaction. Only important when you are using a currency that is not the default with a gateway that supports multiple currencies.
# * <tt>:billing_address</tt> - A hash containing the billing address of the customer.
# * <tt>:shipping_address</tt> - A hash containing the shipping address of the customer.
#
# The <tt>:billing_address</tt>, and <tt>:shipping_address</tt> hashes can have the following keys:
#
# * <tt>:name</tt> - The full name of the customer.
# * <tt>:company</tt> - The company name of the customer.
# * <tt>:address1</tt> - The primary street address of the customer.
# * <tt>:address2</tt> - Additional line of address information.
# * <tt>:city</tt> - The city of the customer.
# * <tt>:state</tt> - The state of the customer. The 2 digit code for US and Canadian addresses. The full name of the state or province for foreign addresses.
# * <tt>:country</tt> - The [ISO 3166-1-alpha-2 code](http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm) for the customer.
# * <tt>:zip</tt> - The zip or postal code of the customer.
# * <tt>:phone</tt> - The phone number of the customer.
#
# == Implmenting new gateways
#
# See the {ActiveMerchant Guide to Contributing}[http://code.google.com/p/activemerchant/wiki/Contributing]
#
class Gateway
include PostsData
include RequiresParameters
include CreditCardFormatting
include Utils
DEBIT_CARDS = [ :switch, :solo ]
cattr_reader :implementations
@@implementations = []
def self.inherited(subclass)
super
@@implementations << subclass
end
# The format of the amounts used by the gateway
# :dollars => '12.50'
# :cents => '1250'
class_inheritable_accessor :money_format
self.money_format = :dollars
# The default currency for the transactions if no currency is provided
class_inheritable_accessor :default_currency
# The countries of merchants the gateway supports
class_inheritable_accessor :supported_countries
self.supported_countries = []
# The supported card types for the gateway
class_inheritable_accessor :supported_cardtypes
self.supported_cardtypes = []
# Indicates if the gateway supports 3D Secure authentication or not
class_inheritable_accessor :supports_3d_secure
self.supports_3d_secure = false
class_inheritable_accessor :homepage_url
class_inheritable_accessor :display_name
# The application making the calls to the gateway
# Useful for things like the PayPal build notation (BN) id fields
superclass_delegating_accessor :application_id
self.application_id = 'ActiveMerchant'
attr_reader :options
# Use this method to check if your gateway of interest supports a credit card of some type
def self.supports?(card_type)
supported_cardtypes.include?(card_type.to_sym)
end
def self.card_brand(source)
result = source.respond_to?(:brand) ? source.brand : source.type
result.to_s.downcase
end
def card_brand(source)
self.class.card_brand(source)
end
# Initialize a new gateway.
#
# See the documentation for the gateway you will be using to make sure there are no other
# required options.
def initialize(options = {})
end
# Are we running in test mode?
def test?
Base.gateway_mode == :test
end
private # :nodoc: all
def name
self.class.name.scan(/\:\:(\w+)Gateway/).flatten.first
end
def amount(money)
return nil if money.nil?
cents = if money.respond_to?(:cents)
warn "Support for Money objects is deprecated and will be removed from a future release of ActiveMerchant. Please use an Integer value in cents"
money.cents
else
money
end
if money.is_a?(String) or cents.to_i < 0
raise ArgumentError, 'money amount must be a positive Integer in cents.'
end
if self.money_format == :cents
cents.to_s
else
sprintf("%.2f", cents.to_f / 100)
end
end
def currency(money)
money.respond_to?(:currency) ? money.currency : self.default_currency
end
def requires_start_date_or_issue_number?(credit_card)
return false if card_brand(credit_card).blank?
DEBIT_CARDS.include?(card_brand(credit_card).to_sym)
end
end
end
end
| Java |
# cool (Deprecated)
**※作成時期が古く、整理もしていないので非推奨です※**
2013年に作成したJava SE 7向けライブラリ。メンテナンス予定は無し。
###util
Java SE 7向けPOJOライブラリ。
コレクション、数値計算等。
###io
Zip4jを用いたファイル操作ライブラリ。
ディレクトリと暗号化Zipファイルを透過的に扱う。
###framework
Java SE 7向けPOJOゲームライブラリ。
(入力の受け取り方法は抽象化した上で)入力結果の処理等。
###jsfml
JSFMLに依存するゲームライブラリ。
JSFMLを直接扱うユーティリティや、2Dシーングラフ等。
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DevDataControl
{
public partial class FrmObjectDataSource1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | Java |
require 'tilt/erb'
module May
class Templator
class Template
def initialize(path)
@file = File.open(path, 'r') if path
end
def path
@file.path
end
def body
return '' unless @file
@body ||= @file.read
end
end
class Generator
def initialize(bind)
@binding = bind
end
def generate(template)
Tilt::ERBTemplate.new(template.path, { trim: '<>' }).render(@binding)
end
end
def initialize(template_path, destination, bind)
@template_path, @destination, @binding = template_path, destination, bind
end
def render
template = Template.new(@template_path)
Generator.new(@binding).generate(template)
end
def write
File.open(@destination, 'w') do |f|
f.puts render
end
end
end
end
| Java |
# RGPlaceholderTextView
Subclass of UITextView which you can set Placeholder.
| Java |
/**
* before : before(el, newEl)
* Inserts a new element `newEl` just before `el`.
*
* var before = require('dom101/before');
* var newNode = document.createElement('div');
* var button = document.querySelector('#submit');
*
* before(button, newNode);
*/
function before (el, newEl) {
if (typeof newEl === 'string') {
return el.insertAdjacentHTML('beforebegin', newEl)
} else {
return el.parentNode.insertBefore(newEl, el)
}
}
module.exports = before
| Java |
<? $page_title = "Mobile Grid System" ?>
<?php include("includes/_header.php"); ?>
<style>
.example .row, .example .row .column, .example .row .columns { background: #f4f4f4; }
.example .row { margin-bottom: 10px; }
.example .row .column, .example .row .columns { background: #eee; border: 1px solid #ddd; }
@media handheld, only screen and (max-width: 767px) {
.example .row { height: auto; }
.example .row .column, .example .row .columns { margin-bottom: 10px; }
.example .row .column:last-child, .example .row .columns:last-child { margin-bottom: 0; }
}
</style>
<header>
<div class="row">
<div class="twelve columns">
<h1>Mobile Grids</h1>
<h4></h4>
</div>
</div>
</header>
<section id="mainContent" class="example">
<div class="row">
<div class="twelve columns">
<h3>On phones, columns become stacked.</h3>
<p>That means this twelve column section will be the full width, and so will the three sections you see below.</p>
</div>
</div>
<div class="row">
<div class="four columns">
<h5>Section 1</h5>
<img src="http://placehold.it/300x100" />
<p>This is a four column section (so three of them across add up to twelve). As noted above on mobile, these columns will be stacked on top of each other.</p>
</div>
<div class="four columns">
<h5>Section 2</h5>
<img src="http://placehold.it/300x100" />
<p>This is another four column section which will be stacked on top of the others. The next section though…</p>
</div>
<div class="four columns">
<h5>Section 3</h5>
<p>Here we've used a block grid (.block-grid.three-up). These are perfect for similarly sized elements that you want to present in a grid even on mobile devices. If you view this on a phone (or small browser window) you can see what we mean.</p>
<ul class="block-grid three-up">
<li>
<img src="http://placehold.it/128x128" />
</li>
<li>
<img src="http://placehold.it/128x128" />
</li>
<li>
<img src="http://placehold.it/128x128" />
</li>
<li>
<img src="http://placehold.it/128x128" />
</li>
<li>
<img src="http://placehold.it/128x128" />
</li>
<li>
<img src="http://placehold.it/128x128" />
</li>
</ul>
</div>
</div>
</section>
<?php include("includes/_footer.php"); ?>
| Java |
package astilog
import "flag"
// Flags
var (
AppName = flag.String("logger-app-name", "", "the logger's app name")
Filename = flag.String("logger-filename", "", "the logger's filename")
Verbose = flag.Bool("logger-verbose", false, "if true, then log level is debug")
)
// Formats
const (
FormatJSON = "json"
FormatText = "text"
)
// Outs
const (
OutFile = "file"
OutStdOut = "stdout"
OutSyslog = "syslog"
)
// Configuration represents the configuration of the logger
type Configuration struct {
AppName string `toml:"app_name"`
DisableColors bool `toml:"disable_colors"`
DisableTimestamp bool `toml:"disable_timestamp"`
Filename string `toml:"filename"`
FullTimestamp bool `toml:"full_timestamp"`
Format string `toml:"format"`
MessageKey string `toml:"message_key"`
Out string `toml:"out"`
TimestampFormat string `toml:"timestamp_format"`
Verbose bool `toml:"verbose"`
}
// SetHandyFlags sets handy flags
func SetHandyFlags() {
Verbose = flag.Bool("v", false, "if true, then log level is debug")
}
// FlagConfig generates a Configuration based on flags
func FlagConfig() Configuration {
return Configuration{
AppName: *AppName,
Filename: *Filename,
Verbose: *Verbose,
}
}
| Java |
<?php
require_once('../../lib/Laposta.php');
Laposta::setApiKey("JdMtbsMq2jqJdQZD9AHC");
// initialize field with list_id
$field = new Laposta_Field("BaImMu3JZA");
try {
// get field info, use field_id or email as argument
// $result will contain een array with the response from the server
$result = $field->get("iPcyYaTCkG");
print '<pre>';print_r($result);print '</pre>';
} catch (Exception $e) {
// you can use the information in $e to react to the exception
print '<pre>';print_r($e);print '</pre>';
}
?>
| Java |
import React, { PropTypes } from 'react';
import Page from './Page';
import ProjectListItem from './ProjectListItem';
import AspectContainer from './AspectContainer';
import BannerImage from './BannerImage';
import styles from './Projects.css';
const Projects = ({ projects }) => (
<Page
Hero={() =>
<AspectContainer>
<BannerImage url="https://placebear.com/900/1200" />
</AspectContainer>
}
title="Projects"
>
<div className={styles.projects}>
{projects.map(project => <ProjectListItem key={project.id} {...project} />)}
</div>
</Page>
);
Projects.propTypes = {
projects: PropTypes.arrayOf(PropTypes.object),
};
export default Projects;
| Java |
(function($) {
var FourthWallConfiguration = function() {
this.token = localStorage.getItem('token');
this.gitlab_host = localStorage.getItem('gitlab_host');
}
FourthWallConfiguration.prototype.save = function() {
localStorage.setItem('token', this.token);
localStorage.setItem('gitlab_host', this.gitlab_host);
$(this).trigger('updated');
}
var FourthWallConfigurationForm = function(form, config) {
this.form = form;
this.statusField = $('#form-status', form)
this.config = config;
this.form.submit(this.onSubmit.bind(this));
};
FourthWallConfigurationForm.prototype.updateStatus = function(string) {
this.statusField.text(string).show();
};
FourthWallConfigurationForm.prototype.onSubmit = function(e) {
var values = this.form.serializeArray();
for( var i in values ) {
this.config[values[i].name] = values[i].value;
}
this.config.save();
this.updateStatus('Data saved!');
return false;
}
var FourthWallConfigurationDisplay = function(element) {
this.configurationList = element;
};
FourthWallConfigurationDisplay.prototype.display = function(config) {
var tokenValue = $('<li>').text('Token: ' + config.token);
var hostnameValue = $('<li>').text('Hostname: ' + config.gitlab_host);
this.configurationList.empty();
this.configurationList.append(tokenValue);
this.configurationList.append(hostnameValue);
};
$(document).ready(function() {
var form = $('#fourth-wall-config');
var savedValues = $('#saved-values');
var config = new FourthWallConfiguration();
var form = new FourthWallConfigurationForm(form, config);
var configDisplay = new FourthWallConfigurationDisplay(savedValues);
configDisplay.display(config);
$(config).on('updated', function() {
configDisplay.display(config);
});
});
})(jQuery);
| Java |
<ts-form-field
[validateOnChange]="validateOnChange"
[control]="selfReference"
[hideRequiredMarker]="hideRequiredMarker"
[hint]="hint"
[id]="id"
[theme]="theme"
cdk-overlay-origin
#origin="cdkOverlayOrigin"
>
<ts-label *ngIf="label">
{{ label }}
</ts-label>
<div class="ts-autocomplete__input-wrap">
<ng-container *ngIf="allowMultiple">
<ts-chip-collection
[allowMultipleSelections]="true"
[isDisabled]="false"
[isReadonly]="false"
(tabUpdateFocus)="focusInput()"
#chipCollection="tsChipCollection"
>
<ts-chip
*ngFor="let chip of autocompleteFormControl.value; trackBy: trackByFn"
[isRemovable]="true"
[isDisabled]="isDisabled"
[value]="chip"
(remove)="autocompleteDeselectItem($event.chip)"
>{{ displayFormatter(chip) }}</ts-chip>
<input
class="ts-autocomplete__input qa-select-autocomplete-input"
[tsAutocompleteTrigger]="auto"
[reopenAfterSelection]="reopenAfterSelection"
[attr.id]="id"
[(ngModel)]="searchQuery"
[readonly]="isDisabled ? 'true' : null"
(ngModelChange)="querySubject.next($event)"
(blur)="handleInputBlur($event)"
#input
/>
</ts-chip-collection>
<ng-template *ngTemplateOutlet="spinnerTemplate"></ng-template>
</ng-container>
<ng-container *ngIf="!allowMultiple">
<input
class="ts-autocomplete__input qa-select-autocomplete-input"
[tsAutocompleteTrigger]="auto"
[attr.id]="id"
[readonly]="isDisabled ? 'true' : null"
[(ngModel)]="searchQuery"
[value]="searchQuery"
(ngModelChange)="querySubject.next($event)"
(blur)="handleInputBlur($event)"
#input
/>
<ng-template *ngTemplateOutlet="spinnerTemplate"></ng-template>
</ng-container>
</div>
</ts-form-field>
<ts-autocomplete-panel
class="ts-autocomplete"
#auto="tsAutocompletePanel"
[id]="id + '-panel'"
[options]="options"
[optionGroups]="optionGroups"
(optionSelected)="autocompleteSelectItem($event)"
>
<!-- Outlet for options passed in by consumer -->
<ng-template *ngTemplateOutlet="contentTemplate"></ng-template>
</ts-autocomplete-panel>
<ng-template #contentTemplate>
<ng-content></ng-content>
</ng-template>
<ng-template #spinnerTemplate>
<mat-progress-spinner
*ngIf="showProgress"
class="c-autocomplete__spinner c-autocomplete__spinner--{{theme}} qa-select-autocomplete-spinner"
[ngClass]="{'c-autocomplete__spinner--active': showProgress}"
diameter="21"
mode="indeterminate"
></mat-progress-spinner>
</ng-template>
| Java |
"use strict";
ace.define("ace/snippets/golang", ["require", "exports", "module"], function (require, exports, module) {
"use strict";
exports.snippetText = undefined;
exports.scope = "golang";
}); | Java |
export default {
A: [[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[4,4]],
B: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4]],
C: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
D: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4]],
E: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
F: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[0,3],[0,4]],
G: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
H: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[4,4]],
I: [[0,0],[1,0],[2,0],[3,0],[4,0],[2,1],[2,2],[2,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
J: [[4,0],[4,1],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
K: [[0,0],[4,0],[0,1],[3,1],[0,2],[1,2],[2,2],[0,3],[3,3],[0,4],[4,4]],
L: [[0,0],[0,1],[0,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
M: [[0,0],[4,0],[0,1],[1,1],[3,1],[4,1],[0,2],[2,2],[4,2],[0,3],[4,3],[0,4],[4,4]],
N: [[0,0],[4,0],[0,1],[1,1],[4,1],[0,2],[2,2],[4,2],[0,3],[3,3],[4,3],[0,4],[4,4]],
O: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
P: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[0,4]],
Q: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[3,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
R: [[0,0],[1,0],[2,0],[3,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[3,3],[0,4],[4,4]],
S: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
T: [[0,0],[1,0],[2,0],[3,0],[4,0],[2,1],[2,2],[2,3],[2,4]],
U: [[0,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
V: [[0,0],[4,0],[0,1],[4,1],[0,2],[4,2],[1,3],[3,3],[2,4]],
W: [[0,0],[4,0],[0,1],[4,1],[0,2],[2,2],[4,2],[0,3],[1,3],[3,3],[4,3],[0,4],[4,4]],
X: [[0,0],[4,0],[1,1],[3,1],[2,2],[1,3],[3,3],[0,4],[4,4]],
Y: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[2,3],[2,4]],
Z: [[0,0],[1,0],[2,0],[3,0],[4,0],[3,1],[2,2],[1,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
Å: [[2,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[1,3],[2,3],[3,3],[4,3],[0,4],[4,4]],
Ä: [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[1,3],[2,3],[3,3],[4,3],[0,4],[4,4]],
Ö: [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
0: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
1: [[1,0],[2,0],[3,0],[3,1],[3,2],[3,3],[3,4]],
2: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
3: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
4: [[0,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[4,4]],
5: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
6: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
7: [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[4,2],[4,3],[4,4]],
8: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[0,3],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
9: [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[1,2],[2,2],[3,2],[4,2],[4,3],[0,4],[1,4],[2,4],[3,4],[4,4]],
'\@': [[0,0],[1,0],[2,0],[3,0],[4,0],[0,1],[4,1],[0,2],[2,2],[3,2],[4,2],[0,3],[2,3],[4,3],[0,4],[2,4],[3,4],[4,4]],
'\#': [[1,0],[3,0],[0,1],[1,1],[2,1],[3,1],[4,1],[1,2],[3,2],[0,3],[1,3],[2,3],[3,3],[4,3],[1,4],[3,4]],
'\?': [[0,0],[1,0],[2,0],[3,0],[4,0],[4,1],[2,2],[3,2],[4,2],[2,4]],
'\%': [[0,0],[1,0],[4,0],[0,1],[1,1],[3,1],[2,2],[1,3],[3,3],[4,3],[0,4],[3,4],[4,4]],
'\/': [[4,0],[3,1],[2,2],[1,3],[0,4]],
'\+': [[2,0],[2,1],[0,2],[1,2],[2,2],[3,2],[4,2],[2,3],[2,4]],
'\-': [[1,2],[2,2],[3,2]],
'\_': [[0,4],[1,4],[2,4],[3,4],[4,4]],
'\=': [[0,1],[1,1],[2,1],[3,1],[4,1],[0,3],[1,3],[2,3],[3,3],[4,3]],
'\*': [[0,1],[2,1],[4,1],[1,2],[2,2],[3,2],[0,3],[2,3],[4,3]],
'\'': [[2,0],[2,1]],
'\"': [[1,0],[3,0],[1,1],[3,1]],
'\(': [[2,0],[1,1],[1,2],[1,3],[2,4]],
'\)': [[2,0],[3,1],[3,2],[3,3],[2,4]],
'\.': [[2,4]],
'\,': [[3,3],[2,3]],
'\;': [[2,1],[2,3],[2,4]],
'\:': [[2,1],[2,4]],
'\!': [[2,0],[2,1],[2,2],[2,4]],
'\{': [[2,0],[3,0],[2,1],[1,2],[2,2],[2,3],[2,4],[3,4]],
'\}': [[1,0],[2,0],[2,1],[2,2],[3,2],[2,3],[1,4],[2,4]],
'\]': [[1,0],[2,0],[2,1],[2,2],[2,3],[1,4],[2,4]],
'\[': [[2,0],[3,0],[2,1],[2,2],[2,3],[2,4],[3,4]],
'\^': [[2,0],[1,1],[3,1]],
'\<': [[3,0],[2,1],[1,2],[2,3],[3,4]],
'\>': [[1,0],[2,1],[3,2],[2,3],[1,4]]
} | Java |
Trace-VstsEnteringInvocation $MyInvocation
try {
. $PSScriptRoot\Get-PythonExe.ps1
$distdir = Get-VstsInput -Name "distdir" -Require
$repository = Get-VstsInput -Name "repository" -Require
$pypirc = Get-VstsInput -Name "pypirc"
$username = Get-VstsInput -Name "username"
$password = Get-VstsInput -Name "password"
$python = Get-PythonExe -Name "pythonpath"
$dependencies = Get-VstsInput -Name "dependencies"
$skipexisting = Get-VstsInput -Name "skipexisting" -AsBool -Require
$otherargs = Get-VstsInput -Name "otherargs"
if ($dependencies) {
Invoke-VstsTool $python "-m pip install $dependencies"
}
if ($repository -match '^HTTP') {
$args = "--repository-url $repository"
} else {
$args = "-r $repository"
}
if ($pypirc -and (Test-Path $pypirc -PathType Leaf)) {
$args = '{0} --config-file "{1}"' -f ($args, $pypirc)
}
if ($skipexisting) {
$args = "$args --skip-existing"
}
if ($otherargs) {
$args = "$args $otherargs"
}
try {
$env:TWINE_USERNAME = $username
$env:TWINE_PASSWORD = $password
if (Test-Path $distdir -PathType Container) {
$distdir = Join-Path $distdir '*'
}
$arguments = '-m twine upload "{0}" {1}' -f ($distdir, $args)
Invoke-VstsTool $python $arguments -RequireExitCodeZero
} finally {
$env:TWINE_USERNAME = $null
$env:TWINE_PASSWORD = $null
}
} finally {
Trace-VstsLeavingInvocation $MyInvocation
}
| Java |
<html><body>
<h4>Windows 10 x64 (19041.208) 2004</h4><br>
<h2>_VF_AVL_TREE_NODE_EX</h2>
<font face="arial"> +0x000 Base : <a href="./_VF_AVL_TREE_NODE.html">_VF_AVL_TREE_NODE</a><br>
+0x010 SessionId : Uint4B<br>
</font></body></html> | Java |
---
author: "Ana Rute Mendes"
date: 2014-04-29
title: "Dica #1"
tags: [
"CSS",
"Ghost",
]
description: "Primeira edição da newsletter Dicas de Front End. Pretendo trazer aqui, semanalmente, artigos e dicas com novidades, opiniões e discussões sobre o desenvolvimento Front-end e Web Design."
---
Olá pessoal,
Esta é a primeira edição da newsletter Dicas de Front-end. Pretendo trazer aqui, semanalmente, artigos e dicas com novidades, opiniões e discussões sobre o desenvolvimento Front-end e Web Design. Não necessariamente compartilho das opiniões dos artigos, mas se estão aqui é que no mínimo considerei as discussões importantes. Manterei o padrão de enviar o link, seguido do tempo estimado de leitura e um breve resumo (escrito por mim) de cada um.
Uma boa semana e boa leitura!
**Artigos**
[Ghost – A simples e perfeita plataforma para publicações](http://tableless.com.br/ghost-simples-e-perfeita-plataforma-para-publicacoes/" target="_blank) [6 min]
Conheça a plataforma de publicações Ghost, que está apostando em valorizar simplicidade e sofisticação para os autores de blogs.
[Pré processadores: usar ou não usar?](http://tableless.com.br/pre-processadores-usar-ou-nao-usar/" target="_blank) [5 min]
Diego Eis do portal [Tableless](http://tableless.com.br/" target="_blank) dá a sua opinião sobre usar ou não pré processadores CSS.
[Como me tornar um Desenvolvedor Front End](http://leandrooriente.com/como-me-tornar-um-desenvolvedor-front-end/" target="_blank) [8 min]
Um artigo que fala um pouco do conhecimento necessário para se tornar um bom desenvolvedor Front-End. Traz algumas referências e boas práticas para quem quer se especializar na área.
[Frontend vs Backend](http://chocoladesign.com/frontend-vs-backend" target="_blank) [4 min]
Para iniciantes: entenda a diferença entre os desenvolvedores front-end e back-end.
**Utilidade pública**
[Guia completo dos Seletores CSS3](http://maujor.com/tutorial/selsvg/tabela-seletores-CSS3.html" target="_blank)
O Maujor, nosso querido "dinossauro das CSS", fez essa super útil tabelinha pronta pra impressão com todos os seletores CSS3. Uma ótima cola pra se ter à mão.
----
Obrigada a todos que assinaram a newsletter! Dúvidas, sugestões de links e críticas serão mais que bem-vindos, só mandar um email para dicasdefrontend@gmail.com
Acha que pode ser útil pra alguém que conhece? Manda o link pra assinar também :) [dicasdefrontend.com.br](http://dicasdefrontend.com.br" target="_blank)
Abraços,
Ana Rute
| Java |
/*
* Signals.h
*
* Created on: 07.06.2017
* Author: abt674
*
*
*/
#ifndef SIGNALS_H_
#define SIGNALS_H_
//Lightbarriers and Sensor
#define INLET_IN_VAL 0b0000000000000001
#define INLET_OUT_VAL 0b0000000000000011
#define HEIGHTMEASUREMENT_IN_VAL 0b0000000000000010
#define HEIGHTMEASUREMENT_OUT_VAL 0b0000000000000110
//#define SENSOR_HEIGHT 0b0000000000000100
#define SWITCH_IN_VAL 0b0000000000001000
#define SWITCH_OUT_VAL 0b0000000000011000
#define METAL_DETECT_VAL 0b0000000000010000
#define SWITCH_OPEN_VAL 0b0000000000100000
#define SWITCH_CLOSED_VAL 0b0000000001100000
#define SLIDE_IN_VAL 0b0000000001000000
#define SLIDE_OUT_VAL 0b0000000011000000
#define OUTLET_IN_VAL 0b0000000010000000
#define OUTLET_OUT_VAL 0b0000000110000000
//Buttons
#define BUTTON_START_VAL 0b0001000000000000
#define BUTTON_STOP_VAL 0b0010000000000000
#define BUTTON_RESET_VAL 0b0100000000000000
#define BUTTON_ESTOP_IN_VAL 0b1000000000000000
#define BUTTON_ESTOP_OUT_VAL 0b1100000000000000
namespace interrupts {
enum interruptSignals : int32_t {
INLET_IN = INLET_IN_VAL,
INLET_OUT = INLET_OUT_VAL,
HEIGHTMEASUREMENT_IN = HEIGHTMEASUREMENT_IN_VAL,
HEIGHTMEASUREMENT_OUT = HEIGHTMEASUREMENT_OUT_VAL,
SWITCH_IN = SWITCH_IN_VAL,
SWITCH_OUT = SWITCH_OUT_VAL,
METAL_DETECT = METAL_DETECT_VAL,
SWITCH_OPEN = SWITCH_OPEN_VAL,
SWITCH_CLOSED = SWITCH_CLOSED_VAL,
SLIDE_IN = SLIDE_IN_VAL,
SLIDE_OUT = SLIDE_OUT_VAL,
OUTLET_IN = OUTLET_IN_VAL,
OUTLET_OUT = OUTLET_OUT_VAL,
BUTTON_START = BUTTON_START_VAL,
BUTTON_STOP = BUTTON_STOP_VAL,
BUTTON_RESET = BUTTON_RESET_VAL,
BUTTON_ESTOP_IN = BUTTON_ESTOP_IN_VAL,
BUTTON_ESTOP_OUT = BUTTON_ESTOP_OUT_VAL
};
}
#endif /* SIGNALS_H_ */
| Java |
html {
font-size: 12px;
font-family: 'Rubik', sans-serif;
}
h1,h2,h3,h4,h5,h6 {
font-family: 'Rubik Mono One',sans-serif;
}
header {
text-align: center;
}
header h1 {
margin: 0;
}
#countries-judged {
margin-bottom: 2rem;
min-height: 2rem;
}
#countries-judged.empty {
border: 1px dashed;
}
#countries-unjudged .country {
background: hsl(341, 38%, 53%);
}
#spacer {
width: 100%;
height: 2rem;
}
.country {
display: grid;
background: #b82352;
color: white;
grid-template-columns: 3rem 2rem 1fr 4rem 2fr;
grid-template-areas: "score flag name picture artist" "score flag name picture title";
grid-gap: 0rem 0.5rem;
padding: 0.2rem;
}
#judging .country {
cursor: ns-resize;
}
.country a {
color: white;
text-decoration: none;
}
.country a:hover {
text-decoration: underline;
}
.country .play {
color: lightgreen;
}
.country > * {align-self: center;}
.country ~ .country {
margin-top: 0.5rem;
}
.country .picture img {
height: 4rem;
width: 4rem;
object-fit: cover;
object-position: center;
display: block;
}
.country .points {
font-size: 2rem;
text-align: right;
}
.country .flag-icon {
height: 2rem;
line-height: 2rem;
width: 2rem;
}
body {
margin: 0;
min-height: 101vh;
}
div#app {
width: 100%;
}
.country .points {
grid-area: score;
justify-self: end;
align-self: center;
}
.country .flag {
grid-area: flag;
align-self: center;
}
.country .name {
grid-area: name;
align-self: center;
}
.country .picture {
grid-area: picture;
}
.country .artist {
grid-area: artist;
}
.country .title {
grid-area: title;
}
input#name {
font-size: 1rem;
padding: 1em;
}
#leaderboard ol {
padding: 0;
list-style: none;
}
nav {
display:flex;
}
nav button {
flex: 1;
}
button {
background: #2b282b;
border: none;
font-size: 2rem;
padding: 0.5em;
color: white;
border-top: 5px solid #2b282b;
}
button.active {
background: hsl(300, 4%, 100%);
color: #2b282b;
}
section {
background: #fafafa;
padding-top: 1rem;
padding-left: 1rem;
}
section#judging div {
padding-left: 1rem;
}
footer {
text-align: right;
padding: 0 1rem;
margin-top: 5rem;
}
@media screen and (min-width:795px) {
.country {
grid-template-columns: 3rem 2rem 1fr 8rem 2fr 2fr;
grid-template-areas: "score flag name picture artist title";
}
.country .picture img {
width: 8rem;
height: 3rem;
}
}
@media screen and (min-width: 960px) {
html {
font-size: 15px;
}
}
@media screen and (min-width: 1240px) {
html {
font-size: 15px;
}
}
@media screen and (min-width: 1490px) {
html {
font-size: 24px;
}
}
| Java |
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Plugin;
use Composer\Composer;
use Composer\EventDispatcher\EventSubscriberInterface;
use Composer\IO\IOInterface;
use Composer\Package\Package;
use Composer\Package\Version\VersionParser;
use Composer\Repository\RepositoryInterface;
use Composer\Package\AliasPackage;
use Composer\Package\PackageInterface;
use Composer\Package\Link;
use Composer\Package\LinkConstraint\VersionConstraint;
use Composer\DependencyResolver\Pool;
/**
* Plugin manager
*
* @author Nils Adermann <naderman@naderman.de>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PluginManager
{
protected $composer;
protected $io;
protected $globalComposer;
protected $versionParser;
protected $plugins = array();
protected $registeredPlugins = array();
private static $classCounter = 0;
/**
* Initializes plugin manager
*
* @param IOInterface $io
* @param Composer $composer
* @param Composer $globalComposer
*/
public function __construct(IOInterface $io, Composer $composer, Composer $globalComposer = null)
{
$this->io = $io;
$this->composer = $composer;
$this->globalComposer = $globalComposer;
$this->versionParser = new VersionParser();
}
/**
* Loads all plugins from currently installed plugin packages
*/
public function loadInstalledPlugins()
{
$repo = $this->composer->getRepositoryManager()->getLocalRepository();
$globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null;
if ($repo) {
$this->loadRepository($repo);
}
if ($globalRepo) {
$this->loadRepository($globalRepo);
}
}
/**
* Adds a plugin, activates it and registers it with the event dispatcher
*
* @param PluginInterface $plugin plugin instance
*/
public function addPlugin(PluginInterface $plugin)
{
$this->plugins[] = $plugin;
$plugin->activate($this->composer, $this->io);
if ($plugin instanceof EventSubscriberInterface) {
$this->composer->getEventDispatcher()->addSubscriber($plugin);
}
}
/**
* Gets all currently active plugin instances
*
* @return array plugins
*/
public function getPlugins()
{
return $this->plugins;
}
/**
* Load all plugins and installers from a repository
*
* Note that plugins in the specified repository that rely on events that
* have fired prior to loading will be missed. This means you likely want to
* call this method as early as possible.
*
* @param RepositoryInterface $repo Repository to scan for plugins to install
*
* @throws \RuntimeException
*/
public function loadRepository(RepositoryInterface $repo)
{
foreach ($repo->getPackages() as $package) {
if ($package instanceof AliasPackage) {
continue;
}
if ('composer-plugin' === $package->getType()) {
$requiresComposer = null;
foreach ($package->getRequires() as $link) {
if ($link->getTarget() == 'composer-plugin-api') {
$requiresComposer = $link->getConstraint();
}
}
if (!$requiresComposer) {
throw new \RuntimeException("Plugin ".$package->getName()." is missing a require statement for a version of the composer-plugin-api package.");
}
if (!$requiresComposer->matches(new VersionConstraint('==', $this->versionParser->normalize(PluginInterface::PLUGIN_API_VERSION)))) {
$this->io->write("<warning>The plugin ".$package->getName()." requires a version of composer-plugin-api that does not match your composer installation. You may need to run composer update with the '--no-plugins' option.</warning>");
}
$this->registerPackage($package);
}
// Backward compatibility
if ('composer-installer' === $package->getType()) {
$this->registerPackage($package);
}
}
}
/**
* Recursively generates a map of package names to packages for all deps
*
* @param Pool $pool Package pool of installed packages
* @param array $collected Current state of the map for recursion
* @param PackageInterface $package The package to analyze
*
* @return array Map of package names to packages
*/
protected function collectDependencies(Pool $pool, array $collected, PackageInterface $package)
{
$requires = array_merge(
$package->getRequires(),
$package->getDevRequires()
);
foreach ($requires as $requireLink) {
$requiredPackage = $this->lookupInstalledPackage($pool, $requireLink);
if ($requiredPackage && !isset($collected[$requiredPackage->getName()])) {
$collected[$requiredPackage->getName()] = $requiredPackage;
$collected = $this->collectDependencies($pool, $collected, $requiredPackage);
}
}
return $collected;
}
/**
* Resolves a package link to a package in the installed pool
*
* Since dependencies are already installed this should always find one.
*
* @param Pool $pool Pool of installed packages only
* @param Link $link Package link to look up
*
* @return PackageInterface|null The found package
*/
protected function lookupInstalledPackage(Pool $pool, Link $link)
{
$packages = $pool->whatProvides($link->getTarget(), $link->getConstraint());
return (!empty($packages)) ? $packages[0] : null;
}
/**
* Register a plugin package, activate it etc.
*
* If it's of type composer-installer it is registered as an installer
* instead for BC
*
* @param PackageInterface $package
* @param bool $failOnMissingClasses By default this silently skips plugins that can not be found, but if set to true it fails with an exception
*
* @throws \UnexpectedValueException
*/
public function registerPackage(PackageInterface $package, $failOnMissingClasses = false)
{
$oldInstallerPlugin = ($package->getType() === 'composer-installer');
if (in_array($package->getName(), $this->registeredPlugins)) {
return;
}
$extra = $package->getExtra();
if (empty($extra['class'])) {
throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.');
}
$classes = is_array($extra['class']) ? $extra['class'] : array($extra['class']);
$localRepo = $this->composer->getRepositoryManager()->getLocalRepository();
$globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null;
$pool = new Pool('dev');
$pool->addRepository($localRepo);
if ($globalRepo) {
$pool->addRepository($globalRepo);
}
$autoloadPackages = array($package->getName() => $package);
$autoloadPackages = $this->collectDependencies($pool, $autoloadPackages, $package);
$generator = $this->composer->getAutoloadGenerator();
$autoloads = array();
foreach ($autoloadPackages as $autoloadPackage) {
$downloadPath = $this->getInstallPath($autoloadPackage, ($globalRepo && $globalRepo->hasPackage($autoloadPackage)));
$autoloads[] = array($autoloadPackage, $downloadPath);
}
$map = $generator->parseAutoloads($autoloads, new Package('dummy', '1.0.0.0', '1.0.0'));
$classLoader = $generator->createLoader($map);
$classLoader->register();
foreach ($classes as $class) {
if (class_exists($class, false)) {
$code = file_get_contents($classLoader->findFile($class));
$code = preg_replace('{^(\s*)class\s+(\S+)}mi', '$1class $2_composer_tmp'.self::$classCounter, $code);
eval('?>'.$code);
$class .= '_composer_tmp'.self::$classCounter;
self::$classCounter++;
}
if ($oldInstallerPlugin) {
$installer = new $class($this->io, $this->composer);
$this->composer->getInstallationManager()->addInstaller($installer);
} elseif (class_exists($class)) {
$plugin = new $class();
$this->addPlugin($plugin);
$this->registeredPlugins[] = $package->getName();
} elseif ($failOnMissingClasses) {
throw new \UnexpectedValueException('Plugin '.$package->getName().' could not be initialized, class not found: '.$class);
}
}
}
/**
* Retrieves the path a package is installed to.
*
* @param PackageInterface $package
* @param bool $global Whether this is a global package
*
* @return string Install path
*/
public function getInstallPath(PackageInterface $package, $global = false)
{
if (!$global) {
return $this->composer->getInstallationManager()->getInstallPath($package);
}
return $this->globalComposer->getInstallationManager()->getInstallPath($package);
}
}
| Java |
export default {
modules: require('glob!./glob.txt'),
options: {
name: 'Comment',
},
info: true,
utils: {},
};
| Java |
using Content.Shared.Sound;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Storage.Components
{
/// <summary>
/// Allows locking/unlocking, with access determined by AccessReader
/// </summary>
[RegisterComponent]
public sealed class LockComponent : Component
{
[ViewVariables(VVAccess.ReadWrite)] [DataField("locked")] public bool Locked { get; set; } = true;
[ViewVariables(VVAccess.ReadWrite)] [DataField("lockOnClick")] public bool LockOnClick { get; set; } = false;
[ViewVariables(VVAccess.ReadWrite)] [DataField("unlockingSound")] public SoundSpecifier UnlockSound { get; set; } = new SoundPathSpecifier("/Audio/Machines/door_lock_off.ogg");
[ViewVariables(VVAccess.ReadWrite)] [DataField("lockingSound")] public SoundSpecifier LockSound { get; set; } = new SoundPathSpecifier("/Audio/Machines/door_lock_off.ogg");
}
}
| Java |
// Copyright 2008 Adrian Akison
// Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx
using System;
using System.Collections.Generic;
using System.Text;
namespace RaidScheduler.Domain.DomainModels.Combinations
{
/// <summary>
/// Interface for Permutations, Combinations and any other classes that present
/// a collection of collections based on an input collection. The enumerators that
/// this class inherits defines the mechanism for enumerating through the collections.
/// </summary>
/// <typeparam name="T">The of the elements in the collection, not the type of the collection.</typeparam>
interface IMetaCollection<T> : IEnumerable<IList<T>> {
/// <summary>
/// The count of items in the collection. This is not inherited from
/// ICollection since this meta-collection cannot be extended by users.
/// </summary>
long Count { get; }
/// <summary>
/// The type of the meta-collection, determining how the collections are
/// determined from the inputs.
/// </summary>
GenerateOption Type { get; }
/// <summary>
/// The upper index of the meta-collection, which is the size of the input collection.
/// </summary>
int UpperIndex { get; }
/// <summary>
/// The lower index of the meta-collection, which is the size of each output collection.
/// </summary>
int LowerIndex { get; }
}
}
| Java |
using DragonSpark.Model.Results;
namespace DragonSpark.Application.Security.Identity;
public interface IUsers<T> : IResult<UsersSession<T>> where T : class {} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.